target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
app/components/Page/PageTitle.js
barbalex/kapla3
import React from 'react' import PropTypes from 'prop-types' import { FormGroup, FormControl } from 'react-bootstrap' import { observer, inject } from 'mobx-react' import compose from 'recompose/compose' import withHandlers from 'recompose/withHandlers' import styled from 'styled-components' const Container = styled.div` @media print { page-break-before: avoid !important; page-break-after: avoid !important; page-break-inside: avoid !important; } ` const StyledTitleInput = styled(FormControl)` margin-top: 3px; margin-bottom: 7px; ` const StyledTitle = styled.div` cursor: pointer; margin-top: 0; font-weight: 700; font-size: 32px; padding-left: 5px; @media print { page-break-before: avoid !important; page-break-after: avoid !important; page-break-inside: avoid !important; } ` const enhance = compose( inject('store'), withHandlers({ onClickH1: props => () => props.store.pagesQueryTitle(true), onKeyPressTitle: props => e => { const { pagesQueryTitle } = props.store const { title } = props.store.pages if (e.key === 'Enter' && title) { pagesQueryTitle(false) } }, onBlurTitle: props => () => { const { pagesQueryTitle } = props.store const { title } = props.store.pages if (title) pagesQueryTitle(false) }, changeQueryTitle: props => e => props.store.pagesSetTitle(e.target.value), }), observer, ) const Page = ({ store, firstPage, onClickH1, onKeyPressTitle, onBlurTitle, changeQueryTitle }) => ( <Container> {firstPage && store.pages.queryTitle && ( <FormGroup> <StyledTitleInput type="text" value={store.pages.title} placeholder="Titel erfassen" onChange={changeQueryTitle} onKeyPress={onKeyPressTitle} onBlur={onBlurTitle} bsSize="large" autoFocus /> </FormGroup> )} {firstPage && !store.pages.queryTitle && ( <StyledTitle // eslint-disable-line jsx-a11y/no-static-element-interactions onClick={onClickH1} > {store.pages.title} </StyledTitle> )} </Container> ) Page.propTypes = { store: PropTypes.object.isRequired, firstPage: PropTypes.bool.isRequired, onClickH1: PropTypes.func.isRequired, onKeyPressTitle: PropTypes.func.isRequired, onBlurTitle: PropTypes.func.isRequired, changeQueryTitle: PropTypes.func.isRequired, } export default enhance(Page)
front/src/components/Comment.js
muhammad-awan/financial-news
import React from 'react' export default function Comment({ _id, text // commentBy }){ return( <div> <p>{ text }</p> </div> ) }
ajax/libs/shariff/1.19.0/shariff.complete.js
tholu/cdnjs
/*! * shariff - v1.19.0 - 20.10.2015 * https://github.com/heiseonline/shariff * Copyright (c) 2015 Ines Pauer, Philipp Busse, Sebastian Hilbig, Erich Kramer, Deniz Sesli * Licensed under the MIT license */ (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ (function (global){ !function(e){function o(e){throw RangeError(T[e])}function n(e,o){for(var n=e.length,r=[];n--;)r[n]=o(e[n]);return r}function r(e,o){var r=e.split("@"),t="";r.length>1&&(t=r[0]+"@",e=r[1]),e=e.replace(S,".");var u=e.split("."),i=n(u,o).join(".");return t+i}function t(e){for(var o,n,r=[],t=0,u=e.length;u>t;)o=e.charCodeAt(t++),o>=55296&&56319>=o&&u>t?(n=e.charCodeAt(t++),56320==(64512&n)?r.push(((1023&o)<<10)+(1023&n)+65536):(r.push(o),t--)):r.push(o);return r}function u(e){return n(e,function(e){var o="";return e>65535&&(e-=65536,o+=P(e>>>10&1023|55296),e=56320|1023&e),o+=P(e)}).join("")}function i(e){return 10>e-48?e-22:26>e-65?e-65:26>e-97?e-97:b}function f(e,o){return e+22+75*(26>e)-((0!=o)<<5)}function c(e,o,n){var r=0;for(e=n?M(e/j):e>>1,e+=M(e/o);e>L*C>>1;r+=b)e=M(e/L);return M(r+(L+1)*e/(e+m))}function l(e){var n,r,t,f,l,s,d,a,p,h,v=[],g=e.length,w=0,m=I,j=A;for(r=e.lastIndexOf(E),0>r&&(r=0),t=0;r>t;++t)e.charCodeAt(t)>=128&&o("not-basic"),v.push(e.charCodeAt(t));for(f=r>0?r+1:0;g>f;){for(l=w,s=1,d=b;f>=g&&o("invalid-input"),a=i(e.charCodeAt(f++)),(a>=b||a>M((x-w)/s))&&o("overflow"),w+=a*s,p=j>=d?y:d>=j+C?C:d-j,!(p>a);d+=b)h=b-p,s>M(x/h)&&o("overflow"),s*=h;n=v.length+1,j=c(w-l,n,0==l),M(w/n)>x-m&&o("overflow"),m+=M(w/n),w%=n,v.splice(w++,0,m)}return u(v)}function s(e){var n,r,u,i,l,s,d,a,p,h,v,g,w,m,j,F=[];for(e=t(e),g=e.length,n=I,r=0,l=A,s=0;g>s;++s)v=e[s],128>v&&F.push(P(v));for(u=i=F.length,i&&F.push(E);g>u;){for(d=x,s=0;g>s;++s)v=e[s],v>=n&&d>v&&(d=v);for(w=u+1,d-n>M((x-r)/w)&&o("overflow"),r+=(d-n)*w,n=d,s=0;g>s;++s)if(v=e[s],n>v&&++r>x&&o("overflow"),v==n){for(a=r,p=b;h=l>=p?y:p>=l+C?C:p-l,!(h>a);p+=b)j=a-h,m=b-h,F.push(P(f(h+j%m,0))),a=M(j/m);F.push(P(f(a,0))),l=c(r,w,u==i),r=0,++u}++r,++n}return F.join("")}function d(e){return r(e,function(e){return F.test(e)?l(e.slice(4).toLowerCase()):e})}function a(e){return r(e,function(e){return O.test(e)?"xn--"+s(e):e})}var p="object"==typeof exports&&exports&&!exports.nodeType&&exports,h="object"==typeof module&&module&&!module.nodeType&&module,v="object"==typeof global&&global;(v.global===v||v.window===v||v.self===v)&&(e=v);var g,w,x=2147483647,b=36,y=1,C=26,m=38,j=700,A=72,I=128,E="-",F=/^xn--/,O=/[^\x20-\x7E]/,S=/[\x2E\u3002\uFF0E\uFF61]/g,T={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},L=b-y,M=Math.floor,P=String.fromCharCode;if(g={version:"1.3.2",ucs2:{decode:t,encode:u},decode:l,encode:s,toASCII:a,toUnicode:d},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return g});else if(p&&h)if(module.exports==p)h.exports=g;else for(w in g)g.hasOwnProperty(w)&&(p[w]=g[w]);else e.punycode=g}(this); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],2:[function(require,module,exports){ "use strict";function hasOwnProperty(r,e){return Object.prototype.hasOwnProperty.call(r,e)}module.exports=function(r,e,t,n){e=e||"&",t=t||"=";var o={};if("string"!=typeof r||0===r.length)return o;var a=/\+/g;r=r.split(e);var s=1e3;n&&"number"==typeof n.maxKeys&&(s=n.maxKeys);var p=r.length;s>0&&p>s&&(p=s);for(var y=0;p>y;++y){var u,c,i,l,f=r[y].replace(a,"%20"),v=f.indexOf(t);v>=0?(u=f.substr(0,v),c=f.substr(v+1)):(u=f,c=""),i=decodeURIComponent(u),l=decodeURIComponent(c),hasOwnProperty(o,i)?isArray(o[i])?o[i].push(l):o[i]=[o[i],l]:o[i]=l}return o};var isArray=Array.isArray||function(r){return"[object Array]"===Object.prototype.toString.call(r)}; },{}],3:[function(require,module,exports){ "use strict";function map(r,e){if(r.map)return r.map(e);for(var t=[],n=0;n<r.length;n++)t.push(e(r[n],n));return t}var stringifyPrimitive=function(r){switch(typeof r){case"string":return r;case"boolean":return r?"true":"false";case"number":return isFinite(r)?r:"";default:return""}};module.exports=function(r,e,t,n){return e=e||"&",t=t||"=",null===r&&(r=void 0),"object"==typeof r?map(objectKeys(r),function(n){var i=encodeURIComponent(stringifyPrimitive(n))+t;return isArray(r[n])?map(r[n],function(r){return i+encodeURIComponent(stringifyPrimitive(r))}).join(e):i+encodeURIComponent(stringifyPrimitive(r[n]))}).join(e):n?encodeURIComponent(stringifyPrimitive(n))+t+encodeURIComponent(stringifyPrimitive(r)):""};var isArray=Array.isArray||function(r){return"[object Array]"===Object.prototype.toString.call(r)},objectKeys=Object.keys||function(r){var e=[];for(var t in r)Object.prototype.hasOwnProperty.call(r,t)&&e.push(t);return e}; },{}],4:[function(require,module,exports){ "use strict";exports.decode=exports.parse=require("./decode"),exports.encode=exports.stringify=require("./encode"); },{"./decode":2,"./encode":3}],5:[function(require,module,exports){ function Url(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function urlParse(t,s,e){if(t&&isObject(t)&&t instanceof Url)return t;var h=new Url;return h.parse(t,s,e),h}function urlFormat(t){return isString(t)&&(t=urlParse(t)),t instanceof Url?t.format():Url.prototype.format.call(t)}function urlResolve(t,s){return urlParse(t,!1,!0).resolve(s)}function urlResolveObject(t,s){return t?urlParse(t,!1,!0).resolveObject(s):s}function isString(t){return"string"==typeof t}function isObject(t){return"object"==typeof t&&null!==t}function isNull(t){return null===t}function isNullOrUndefined(t){return null==t}var punycode=require("punycode");exports.parse=urlParse,exports.resolve=urlResolve,exports.resolveObject=urlResolveObject,exports.format=urlFormat,exports.Url=Url;var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,delims=["<",">",'"',"`"," ","\r","\n"," "],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=require("querystring");Url.prototype.parse=function(t,s,e){if(!isString(t))throw new TypeError("Parameter 'url' must be a string, not "+typeof t);var h=t;h=h.trim();var r=protocolPattern.exec(h);if(r){r=r[0];var o=r.toLowerCase();this.protocol=o,h=h.substr(r.length)}if(e||r||h.match(/^\/\/[^@\/]+@[^@\/]+/)){var a="//"===h.substr(0,2);!a||r&&hostlessProtocol[r]||(h=h.substr(2),this.slashes=!0)}if(!hostlessProtocol[r]&&(a||r&&!slashedProtocol[r])){for(var n=-1,i=0;i<hostEndingChars.length;i++){var l=h.indexOf(hostEndingChars[i]);-1!==l&&(-1===n||n>l)&&(n=l)}var c,u;u=-1===n?h.lastIndexOf("@"):h.lastIndexOf("@",n),-1!==u&&(c=h.slice(0,u),h=h.slice(u+1),this.auth=decodeURIComponent(c)),n=-1;for(var i=0;i<nonHostChars.length;i++){var l=h.indexOf(nonHostChars[i]);-1!==l&&(-1===n||n>l)&&(n=l)}-1===n&&(n=h.length),this.host=h.slice(0,n),h=h.slice(n),this.parseHost(),this.hostname=this.hostname||"";var p="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!p)for(var f=this.hostname.split(/\./),i=0,m=f.length;m>i;i++){var v=f[i];if(v&&!v.match(hostnamePartPattern)){for(var g="",y=0,d=v.length;d>y;y++)g+=v.charCodeAt(y)>127?"x":v[y];if(!g.match(hostnamePartPattern)){var P=f.slice(0,i),b=f.slice(i+1),j=v.match(hostnamePartStart);j&&(P.push(j[1]),b.unshift(j[2])),b.length&&(h="/"+b.join(".")+h),this.hostname=P.join(".");break}}}if(this.hostname.length>hostnameMaxLen?this.hostname="":this.hostname=this.hostname.toLowerCase(),!p){for(var O=this.hostname.split("."),q=[],i=0;i<O.length;++i){var x=O[i];q.push(x.match(/[^A-Za-z0-9_-]/)?"xn--"+punycode.encode(x):x)}this.hostname=q.join(".")}var U=this.port?":"+this.port:"",C=this.hostname||"";this.host=C+U,this.href+=this.host,p&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==h[0]&&(h="/"+h))}if(!unsafeProtocol[o])for(var i=0,m=autoEscape.length;m>i;i++){var A=autoEscape[i],E=encodeURIComponent(A);E===A&&(E=escape(A)),h=h.split(A).join(E)}var w=h.indexOf("#");-1!==w&&(this.hash=h.substr(w),h=h.slice(0,w));var R=h.indexOf("?");if(-1!==R?(this.search=h.substr(R),this.query=h.substr(R+1),s&&(this.query=querystring.parse(this.query)),h=h.slice(0,R)):s&&(this.search="",this.query={}),h&&(this.pathname=h),slashedProtocol[o]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var U=this.pathname||"",x=this.search||"";this.path=U+x}return this.href=this.format(),this},Url.prototype.format=function(){var t=this.auth||"";t&&(t=encodeURIComponent(t),t=t.replace(/%3A/i,":"),t+="@");var s=this.protocol||"",e=this.pathname||"",h=this.hash||"",r=!1,o="";this.host?r=t+this.host:this.hostname&&(r=t+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(r+=":"+this.port)),this.query&&isObject(this.query)&&Object.keys(this.query).length&&(o=querystring.stringify(this.query));var a=this.search||o&&"?"+o||"";return s&&":"!==s.substr(-1)&&(s+=":"),this.slashes||(!s||slashedProtocol[s])&&r!==!1?(r="//"+(r||""),e&&"/"!==e.charAt(0)&&(e="/"+e)):r||(r=""),h&&"#"!==h.charAt(0)&&(h="#"+h),a&&"?"!==a.charAt(0)&&(a="?"+a),e=e.replace(/[?#]/g,function(t){return encodeURIComponent(t)}),a=a.replace("#","%23"),s+r+e+a+h},Url.prototype.resolve=function(t){return this.resolveObject(urlParse(t,!1,!0)).format()},Url.prototype.resolveObject=function(t){if(isString(t)){var s=new Url;s.parse(t,!1,!0),t=s}var e=new Url;if(Object.keys(this).forEach(function(t){e[t]=this[t]},this),e.hash=t.hash,""===t.href)return e.href=e.format(),e;if(t.slashes&&!t.protocol)return Object.keys(t).forEach(function(s){"protocol"!==s&&(e[s]=t[s])}),slashedProtocol[e.protocol]&&e.hostname&&!e.pathname&&(e.path=e.pathname="/"),e.href=e.format(),e;if(t.protocol&&t.protocol!==e.protocol){if(!slashedProtocol[t.protocol])return Object.keys(t).forEach(function(s){e[s]=t[s]}),e.href=e.format(),e;if(e.protocol=t.protocol,t.host||hostlessProtocol[t.protocol])e.pathname=t.pathname;else{for(var h=(t.pathname||"").split("/");h.length&&!(t.host=h.shift()););t.host||(t.host=""),t.hostname||(t.hostname=""),""!==h[0]&&h.unshift(""),h.length<2&&h.unshift(""),e.pathname=h.join("/")}if(e.search=t.search,e.query=t.query,e.host=t.host||"",e.auth=t.auth,e.hostname=t.hostname||t.host,e.port=t.port,e.pathname||e.search){var r=e.pathname||"",o=e.search||"";e.path=r+o}return e.slashes=e.slashes||t.slashes,e.href=e.format(),e}var a=e.pathname&&"/"===e.pathname.charAt(0),n=t.host||t.pathname&&"/"===t.pathname.charAt(0),i=n||a||e.host&&t.pathname,l=i,c=e.pathname&&e.pathname.split("/")||[],h=t.pathname&&t.pathname.split("/")||[],u=e.protocol&&!slashedProtocol[e.protocol];if(u&&(e.hostname="",e.port=null,e.host&&(""===c[0]?c[0]=e.host:c.unshift(e.host)),e.host="",t.protocol&&(t.hostname=null,t.port=null,t.host&&(""===h[0]?h[0]=t.host:h.unshift(t.host)),t.host=null),i=i&&(""===h[0]||""===c[0])),n)e.host=t.host||""===t.host?t.host:e.host,e.hostname=t.hostname||""===t.hostname?t.hostname:e.hostname,e.search=t.search,e.query=t.query,c=h;else if(h.length)c||(c=[]),c.pop(),c=c.concat(h),e.search=t.search,e.query=t.query;else if(!isNullOrUndefined(t.search)){if(u){e.hostname=e.host=c.shift();var p=e.host&&e.host.indexOf("@")>0?e.host.split("@"):!1;p&&(e.auth=p.shift(),e.host=e.hostname=p.shift())}return e.search=t.search,e.query=t.query,isNull(e.pathname)&&isNull(e.search)||(e.path=(e.pathname?e.pathname:"")+(e.search?e.search:"")),e.href=e.format(),e}if(!c.length)return e.pathname=null,e.search?e.path="/"+e.search:e.path=null,e.href=e.format(),e;for(var f=c.slice(-1)[0],m=(e.host||t.host)&&("."===f||".."===f)||""===f,v=0,g=c.length;g>=0;g--)f=c[g],"."==f?c.splice(g,1):".."===f?(c.splice(g,1),v++):v&&(c.splice(g,1),v--);if(!i&&!l)for(;v--;v)c.unshift("..");!i||""===c[0]||c[0]&&"/"===c[0].charAt(0)||c.unshift(""),m&&"/"!==c.join("/").substr(-1)&&c.push("");var y=""===c[0]||c[0]&&"/"===c[0].charAt(0);if(u){e.hostname=e.host=y?"":c.length?c.shift():"";var p=e.host&&e.host.indexOf("@")>0?e.host.split("@"):!1;p&&(e.auth=p.shift(),e.host=e.hostname=p.shift())}return i=i||e.host&&c.length,i&&!y&&c.unshift(""),c.length?e.pathname=c.join("/"):(e.pathname=null,e.path=null),isNull(e.pathname)&&isNull(e.search)||(e.path=(e.pathname?e.pathname:"")+(e.search?e.search:"")),e.auth=t.auth||e.auth,e.slashes=e.slashes||t.slashes,e.href=e.format(),e},Url.prototype.parseHost=function(){var t=this.host,s=portPattern.exec(t);s&&(s=s[0],":"!==s&&(this.port=s.substr(1)),t=t.substr(0,t.length-s.length)),t&&(this.hostname=t)}; },{"punycode":1,"querystring":4}],6:[function(require,module,exports){ !function(e,t){"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){function n(e){var t="length"in e&&e.length,n=ie.type(e);return"function"===n||ie.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e}function r(e,t,n){if(ie.isFunction(t))return ie.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return ie.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(fe.test(t))return ie.filter(t,e,n);t=ie.filter(t,e)}return ie.grep(e,function(e){return ie.inArray(e,t)>=0!==n})}function i(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function o(e){var t=xe[e]={};return ie.each(e.match(be)||[],function(e,n){t[n]=!0}),t}function a(){he.addEventListener?(he.removeEventListener("DOMContentLoaded",s,!1),e.removeEventListener("load",s,!1)):(he.detachEvent("onreadystatechange",s),e.detachEvent("onload",s))}function s(){(he.addEventListener||"load"===event.type||"complete"===he.readyState)&&(a(),ie.ready())}function u(e,t,n){if(void 0===n&&1===e.nodeType){var r="data-"+t.replace(Ee,"-$1").toLowerCase();if(n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:Ne.test(n)?ie.parseJSON(n):n}catch(i){}ie.data(e,t,n)}else n=void 0}return n}function l(e){var t;for(t in e)if(("data"!==t||!ie.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,n,r){if(ie.acceptData(e)){var i,o,a=ie.expando,s=e.nodeType,u=s?ie.cache:e,l=s?e[a]:e[a]&&a;if(l&&u[l]&&(r||u[l].data)||void 0!==n||"string"!=typeof t)return l||(l=s?e[a]=J.pop()||ie.guid++:a),u[l]||(u[l]=s?{}:{toJSON:ie.noop}),("object"==typeof t||"function"==typeof t)&&(r?u[l]=ie.extend(u[l],t):u[l].data=ie.extend(u[l].data,t)),o=u[l],r||(o.data||(o.data={}),o=o.data),void 0!==n&&(o[ie.camelCase(t)]=n),"string"==typeof t?(i=o[t],null==i&&(i=o[ie.camelCase(t)])):i=o,i}}function d(e,t,n){if(ie.acceptData(e)){var r,i,o=e.nodeType,a=o?ie.cache:e,s=o?e[ie.expando]:ie.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){ie.isArray(t)?t=t.concat(ie.map(t,ie.camelCase)):t in r?t=[t]:(t=ie.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;for(;i--;)delete r[t[i]];if(n?!l(r):!ie.isEmptyObject(r))return}(n||(delete a[s].data,l(a[s])))&&(o?ie.cleanData([e],!0):ne.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}function f(){return!0}function p(){return!1}function h(){try{return he.activeElement}catch(e){}}function m(e){var t=Fe.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function g(e,t){var n,r,i=0,o=typeof e.getElementsByTagName!==Ce?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==Ce?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],n=e.childNodes||e;null!=(r=n[i]);i++)!t||ie.nodeName(r,t)?o.push(r):ie.merge(o,g(r,t));return void 0===t||t&&ie.nodeName(e,t)?ie.merge([e],o):o}function v(e){je.test(e.type)&&(e.defaultChecked=e.checked)}function y(e,t){return ie.nodeName(e,"table")&&ie.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function b(e){return e.type=(null!==ie.find.attr(e,"type"))+"/"+e.type,e}function x(e){var t=Ve.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function w(e,t){for(var n,r=0;null!=(n=e[r]);r++)ie._data(n,"globalEval",!t||ie._data(t[r],"globalEval"))}function T(e,t){if(1===t.nodeType&&ie.hasData(e)){var n,r,i,o=ie._data(e),a=ie._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)ie.event.add(t,n,s[n][r])}a.data&&(a.data=ie.extend({},a.data))}}function C(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!ne.noCloneEvent&&t[ie.expando]){i=ie._data(t);for(r in i.events)ie.removeEvent(t,r,i.handle);t.removeAttribute(ie.expando)}"script"===n&&t.text!==e.text?(b(t).text=e.text,x(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),ne.html5Clone&&e.innerHTML&&!ie.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&je.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}function N(t,n){var r,i=ie(n.createElement(t)).appendTo(n.body),o=e.getDefaultComputedStyle&&(r=e.getDefaultComputedStyle(i[0]))?r.display:ie.css(i[0],"display");return i.detach(),o}function E(e){var t=he,n=Ze[e];return n||(n=N(e,t),"none"!==n&&n||(Ke=(Ke||ie("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=(Ke[0].contentWindow||Ke[0].contentDocument).document,t.write(),t.close(),n=N(e,t),Ke.detach()),Ze[e]=n),n}function k(e,t){return{get:function(){var n=e();if(null!=n)return n?void delete this.get:(this.get=t).apply(this,arguments)}}}function S(e,t){if(t in e)return t;for(var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=ft.length;i--;)if(t=ft[i]+n,t in e)return t;return r}function A(e,t){for(var n,r,i,o=[],a=0,s=e.length;s>a;a++)r=e[a],r.style&&(o[a]=ie._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&Ae(r)&&(o[a]=ie._data(r,"olddisplay",E(r.nodeName)))):(i=Ae(r),(n&&"none"!==n||!i)&&ie._data(r,"olddisplay",i?n:ie.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}function D(e,t,n){var r=ut.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function j(e,t,n,r,i){for(var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;4>o;o+=2)"margin"===n&&(a+=ie.css(e,n+Se[o],!0,i)),r?("content"===n&&(a-=ie.css(e,"padding"+Se[o],!0,i)),"margin"!==n&&(a-=ie.css(e,"border"+Se[o]+"Width",!0,i))):(a+=ie.css(e,"padding"+Se[o],!0,i),"padding"!==n&&(a+=ie.css(e,"border"+Se[o]+"Width",!0,i)));return a}function L(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=et(e),a=ne.boxSizing&&"border-box"===ie.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=tt(e,t,o),(0>i||null==i)&&(i=e.style[t]),rt.test(i))return i;r=a&&(ne.boxSizingReliable()||i===e.style[t]),i=parseFloat(i)||0}return i+j(e,t,n||(a?"border":"content"),r,o)+"px"}function H(e,t,n,r,i){return new H.prototype.init(e,t,n,r,i)}function q(){return setTimeout(function(){pt=void 0}),pt=ie.now()}function _(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Se[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function M(e,t,n){for(var r,i=(bt[t]||[]).concat(bt["*"]),o=0,a=i.length;a>o;o++)if(r=i[o].call(n,t,e))return r}function F(e,t,n){var r,i,o,a,s,u,l,c,d=this,f={},p=e.style,h=e.nodeType&&Ae(e),m=ie._data(e,"fxshow");n.queue||(s=ie._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,u=s.empty.fire,s.empty.fire=function(){s.unqueued||u()}),s.unqueued++,d.always(function(){d.always(function(){s.unqueued--,ie.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],l=ie.css(e,"display"),c="none"===l?ie._data(e,"olddisplay")||E(e.nodeName):l,"inline"===c&&"none"===ie.css(e,"float")&&(ne.inlineBlockNeedsLayout&&"inline"!==E(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",ne.shrinkWrapBlocks()||d.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],mt.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(h?"hide":"show")){if("show"!==i||!m||void 0===m[r])continue;h=!0}f[r]=m&&m[r]||ie.style(e,r)}else l=void 0;if(ie.isEmptyObject(f))"inline"===("none"===l?E(e.nodeName):l)&&(p.display=l);else{m?"hidden"in m&&(h=m.hidden):m=ie._data(e,"fxshow",{}),o&&(m.hidden=!h),h?ie(e).show():d.done(function(){ie(e).hide()}),d.done(function(){var t;ie._removeData(e,"fxshow");for(t in f)ie.style(e,t,f[t])});for(r in f)a=M(h?m[r]:0,r,d),r in m||(m[r]=a.start,h&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function O(e,t){var n,r,i,o,a;for(n in e)if(r=ie.camelCase(n),i=t[r],o=e[n],ie.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=ie.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}function B(e,t,n){var r,i,o=0,a=yt.length,s=ie.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;for(var t=pt||q(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:ie.extend({},t),opts:ie.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:pt||q(),duration:n.duration,tweens:[],createTween:function(t,n){var r=ie.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(O(c,l.opts.specialEasing);a>o;o++)if(r=yt[o].call(l,e,c,l.opts))return r;return ie.map(c,M,l),ie.isFunction(l.opts.start)&&l.opts.start.call(e,l),ie.fx.timer(ie.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function P(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(be)||[];if(ie.isFunction(n))for(;r=o[i++];)"+"===r.charAt(0)?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function R(e,t,n,r){function i(s){var u;return o[s]=!0,ie.each(e[s]||[],function(e,s){var l=s(t,n,r);return"string"!=typeof l||a||o[l]?a?!(u=l):void 0:(t.dataTypes.unshift(l),i(l),!1)}),u}var o={},a=e===zt;return i(t.dataTypes[0])||!o["*"]&&i("*")}function W(e,t){var n,r,i=ie.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((i[r]?e:n||(n={}))[r]=t[r]);return n&&ie.extend(!0,e,n),e}function $(e,t,n){for(var r,i,o,a,s=e.contents,u=e.dataTypes;"*"===u[0];)u.shift(),void 0===i&&(i=e.mimeType||t.getResponseHeader("Content-Type"));if(i)for(a in s)if(s[a]&&s[a].test(i)){u.unshift(a);break}if(u[0]in n)o=u[0];else{for(a in n){if(!u[0]||e.converters[a+" "+u[0]]){o=a;break}r||(r=a)}o=o||r}return o?(o!==u[0]&&u.unshift(o),n[o]):void 0}function z(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];for(o=c.shift();o;)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(a=l[u+" "+o]||l["* "+o],!a)for(i in l)if(s=i.split(" "),s[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){a===!0?a=l[i]:l[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(d){return{state:"parsererror",error:a?d:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}function I(e,t,n,r){var i;if(ie.isArray(t))ie.each(t,function(t,i){n||Vt.test(e)?r(e,i):I(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==ie.type(t))r(e,t);else for(i in t)I(e+"["+i+"]",t[i],n,r)}function X(){try{return new e.XMLHttpRequest}catch(t){}}function U(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function V(e){return ie.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var J=[],Y=J.slice,G=J.concat,Q=J.push,K=J.indexOf,Z={},ee=Z.toString,te=Z.hasOwnProperty,ne={},re="1.11.3",ie=function(e,t){return new ie.fn.init(e,t)},oe=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,ae=/^-ms-/,se=/-([\da-z])/gi,ue=function(e,t){return t.toUpperCase()};ie.fn=ie.prototype={jquery:re,constructor:ie,selector:"",length:0,toArray:function(){return Y.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:Y.call(this)},pushStack:function(e){var t=ie.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return ie.each(this,e,t)},map:function(e){return this.pushStack(ie.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(Y.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Q,sort:J.sort,splice:J.splice},ie.extend=ie.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||ie.isFunction(a)||(a={}),s===u&&(a=this,s--);u>s;s++)if(null!=(i=arguments[s]))for(r in i)e=a[r],n=i[r],a!==n&&(l&&n&&(ie.isPlainObject(n)||(t=ie.isArray(n)))?(t?(t=!1,o=e&&ie.isArray(e)?e:[]):o=e&&ie.isPlainObject(e)?e:{},a[r]=ie.extend(l,o,n)):void 0!==n&&(a[r]=n));return a},ie.extend({expando:"jQuery"+(re+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===ie.type(e)},isArray:Array.isArray||function(e){return"array"===ie.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!ie.isArray(e)&&e-parseFloat(e)+1>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==ie.type(e)||e.nodeType||ie.isWindow(e))return!1;try{if(e.constructor&&!te.call(e,"constructor")&&!te.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}if(ne.ownLast)for(t in e)return te.call(e,t);for(t in e);return void 0===t||te.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?Z[ee.call(e)]||"object":typeof e},globalEval:function(t){t&&ie.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(ae,"ms-").replace(se,ue)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,r){var i,o=0,a=e.length,s=n(e);if(r){if(s)for(;a>o&&(i=t.apply(e[o],r),i!==!1);o++);else for(o in e)if(i=t.apply(e[o],r),i===!1)break}else if(s)for(;a>o&&(i=t.call(e[o],o,e[o]),i!==!1);o++);else for(o in e)if(i=t.call(e[o],o,e[o]),i===!1)break;return e},trim:function(e){return null==e?"":(e+"").replace(oe,"")},makeArray:function(e,t){var r=t||[];return null!=e&&(n(Object(e))?ie.merge(r,"string"==typeof e?[e]:e):Q.call(r,e)),r},inArray:function(e,t,n){var r;if(t){if(K)return K.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;n>r;)e[i++]=t[r++];if(n!==n)for(;void 0!==t[r];)e[i++]=t[r++];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;a>o;o++)r=!t(e[o],o),r!==s&&i.push(e[o]);return i},map:function(e,t,r){var i,o=0,a=e.length,s=n(e),u=[];if(s)for(;a>o;o++)i=t(e[o],o,r),null!=i&&u.push(i);else for(o in e)i=t(e[o],o,r),null!=i&&u.push(i);return G.apply([],u)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(i=e[t],t=e,e=i),ie.isFunction(e)?(n=Y.call(arguments,2),r=function(){return e.apply(t||this,n.concat(Y.call(arguments)))},r.guid=e.guid=e.guid||ie.guid++,r):void 0},now:function(){return+new Date},support:ne}),ie.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){Z["[object "+t+"]"]=t.toLowerCase()});var le=function(e){function t(e,t,n,r){var i,o,a,s,u,l,d,p,h,m;if((t?t.ownerDocument||t:R)!==H&&L(t),t=t||H,n=n||[],s=t.nodeType,"string"!=typeof e||!e||1!==s&&9!==s&&11!==s)return n;if(!r&&_){if(11!==s&&(i=ye.exec(e)))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&B(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return K.apply(n,t.getElementsByTagName(e)),n;if((a=i[3])&&w.getElementsByClassName)return K.apply(n,t.getElementsByClassName(a)),n}if(w.qsa&&(!M||!M.test(e))){if(p=d=P,h=t,m=1!==s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){for(l=E(e),(d=t.getAttribute("id"))?p=d.replace(xe,"\\$&"):t.setAttribute("id",p),p="[id='"+p+"'] ",u=l.length;u--;)l[u]=p+f(l[u]);h=be.test(e)&&c(t.parentNode)||t,m=l.join(",")}if(m)try{return K.apply(n,h.querySelectorAll(m)),n}catch(g){}finally{d||t.removeAttribute("id")}}}return S(e.replace(ue,"$1"),t,n,r)}function n(){function e(n,r){return t.push(n+" ")>T.cacheLength&&delete e[t.shift()],e[n+" "]=r}var t=[];return e}function r(e){return e[P]=!0,e}function i(e){var t=H.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function o(e,t){for(var n=e.split("|"),r=e.length;r--;)T.attrHandle[n[r]]=t}function a(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||V)-(~e.sourceIndex||V);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function s(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function u(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function l(e){return r(function(t){return t=+t,r(function(n,r){for(var i,o=e([],n.length,t),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function c(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function d(){}function f(e){for(var t=0,n=e.length,r="";n>t;t++)r+=e[t].value;return r}function p(e,t,n){var r=t.dir,i=n&&"parentNode"===r,o=$++;return t.first?function(t,n,o){for(;t=t[r];)if(1===t.nodeType||i)return e(t,n,o)}:function(t,n,a){var s,u,l=[W,o];if(a){for(;t=t[r];)if((1===t.nodeType||i)&&e(t,n,a))return!0}else for(;t=t[r];)if(1===t.nodeType||i){if(u=t[P]||(t[P]={}),(s=u[r])&&s[0]===W&&s[1]===o)return l[2]=s[2];if(u[r]=l,l[2]=e(t,n,a))return!0}}}function h(e){return e.length>1?function(t,n,r){for(var i=e.length;i--;)if(!e[i](t,n,r))return!1;return!0}:e[0]}function m(e,n,r){for(var i=0,o=n.length;o>i;i++)t(e,n[i],r);return r}function g(e,t,n,r,i){for(var o,a=[],s=0,u=e.length,l=null!=t;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function v(e,t,n,i,o,a){return i&&!i[P]&&(i=v(i)),o&&!o[P]&&(o=v(o,a)),r(function(r,a,s,u){var l,c,d,f=[],p=[],h=a.length,v=r||m(t||"*",s.nodeType?[s]:s,[]),y=!e||!r&&t?v:g(v,f,e,s,u),b=n?o||(r?e:h||i)?[]:a:y;if(n&&n(y,b,s,u),i)for(l=g(b,p),i(l,[],s,u),c=l.length;c--;)(d=l[c])&&(b[p[c]]=!(y[p[c]]=d));if(r){if(o||e){if(o){for(l=[],c=b.length;c--;)(d=b[c])&&l.push(y[c]=d);o(null,b=[],l,u)}for(c=b.length;c--;)(d=b[c])&&(l=o?ee(r,d):f[c])>-1&&(r[l]=!(a[l]=d))}}else b=g(b===a?b.splice(h,b.length):b),o?o(null,a,b,u):K.apply(a,b)})}function y(e){for(var t,n,r,i=e.length,o=T.relative[e[0].type],a=o||T.relative[" "],s=o?1:0,u=p(function(e){return e===t},a,!0),l=p(function(e){return ee(t,e)>-1},a,!0),c=[function(e,n,r){var i=!o&&(r||n!==A)||((t=n).nodeType?u(e,n,r):l(e,n,r));return t=null,i}];i>s;s++)if(n=T.relative[e[s].type])c=[p(h(c),n)];else{if(n=T.filter[e[s].type].apply(null,e[s].matches),n[P]){for(r=++s;i>r&&!T.relative[e[r].type];r++);return v(s>1&&h(c),s>1&&f(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace(ue,"$1"),n,r>s&&y(e.slice(s,r)),i>r&&y(e=e.slice(r)),i>r&&f(e))}c.push(n)}return h(c)}function b(e,n){var i=n.length>0,o=e.length>0,a=function(r,a,s,u,l){var c,d,f,p=0,h="0",m=r&&[],v=[],y=A,b=r||o&&T.find.TAG("*",l),x=W+=null==y?1:Math.random()||.1,w=b.length;for(l&&(A=a!==H&&a);h!==w&&null!=(c=b[h]);h++){if(o&&c){for(d=0;f=e[d++];)if(f(c,a,s)){u.push(c);break}l&&(W=x)}i&&((c=!f&&c)&&p--,r&&m.push(c))}if(p+=h,i&&h!==p){for(d=0;f=n[d++];)f(m,v,a,s);if(r){if(p>0)for(;h--;)m[h]||v[h]||(v[h]=G.call(u));v=g(v)}K.apply(u,v),l&&!r&&v.length>0&&p+n.length>1&&t.uniqueSort(u)}return l&&(W=x,A=y),m};return i?r(a):a}var x,w,T,C,N,E,k,S,A,D,j,L,H,q,_,M,F,O,B,P="sizzle"+1*new Date,R=e.document,W=0,$=0,z=n(),I=n(),X=n(),U=function(e,t){return e===t&&(j=!0),0},V=1<<31,J={}.hasOwnProperty,Y=[],G=Y.pop,Q=Y.push,K=Y.push,Z=Y.slice,ee=function(e,t){for(var n=0,r=e.length;r>n;n++)if(e[n]===t)return n;return-1},te="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",ne="[\\x20\\t\\r\\n\\f]",re="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ie=re.replace("w","w#"),oe="\\["+ne+"*("+re+")(?:"+ne+"*([*^$|!~]?=)"+ne+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+ie+"))|)"+ne+"*\\]",ae=":("+re+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+oe+")*)|.*)\\)|)",se=new RegExp(ne+"+","g"),ue=new RegExp("^"+ne+"+|((?:^|[^\\\\])(?:\\\\.)*)"+ne+"+$","g"),le=new RegExp("^"+ne+"*,"+ne+"*"),ce=new RegExp("^"+ne+"*([>+~]|"+ne+")"+ne+"*"),de=new RegExp("="+ne+"*([^\\]'\"]*?)"+ne+"*\\]","g"),fe=new RegExp(ae),pe=new RegExp("^"+ie+"$"),he={ID:new RegExp("^#("+re+")"),CLASS:new RegExp("^\\.("+re+")"),TAG:new RegExp("^("+re.replace("w","w*")+")"),ATTR:new RegExp("^"+oe),PSEUDO:new RegExp("^"+ae),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ne+"*(even|odd|(([+-]|)(\\d*)n|)"+ne+"*(?:([+-]|)"+ne+"*(\\d+)|))"+ne+"*\\)|)","i"),bool:new RegExp("^(?:"+te+")$","i"),needsContext:new RegExp("^"+ne+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ne+"*((?:-\\d)?\\d*)"+ne+"*\\)|)(?=[^-]|$)","i")},me=/^(?:input|select|textarea|button)$/i,ge=/^h\d$/i,ve=/^[^{]+\{\s*\[native \w/,ye=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,be=/[+~]/,xe=/'|\\/g,we=new RegExp("\\\\([\\da-f]{1,6}"+ne+"?|("+ne+")|.)","ig"),Te=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},Ce=function(){L()};try{K.apply(Y=Z.call(R.childNodes),R.childNodes),Y[R.childNodes.length].nodeType}catch(Ne){K={apply:Y.length?function(e,t){Q.apply(e,Z.call(t))}:function(e,t){for(var n=e.length,r=0;e[n++]=t[r++];);e.length=n-1}}}w=t.support={},N=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},L=t.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:R;return r!==H&&9===r.nodeType&&r.documentElement?(H=r,q=r.documentElement,n=r.defaultView,n&&n!==n.top&&(n.addEventListener?n.addEventListener("unload",Ce,!1):n.attachEvent&&n.attachEvent("onunload",Ce)),_=!N(r),w.attributes=i(function(e){return e.className="i",!e.getAttribute("className")}),w.getElementsByTagName=i(function(e){return e.appendChild(r.createComment("")),!e.getElementsByTagName("*").length}),w.getElementsByClassName=ve.test(r.getElementsByClassName),w.getById=i(function(e){return q.appendChild(e).id=P,!r.getElementsByName||!r.getElementsByName(P).length}),w.getById?(T.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&_){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},T.filter.ID=function(e){var t=e.replace(we,Te);return function(e){return e.getAttribute("id")===t}}):(delete T.find.ID,T.filter.ID=function(e){var t=e.replace(we,Te);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}}),T.find.TAG=w.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):w.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o},T.find.CLASS=w.getElementsByClassName&&function(e,t){return _?t.getElementsByClassName(e):void 0},F=[],M=[],(w.qsa=ve.test(r.querySelectorAll))&&(i(function(e){q.appendChild(e).innerHTML="<a id='"+P+"'></a><select id='"+P+"-\f]' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&M.push("[*^$]="+ne+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||M.push("\\["+ne+"*(?:value|"+te+")"),e.querySelectorAll("[id~="+P+"-]").length||M.push("~="),e.querySelectorAll(":checked").length||M.push(":checked"),e.querySelectorAll("a#"+P+"+*").length||M.push(".#.+[+~]")}),i(function(e){var t=r.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&M.push("name"+ne+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||M.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),M.push(",.*:")})),(w.matchesSelector=ve.test(O=q.matches||q.webkitMatchesSelector||q.mozMatchesSelector||q.oMatchesSelector||q.msMatchesSelector))&&i(function(e){w.disconnectedMatch=O.call(e,"div"),O.call(e,"[s!='']:x"),F.push("!=",ae)}),M=M.length&&new RegExp(M.join("|")),F=F.length&&new RegExp(F.join("|")),t=ve.test(q.compareDocumentPosition),B=t||ve.test(q.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},U=t?function(e,t){if(e===t)return j=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n?n:(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&n||!w.sortDetached&&t.compareDocumentPosition(e)===n?e===r||e.ownerDocument===R&&B(R,e)?-1:t===r||t.ownerDocument===R&&B(R,t)?1:D?ee(D,e)-ee(D,t):0:4&n?-1:1)}:function(e,t){if(e===t)return j=!0,0;var n,i=0,o=e.parentNode,s=t.parentNode,u=[e],l=[t];if(!o||!s)return e===r?-1:t===r?1:o?-1:s?1:D?ee(D,e)-ee(D,t):0;if(o===s)return a(e,t);for(n=e;n=n.parentNode;)u.unshift(n);for(n=t;n=n.parentNode;)l.unshift(n);for(;u[i]===l[i];)i++;return i?a(u[i],l[i]):u[i]===R?-1:l[i]===R?1:0},r):H},t.matches=function(e,n){return t(e,null,null,n)},t.matchesSelector=function(e,n){if((e.ownerDocument||e)!==H&&L(e),n=n.replace(de,"='$1']"),w.matchesSelector&&_&&(!F||!F.test(n))&&(!M||!M.test(n)))try{var r=O.call(e,n);if(r||w.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(i){}return t(n,H,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==H&&L(e),B(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==H&&L(e);var n=T.attrHandle[t.toLowerCase()],r=n&&J.call(T.attrHandle,t.toLowerCase())?n(e,t,!_):void 0;return void 0!==r?r:w.attributes||!_?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,n=[],r=0,i=0;if(j=!w.detectDuplicates,D=!w.sortStable&&e.slice(0),e.sort(U),j){for(;t=e[i++];)t===e[i]&&(r=n.push(i));for(;r--;)e.splice(n[r],1)}return D=null,e},C=t.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=C(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r++];)n+=C(t);return n},T=t.selectors={cacheLength:50,createPseudo:r,match:he,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(we,Te),e[3]=(e[3]||e[4]||e[5]||"").replace(we,Te),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||t.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&t.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return he.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&fe.test(n)&&(t=E(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(we,Te).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=z[e+" "];return t||(t=new RegExp("(^|"+ne+")"+e+"("+ne+"|$)"))&&z(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,n,r){return function(i){var o=t.attr(i,e);return null==o?"!="===n:n?(o+="","="===n?o===r:"!="===n?o!==r:"^="===n?r&&0===o.indexOf(r):"*="===n?r&&o.indexOf(r)>-1:"$="===n?r&&o.slice(-r.length)===r:"~="===n?(" "+o.replace(se," ")+" ").indexOf(r)>-1:"|="===n?o===r||o.slice(0,r.length+1)===r+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,d,f,p,h,m=o!==a?"nextSibling":"previousSibling",g=t.parentNode,v=s&&t.nodeName.toLowerCase(),y=!u&&!s;if(g){if(o){for(;m;){for(d=t;d=d[m];)if(s?d.nodeName.toLowerCase()===v:1===d.nodeType)return!1;h=m="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?g.firstChild:g.lastChild],a&&y){for(c=g[P]||(g[P]={}),l=c[e]||[],p=l[0]===W&&l[1],f=l[0]===W&&l[2],d=p&&g.childNodes[p];d=++p&&d&&d[m]||(f=p=0)||h.pop();)if(1===d.nodeType&&++f&&d===t){c[e]=[W,p,f];break}}else if(y&&(l=(t[P]||(t[P]={}))[e])&&l[0]===W)f=l[1];else for(;(d=++p&&d&&d[m]||(f=p=0)||h.pop())&&((s?d.nodeName.toLowerCase()!==v:1!==d.nodeType)||!++f||(y&&((d[P]||(d[P]={}))[e]=[W,f]),d!==t)););return f-=i,f===r||f%r===0&&f/r>=0}}},PSEUDO:function(e,n){var i,o=T.pseudos[e]||T.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return o[P]?o(n):o.length>1?(i=[e,e,"",n],T.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,i=o(e,n),a=i.length;a--;)r=ee(e,i[a]),e[r]=!(t[r]=i[a])}):function(e){return o(e,0,i)}):o}},pseudos:{not:r(function(e){var t=[],n=[],i=k(e.replace(ue,"$1"));return i[P]?r(function(e,t,n,r){for(var o,a=i(e,null,r,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,r,o){return t[0]=e,i(t,null,o,n),t[0]=null,!n.pop()}}),has:r(function(e){return function(n){return t(e,n).length>0}}),contains:r(function(e){return e=e.replace(we,Te),function(t){return(t.textContent||t.innerText||C(t)).indexOf(e)>-1}}),lang:r(function(e){return pe.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(we,Te).toLowerCase(),function(t){var n;do if(n=_?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===q},focus:function(e){return e===H.activeElement&&(!H.hasFocus||H.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!T.pseudos.empty(e)},header:function(e){return ge.test(e.nodeName)},input:function(e){return me.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:l(function(){return[0]}),last:l(function(e,t){return[t-1]}),eq:l(function(e,t,n){return[0>n?n+t:n]}),even:l(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:l(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:l(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:l(function(e,t,n){for(var r=0>n?n+t:n;++r<t;)e.push(r);return e})}},T.pseudos.nth=T.pseudos.eq;for(x in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})T.pseudos[x]=s(x);for(x in{submit:!0,reset:!0})T.pseudos[x]=u(x);return d.prototype=T.filters=T.pseudos,T.setFilters=new d,E=t.tokenize=function(e,n){var r,i,o,a,s,u,l,c=I[e+" "];if(c)return n?0:c.slice(0);for(s=e,u=[],l=T.preFilter;s;){(!r||(i=le.exec(s)))&&(i&&(s=s.slice(i[0].length)||s),u.push(o=[])),r=!1,(i=ce.exec(s))&&(r=i.shift(),o.push({value:r,type:i[0].replace(ue," ")}),s=s.slice(r.length));for(a in T.filter)!(i=he[a].exec(s))||l[a]&&!(i=l[a](i))||(r=i.shift(), o.push({value:r,type:a,matches:i}),s=s.slice(r.length));if(!r)break}return n?s.length:s?t.error(e):I(e,u).slice(0)},k=t.compile=function(e,t){var n,r=[],i=[],o=X[e+" "];if(!o){for(t||(t=E(e)),n=t.length;n--;)o=y(t[n]),o[P]?r.push(o):i.push(o);o=X(e,b(i,r)),o.selector=e}return o},S=t.select=function(e,t,n,r){var i,o,a,s,u,l="function"==typeof e&&e,d=!r&&E(e=l.selector||e);if(n=n||[],1===d.length){if(o=d[0]=d[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&w.getById&&9===t.nodeType&&_&&T.relative[o[1].type]){if(t=(T.find.ID(a.matches[0].replace(we,Te),t)||[])[0],!t)return n;l&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(i=he.needsContext.test(e)?0:o.length;i--&&(a=o[i],!T.relative[s=a.type]);)if((u=T.find[s])&&(r=u(a.matches[0].replace(we,Te),be.test(o[0].type)&&c(t.parentNode)||t))){if(o.splice(i,1),e=r.length&&f(o),!e)return K.apply(n,r),n;break}}return(l||k(e,d))(r,t,!_,n,be.test(e)&&c(t.parentNode)||t),n},w.sortStable=P.split("").sort(U).join("")===P,w.detectDuplicates=!!j,L(),w.sortDetached=i(function(e){return 1&e.compareDocumentPosition(H.createElement("div"))}),i(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,n){return n?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),w.attributes&&i(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||o("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),i(function(e){return null==e.getAttribute("disabled")})||o(te,function(e,t,n){var r;return n?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),t}(e);ie.find=le,ie.expr=le.selectors,ie.expr[":"]=ie.expr.pseudos,ie.unique=le.uniqueSort,ie.text=le.getText,ie.isXMLDoc=le.isXML,ie.contains=le.contains;var ce=ie.expr.match.needsContext,de=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,fe=/^.[^:#\[\.,]*$/;ie.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?ie.find.matchesSelector(r,e)?[r]:[]:ie.find.matches(e,ie.grep(t,function(e){return 1===e.nodeType}))},ie.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(ie(e).filter(function(){for(t=0;i>t;t++)if(ie.contains(r[t],this))return!0}));for(t=0;i>t;t++)ie.find(e,r[t],n);return n=this.pushStack(i>1?ie.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},filter:function(e){return this.pushStack(r(this,e||[],!1))},not:function(e){return this.pushStack(r(this,e||[],!0))},is:function(e){return!!r(this,"string"==typeof e&&ce.test(e)?ie(e):e||[],!1).length}});var pe,he=e.document,me=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,ge=ie.fn.init=function(e,t){var n,r;if(!e)return this;if("string"==typeof e){if(n="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:me.exec(e),!n||!n[1]&&t)return!t||t.jquery?(t||pe).find(e):this.constructor(t).find(e);if(n[1]){if(t=t instanceof ie?t[0]:t,ie.merge(this,ie.parseHTML(n[1],t&&t.nodeType?t.ownerDocument||t:he,!0)),de.test(n[1])&&ie.isPlainObject(t))for(n in t)ie.isFunction(this[n])?this[n](t[n]):this.attr(n,t[n]);return this}if(r=he.getElementById(n[2]),r&&r.parentNode){if(r.id!==n[2])return pe.find(e);this.length=1,this[0]=r}return this.context=he,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):ie.isFunction(e)?"undefined"!=typeof pe.ready?pe.ready(e):e(ie):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),ie.makeArray(e,this))};ge.prototype=ie.fn,pe=ie(he);var ve=/^(?:parents|prev(?:Until|All))/,ye={children:!0,contents:!0,next:!0,prev:!0};ie.extend({dir:function(e,t,n){for(var r=[],i=e[t];i&&9!==i.nodeType&&(void 0===n||1!==i.nodeType||!ie(i).is(n));)1===i.nodeType&&r.push(i),i=i[t];return r},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}}),ie.fn.extend({has:function(e){var t,n=ie(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(ie.contains(this,n[t]))return!0})},closest:function(e,t){for(var n,r=0,i=this.length,o=[],a=ce.test(e)||"string"!=typeof e?ie(e,t||this.context):0;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&ie.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?ie.unique(o):o)},index:function(e){return e?"string"==typeof e?ie.inArray(this[0],ie(e)):ie.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(ie.unique(ie.merge(this.get(),ie(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),ie.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return ie.dir(e,"parentNode")},parentsUntil:function(e,t,n){return ie.dir(e,"parentNode",n)},next:function(e){return i(e,"nextSibling")},prev:function(e){return i(e,"previousSibling")},nextAll:function(e){return ie.dir(e,"nextSibling")},prevAll:function(e){return ie.dir(e,"previousSibling")},nextUntil:function(e,t,n){return ie.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return ie.dir(e,"previousSibling",n)},siblings:function(e){return ie.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return ie.sibling(e.firstChild)},contents:function(e){return ie.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:ie.merge([],e.childNodes)}},function(e,t){ie.fn[e]=function(n,r){var i=ie.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=ie.filter(r,i)),this.length>1&&(ye[e]||(i=ie.unique(i)),ve.test(e)&&(i=i.reverse())),this.pushStack(i)}});var be=/\S+/g,xe={};ie.Callbacks=function(e){e="string"==typeof e?xe[e]||o(e):ie.extend({},e);var t,n,r,i,a,s,u=[],l=!e.once&&[],c=function(o){for(n=e.memory&&o,r=!0,a=s||0,s=0,i=u.length,t=!0;u&&i>a;a++)if(u[a].apply(o[0],o[1])===!1&&e.stopOnFalse){n=!1;break}t=!1,u&&(l?l.length&&c(l.shift()):n?u=[]:d.disable())},d={add:function(){if(u){var r=u.length;!function o(t){ie.each(t,function(t,n){var r=ie.type(n);"function"===r?e.unique&&d.has(n)||u.push(n):n&&n.length&&"string"!==r&&o(n)})}(arguments),t?i=u.length:n&&(s=r,c(n))}return this},remove:function(){return u&&ie.each(arguments,function(e,n){for(var r;(r=ie.inArray(n,u,r))>-1;)u.splice(r,1),t&&(i>=r&&i--,a>=r&&a--)}),this},has:function(e){return e?ie.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],i=0,this},disable:function(){return u=l=n=void 0,this},disabled:function(){return!u},lock:function(){return l=void 0,n||d.disable(),this},locked:function(){return!l},fireWith:function(e,n){return!u||r&&!l||(n=n||[],n=[e,n.slice?n.slice():n],t?l.push(n):c(n)),this},fire:function(){return d.fireWith(this,arguments),this},fired:function(){return!!r}};return d},ie.extend({Deferred:function(e){var t=[["resolve","done",ie.Callbacks("once memory"),"resolved"],["reject","fail",ie.Callbacks("once memory"),"rejected"],["notify","progress",ie.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return ie.Deferred(function(n){ie.each(t,function(t,o){var a=ie.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&ie.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[o[0]+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?ie.extend(e,r):r}},i={};return r.pipe=r.then,ie.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t,n,r,i=0,o=Y.call(arguments),a=o.length,s=1!==a||e&&ie.isFunction(e.promise)?a:0,u=1===s?e:ie.Deferred(),l=function(e,n,r){return function(i){n[e]=this,r[e]=arguments.length>1?Y.call(arguments):i,r===t?u.notifyWith(n,r):--s||u.resolveWith(n,r)}};if(a>1)for(t=new Array(a),n=new Array(a),r=new Array(a);a>i;i++)o[i]&&ie.isFunction(o[i].promise)?o[i].promise().done(l(i,r,o)).fail(u.reject).progress(l(i,n,t)):--s;return s||u.resolveWith(r,o),u.promise()}});var we;ie.fn.ready=function(e){return ie.ready.promise().done(e),this},ie.extend({isReady:!1,readyWait:1,holdReady:function(e){e?ie.readyWait++:ie.ready(!0)},ready:function(e){if(e===!0?!--ie.readyWait:!ie.isReady){if(!he.body)return setTimeout(ie.ready);ie.isReady=!0,e!==!0&&--ie.readyWait>0||(we.resolveWith(he,[ie]),ie.fn.triggerHandler&&(ie(he).triggerHandler("ready"),ie(he).off("ready")))}}}),ie.ready.promise=function(t){if(!we)if(we=ie.Deferred(),"complete"===he.readyState)setTimeout(ie.ready);else if(he.addEventListener)he.addEventListener("DOMContentLoaded",s,!1),e.addEventListener("load",s,!1);else{he.attachEvent("onreadystatechange",s),e.attachEvent("onload",s);var n=!1;try{n=null==e.frameElement&&he.documentElement}catch(r){}n&&n.doScroll&&!function i(){if(!ie.isReady){try{n.doScroll("left")}catch(e){return setTimeout(i,50)}a(),ie.ready()}}()}return we.promise(t)};var Te,Ce="undefined";for(Te in ie(ne))break;ne.ownLast="0"!==Te,ne.inlineBlockNeedsLayout=!1,ie(function(){var e,t,n,r;n=he.getElementsByTagName("body")[0],n&&n.style&&(t=he.createElement("div"),r=he.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Ce&&(t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",ne.inlineBlockNeedsLayout=e=3===t.offsetWidth,e&&(n.style.zoom=1)),n.removeChild(r))}),function(){var e=he.createElement("div");if(null==ne.deleteExpando){ne.deleteExpando=!0;try{delete e.test}catch(t){ne.deleteExpando=!1}}e=null}(),ie.acceptData=function(e){var t=ie.noData[(e.nodeName+" ").toLowerCase()],n=+e.nodeType||1;return 1!==n&&9!==n?!1:!t||t!==!0&&e.getAttribute("classid")===t};var Ne=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Ee=/([A-Z])/g;ie.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?ie.cache[e[ie.expando]]:e[ie.expando],!!e&&!l(e)},data:function(e,t,n){return c(e,t,n)},removeData:function(e,t){return d(e,t)},_data:function(e,t,n){return c(e,t,n,!0)},_removeData:function(e,t){return d(e,t,!0)}}),ie.fn.extend({data:function(e,t){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===e){if(this.length&&(i=ie.data(o),1===o.nodeType&&!ie._data(o,"parsedAttrs"))){for(n=a.length;n--;)a[n]&&(r=a[n].name,0===r.indexOf("data-")&&(r=ie.camelCase(r.slice(5)),u(o,r,i[r])));ie._data(o,"parsedAttrs",!0)}return i}return"object"==typeof e?this.each(function(){ie.data(this,e)}):arguments.length>1?this.each(function(){ie.data(this,e,t)}):o?u(o,e,ie.data(o,e)):void 0},removeData:function(e){return this.each(function(){ie.removeData(this,e)})}}),ie.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=ie._data(e,t),n&&(!r||ie.isArray(n)?r=ie._data(e,t,ie.makeArray(n)):r.push(n)),r||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=ie.queue(e,t),r=n.length,i=n.shift(),o=ie._queueHooks(e,t),a=function(){ie.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return ie._data(e,n)||ie._data(e,n,{empty:ie.Callbacks("once memory").add(function(){ie._removeData(e,t+"queue"),ie._removeData(e,n)})})}}),ie.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?ie.queue(this[0],e):void 0===t?this:this.each(function(){var n=ie.queue(this,e,t);ie._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&ie.dequeue(this,e)})},dequeue:function(e){return this.each(function(){ie.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=ie.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";a--;)n=ie._data(o[a],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var ke=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Se=["Top","Right","Bottom","Left"],Ae=function(e,t){return e=t||e,"none"===ie.css(e,"display")||!ie.contains(e.ownerDocument,e)},De=ie.access=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===ie.type(n)){i=!0;for(s in n)ie.access(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,ie.isFunction(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(ie(e),n)})),t))for(;u>s;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:l?t.call(e):u?t(e[0],n):o},je=/^(?:checkbox|radio)$/i;!function(){var e=he.createElement("input"),t=he.createElement("div"),n=he.createDocumentFragment();if(t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",ne.leadingWhitespace=3===t.firstChild.nodeType,ne.tbody=!t.getElementsByTagName("tbody").length,ne.htmlSerialize=!!t.getElementsByTagName("link").length,ne.html5Clone="<:nav></:nav>"!==he.createElement("nav").cloneNode(!0).outerHTML,e.type="checkbox",e.checked=!0,n.appendChild(e),ne.appendChecked=e.checked,t.innerHTML="<textarea>x</textarea>",ne.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue,n.appendChild(t),t.innerHTML="<input type='radio' checked='checked' name='t'/>",ne.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,ne.noCloneEvent=!0,t.attachEvent&&(t.attachEvent("onclick",function(){ne.noCloneEvent=!1}),t.cloneNode(!0).click()),null==ne.deleteExpando){ne.deleteExpando=!0;try{delete t.test}catch(r){ne.deleteExpando=!1}}}(),function(){var t,n,r=he.createElement("div");for(t in{submit:!0,change:!0,focusin:!0})n="on"+t,(ne[t+"Bubbles"]=n in e)||(r.setAttribute(n,"t"),ne[t+"Bubbles"]=r.attributes[n].expando===!1);r=null}();var Le=/^(?:input|select|textarea)$/i,He=/^key/,qe=/^(?:mouse|pointer|contextmenu)|click/,_e=/^(?:focusinfocus|focusoutblur)$/,Me=/^([^.]*)(?:\.(.+)|)$/;ie.event={global:{},add:function(e,t,n,r,i){var o,a,s,u,l,c,d,f,p,h,m,g=ie._data(e);if(g){for(n.handler&&(u=n,n=u.handler,i=u.selector),n.guid||(n.guid=ie.guid++),(a=g.events)||(a=g.events={}),(c=g.handle)||(c=g.handle=function(e){return typeof ie===Ce||e&&ie.event.triggered===e.type?void 0:ie.event.dispatch.apply(c.elem,arguments)},c.elem=e),t=(t||"").match(be)||[""],s=t.length;s--;)o=Me.exec(t[s])||[],p=m=o[1],h=(o[2]||"").split(".").sort(),p&&(l=ie.event.special[p]||{},p=(i?l.delegateType:l.bindType)||p,l=ie.event.special[p]||{},d=ie.extend({type:p,origType:m,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&ie.expr.match.needsContext.test(i),namespace:h.join(".")},u),(f=a[p])||(f=a[p]=[],f.delegateCount=0,l.setup&&l.setup.call(e,r,h,c)!==!1||(e.addEventListener?e.addEventListener(p,c,!1):e.attachEvent&&e.attachEvent("on"+p,c))),l.add&&(l.add.call(e,d),d.handler.guid||(d.handler.guid=n.guid)),i?f.splice(f.delegateCount++,0,d):f.push(d),ie.event.global[p]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,d,f,p,h,m,g=ie.hasData(e)&&ie._data(e);if(g&&(c=g.events)){for(t=(t||"").match(be)||[""],l=t.length;l--;)if(s=Me.exec(t[l])||[],p=m=s[1],h=(s[2]||"").split(".").sort(),p){for(d=ie.event.special[p]||{},p=(r?d.delegateType:d.bindType)||p,f=c[p]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;o--;)a=f[o],!i&&m!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,d.remove&&d.remove.call(e,a));u&&!f.length&&(d.teardown&&d.teardown.call(e,h,g.handle)!==!1||ie.removeEvent(e,p,g.handle),delete c[p])}else for(p in c)ie.event.remove(e,p+t[l],n,r,!0);ie.isEmptyObject(c)&&(delete g.handle,ie._removeData(e,"events"))}},trigger:function(t,n,r,i){var o,a,s,u,l,c,d,f=[r||he],p=te.call(t,"type")?t.type:t,h=te.call(t,"namespace")?t.namespace.split("."):[];if(s=c=r=r||he,3!==r.nodeType&&8!==r.nodeType&&!_e.test(p+ie.event.triggered)&&(p.indexOf(".")>=0&&(h=p.split("."),p=h.shift(),h.sort()),a=p.indexOf(":")<0&&"on"+p,t=t[ie.expando]?t:new ie.Event(p,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=h.join("."),t.namespace_re=t.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=r),n=null==n?[t]:ie.makeArray(n,[t]),l=ie.event.special[p]||{},i||!l.trigger||l.trigger.apply(r,n)!==!1)){if(!i&&!l.noBubble&&!ie.isWindow(r)){for(u=l.delegateType||p,_e.test(u+p)||(s=s.parentNode);s;s=s.parentNode)f.push(s),c=s;c===(r.ownerDocument||he)&&f.push(c.defaultView||c.parentWindow||e)}for(d=0;(s=f[d++])&&!t.isPropagationStopped();)t.type=d>1?u:l.bindType||p,o=(ie._data(s,"events")||{})[t.type]&&ie._data(s,"handle"),o&&o.apply(s,n),o=a&&s[a],o&&o.apply&&ie.acceptData(s)&&(t.result=o.apply(s,n),t.result===!1&&t.preventDefault());if(t.type=p,!i&&!t.isDefaultPrevented()&&(!l._default||l._default.apply(f.pop(),n)===!1)&&ie.acceptData(r)&&a&&r[p]&&!ie.isWindow(r)){c=r[a],c&&(r[a]=null),ie.event.triggered=p;try{r[p]()}catch(m){}ie.event.triggered=void 0,c&&(r[a]=c)}return t.result}},dispatch:function(e){e=ie.event.fix(e);var t,n,r,i,o,a=[],s=Y.call(arguments),u=(ie._data(this,"events")||{})[e.type]||[],l=ie.event.special[e.type]||{};if(s[0]=e,e.delegateTarget=this,!l.preDispatch||l.preDispatch.call(this,e)!==!1){for(a=ie.event.handlers.call(this,e,u),t=0;(i=a[t++])&&!e.isPropagationStopped();)for(e.currentTarget=i.elem,o=0;(r=i.handlers[o++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(r.namespace))&&(e.handleObj=r,e.data=r.data,n=((ie.event.special[r.origType]||{}).handle||r.handler).apply(i.elem,s),void 0!==n&&(e.result=n)===!1&&(e.preventDefault(),e.stopPropagation()));return l.postDispatch&&l.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,a=[],s=t.delegateCount,u=e.target;if(s&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(i=[],o=0;s>o;o++)r=t[o],n=r.selector+" ",void 0===i[n]&&(i[n]=r.needsContext?ie(n,this).index(u)>=0:ie.find(n,this,null,[u]).length),i[n]&&i.push(r);i.length&&a.push({elem:u,handlers:i})}return s<t.length&&a.push({elem:this,handlers:t.slice(s)}),a},fix:function(e){if(e[ie.expando])return e;var t,n,r,i=e.type,o=e,a=this.fixHooks[i];for(a||(this.fixHooks[i]=a=qe.test(i)?this.mouseHooks:He.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new ie.Event(o),t=r.length;t--;)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||he),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,a.filter?a.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,o=t.button,a=t.fromElement;return null==e.pageX&&null!=t.clientX&&(r=e.target.ownerDocument||he,i=r.documentElement,n=r.body,e.pageX=t.clientX+(i&&i.scrollLeft||n&&n.scrollLeft||0)-(i&&i.clientLeft||n&&n.clientLeft||0),e.pageY=t.clientY+(i&&i.scrollTop||n&&n.scrollTop||0)-(i&&i.clientTop||n&&n.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?t.toElement:a),e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==h()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===h()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return ie.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(e){return ie.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=ie.extend(new ie.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?ie.event.trigger(i,null,t):ie.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},ie.removeEvent=he.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===Ce&&(e[r]=null),e.detachEvent(r,n))},ie.Event=function(e,t){return this instanceof ie.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?f:p):this.type=e,t&&ie.extend(this,t),this.timeStamp=e&&e.timeStamp||ie.now(),void(this[ie.expando]=!0)):new ie.Event(e,t)},ie.Event.prototype={isDefaultPrevented:p,isPropagationStopped:p,isImmediatePropagationStopped:p,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=f,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=f,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=f,e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),this.stopPropagation()}},ie.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){ie.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!ie.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),ne.submitBubbles||(ie.event.special.submit={setup:function(){return ie.nodeName(this,"form")?!1:void ie.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,n=ie.nodeName(t,"input")||ie.nodeName(t,"button")?t.form:void 0;n&&!ie._data(n,"submitBubbles")&&(ie.event.add(n,"submit._submit",function(e){e._submit_bubble=!0}),ie._data(n,"submitBubbles",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&ie.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return ie.nodeName(this,"form")?!1:void ie.event.remove(this,"._submit")}}),ne.changeBubbles||(ie.event.special.change={setup:function(){return Le.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(ie.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),ie.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),ie.event.simulate("change",this,e,!0)})),!1):void ie.event.add(this,"beforeactivate._change",function(e){var t=e.target;Le.test(t.nodeName)&&!ie._data(t,"changeBubbles")&&(ie.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||ie.event.simulate("change",this.parentNode,e,!0)}),ie._data(t,"changeBubbles",!0))})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return ie.event.remove(this,"._change"),!Le.test(this.nodeName)}}),ne.focusinBubbles||ie.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){ie.event.simulate(t,e.target,ie.event.fix(e),!0)};ie.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=ie._data(r,t);i||r.addEventListener(e,n,!0),ie._data(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=ie._data(r,t)-1;i?ie._data(r,t,i):(r.removeEventListener(e,n,!0),ie._removeData(r,t))}}}),ie.fn.extend({on:function(e,t,n,r,i){var o,a;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=void 0);for(o in e)this.on(o,t,n,e[o],i);return this}if(null==n&&null==r?(r=t,n=t=void 0):null==r&&("string"==typeof t?(r=n,n=void 0):(r=n,n=t,t=void 0)),r===!1)r=p;else if(!r)return this;return 1===i&&(a=r,r=function(e){return ie().off(e),a.apply(this,arguments)},r.guid=a.guid||(a.guid=ie.guid++)),this.each(function(){ie.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,ie(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=void 0),n===!1&&(n=p),this.each(function(){ie.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){ie.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?ie.event.trigger(e,t,n,!0):void 0}});var Fe="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Oe=/ jQuery\d+="(?:null|\d+)"/g,Be=new RegExp("<(?:"+Fe+")[\\s/>]","i"),Pe=/^\s+/,Re=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,We=/<([\w:]+)/,$e=/<tbody/i,ze=/<|&#?\w+;/,Ie=/<(?:script|style|link)/i,Xe=/checked\s*(?:[^=]|=\s*.checked.)/i,Ue=/^$|\/(?:java|ecma)script/i,Ve=/^true\/(.*)/,Je=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Ye={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:ne.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Ge=m(he),Qe=Ge.appendChild(he.createElement("div"));Ye.optgroup=Ye.option,Ye.tbody=Ye.tfoot=Ye.colgroup=Ye.caption=Ye.thead,Ye.th=Ye.td,ie.extend({clone:function(e,t,n){var r,i,o,a,s,u=ie.contains(e.ownerDocument,e);if(ne.html5Clone||ie.isXMLDoc(e)||!Be.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Qe.innerHTML=e.outerHTML,Qe.removeChild(o=Qe.firstChild)),!(ne.noCloneEvent&&ne.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ie.isXMLDoc(e)))for(r=g(o),s=g(e),a=0;null!=(i=s[a]);++a)r[a]&&C(i,r[a]);if(t)if(n)for(s=s||g(e),r=r||g(o),a=0;null!=(i=s[a]);a++)T(i,r[a]);else T(e,o);return r=g(o,"script"),r.length>0&&w(r,!u&&g(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){for(var i,o,a,s,u,l,c,d=e.length,f=m(t),p=[],h=0;d>h;h++)if(o=e[h],o||0===o)if("object"===ie.type(o))ie.merge(p,o.nodeType?[o]:o);else if(ze.test(o)){for(s=s||f.appendChild(t.createElement("div")),u=(We.exec(o)||["",""])[1].toLowerCase(),c=Ye[u]||Ye._default,s.innerHTML=c[1]+o.replace(Re,"<$1></$2>")+c[2],i=c[0];i--;)s=s.lastChild;if(!ne.leadingWhitespace&&Pe.test(o)&&p.push(t.createTextNode(Pe.exec(o)[0])),!ne.tbody)for(o="table"!==u||$e.test(o)?"<table>"!==c[1]||$e.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;i--;)ie.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l);for(ie.merge(p,s.childNodes),s.textContent="";s.firstChild;)s.removeChild(s.firstChild);s=f.lastChild}else p.push(t.createTextNode(o));for(s&&f.removeChild(s),ne.appendChecked||ie.grep(g(p,"input"),v),h=0;o=p[h++];)if((!r||-1===ie.inArray(o,r))&&(a=ie.contains(o.ownerDocument,o),s=g(f.appendChild(o),"script"),a&&w(s),n))for(i=0;o=s[i++];)Ue.test(o.type||"")&&n.push(o);return s=null,f},cleanData:function(e,t){for(var n,r,i,o,a=0,s=ie.expando,u=ie.cache,l=ne.deleteExpando,c=ie.event.special;null!=(n=e[a]);a++)if((t||ie.acceptData(n))&&(i=n[s],o=i&&u[i])){if(o.events)for(r in o.events)c[r]?ie.event.remove(n,r):ie.removeEvent(n,r,o.handle);u[i]&&(delete u[i],l?delete n[s]:typeof n.removeAttribute!==Ce?n.removeAttribute(s):n[s]=null,J.push(i))}}}),ie.fn.extend({text:function(e){return De(this,function(e){return void 0===e?ie.text(this):this.empty().append((this[0]&&this[0].ownerDocument||he).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=y(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=y(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var n,r=e?ie.filter(e,this):this,i=0;null!=(n=r[i]);i++)t||1!==n.nodeType||ie.cleanData(g(n)),n.parentNode&&(t&&ie.contains(n.ownerDocument,n)&&w(g(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&ie.cleanData(g(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&ie.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return ie.clone(this,e,t)})},html:function(e){return De(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Oe,""):void 0;if("string"==typeof e&&!Ie.test(e)&&(ne.htmlSerialize||!Be.test(e))&&(ne.leadingWhitespace||!Pe.test(e))&&!Ye[(We.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(Re,"<$1></$2>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(ie.cleanData(g(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];return this.domManip(arguments,function(t){e=this.parentNode,ie.cleanData(g(this)),e&&e.replaceChild(t,this)}),e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=G.apply([],e);var n,r,i,o,a,s,u=0,l=this.length,c=this,d=l-1,f=e[0],p=ie.isFunction(f);if(p||l>1&&"string"==typeof f&&!ne.checkClone&&Xe.test(f))return this.each(function(n){var r=c.eq(n);p&&(e[0]=f.call(this,n,r.html())),r.domManip(e,t)});if(l&&(s=ie.buildFragment(e,this[0].ownerDocument,!1,this),n=s.firstChild,1===s.childNodes.length&&(s=n),n)){for(o=ie.map(g(s,"script"),b),i=o.length;l>u;u++)r=s,u!==d&&(r=ie.clone(r,!0,!0),i&&ie.merge(o,g(r,"script"))),t.call(this[u],r,u);if(i)for(a=o[o.length-1].ownerDocument,ie.map(o,x),u=0;i>u;u++)r=o[u],Ue.test(r.type||"")&&!ie._data(r,"globalEval")&&ie.contains(a,r)&&(r.src?ie._evalUrl&&ie._evalUrl(r.src):ie.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Je,"")));s=n=null}return this}}),ie.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){ie.fn[e]=function(e){for(var n,r=0,i=[],o=ie(e),a=o.length-1;a>=r;r++)n=r===a?this:this.clone(!0),ie(o[r])[t](n),Q.apply(i,n.get());return this.pushStack(i)}});var Ke,Ze={};!function(){var e;ne.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,n,r;return n=he.getElementsByTagName("body")[0],n&&n.style?(t=he.createElement("div"),r=he.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Ce&&(t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",t.appendChild(he.createElement("div")).style.width="5px",e=3!==t.offsetWidth),n.removeChild(r),e):void 0}}();var et,tt,nt=/^margin/,rt=new RegExp("^("+ke+")(?!px)[a-z%]+$","i"),it=/^(top|right|bottom|left)$/;e.getComputedStyle?(et=function(t){return t.ownerDocument.defaultView.opener?t.ownerDocument.defaultView.getComputedStyle(t,null):e.getComputedStyle(t,null)},tt=function(e,t,n){var r,i,o,a,s=e.style;return n=n||et(e),a=n?n.getPropertyValue(t)||n[t]:void 0,n&&(""!==a||ie.contains(e.ownerDocument,e)||(a=ie.style(e,t)),rt.test(a)&&nt.test(t)&&(r=s.width,i=s.minWidth, o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0===a?a:a+""}):he.documentElement.currentStyle&&(et=function(e){return e.currentStyle},tt=function(e,t,n){var r,i,o,a,s=e.style;return n=n||et(e),a=n?n[t]:void 0,null==a&&s&&s[t]&&(a=s[t]),rt.test(a)&&!it.test(t)&&(r=s.left,i=e.runtimeStyle,o=i&&i.left,o&&(i.left=e.currentStyle.left),s.left="fontSize"===t?"1em":a,a=s.pixelLeft+"px",s.left=r,o&&(i.left=o)),void 0===a?a:a+""||"auto"}),function(){function t(){var t,n,r,i;n=he.getElementsByTagName("body")[0],n&&n.style&&(t=he.createElement("div"),r=he.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),t.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",o=a=!1,u=!0,e.getComputedStyle&&(o="1%"!==(e.getComputedStyle(t,null)||{}).top,a="4px"===(e.getComputedStyle(t,null)||{width:"4px"}).width,i=t.appendChild(he.createElement("div")),i.style.cssText=t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",t.style.width="1px",u=!parseFloat((e.getComputedStyle(i,null)||{}).marginRight),t.removeChild(i)),t.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=t.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",s=0===i[0].offsetHeight,s&&(i[0].style.display="",i[1].style.display="none",s=0===i[0].offsetHeight),n.removeChild(r))}var n,r,i,o,a,s,u;n=he.createElement("div"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",i=n.getElementsByTagName("a")[0],r=i&&i.style,r&&(r.cssText="float:left;opacity:.5",ne.opacity="0.5"===r.opacity,ne.cssFloat=!!r.cssFloat,n.style.backgroundClip="content-box",n.cloneNode(!0).style.backgroundClip="",ne.clearCloneStyle="content-box"===n.style.backgroundClip,ne.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing,ie.extend(ne,{reliableHiddenOffsets:function(){return null==s&&t(),s},boxSizingReliable:function(){return null==a&&t(),a},pixelPosition:function(){return null==o&&t(),o},reliableMarginRight:function(){return null==u&&t(),u}}))}(),ie.swap=function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i};var ot=/alpha\([^)]*\)/i,at=/opacity\s*=\s*([^)]*)/,st=/^(none|table(?!-c[ea]).+)/,ut=new RegExp("^("+ke+")(.*)$","i"),lt=new RegExp("^([+-])=("+ke+")","i"),ct={position:"absolute",visibility:"hidden",display:"block"},dt={letterSpacing:"0",fontWeight:"400"},ft=["Webkit","O","Moz","ms"];ie.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=tt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":ne.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=ie.camelCase(t),u=e.style;if(t=ie.cssProps[s]||(ie.cssProps[s]=S(u,s)),a=ie.cssHooks[t]||ie.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:u[t];if(o=typeof n,"string"===o&&(i=lt.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(ie.css(e,t)),o="number"),null!=n&&n===n&&("number"!==o||ie.cssNumber[s]||(n+="px"),ne.clearCloneStyle||""!==n||0!==t.indexOf("background")||(u[t]="inherit"),!(a&&"set"in a&&void 0===(n=a.set(e,n,r)))))try{u[t]=n}catch(l){}}},css:function(e,t,n,r){var i,o,a,s=ie.camelCase(t);return t=ie.cssProps[s]||(ie.cssProps[s]=S(e.style,s)),a=ie.cssHooks[t]||ie.cssHooks[s],a&&"get"in a&&(o=a.get(e,!0,n)),void 0===o&&(o=tt(e,t,r)),"normal"===o&&t in dt&&(o=dt[t]),""===n||n?(i=parseFloat(o),n===!0||ie.isNumeric(i)?i||0:o):o}}),ie.each(["height","width"],function(e,t){ie.cssHooks[t]={get:function(e,n,r){return n?st.test(ie.css(e,"display"))&&0===e.offsetWidth?ie.swap(e,ct,function(){return L(e,t,r)}):L(e,t,r):void 0},set:function(e,n,r){var i=r&&et(e);return D(e,n,r?j(e,t,r,ne.boxSizing&&"border-box"===ie.css(e,"boxSizing",!1,i),i):0)}}}),ne.opacity||(ie.cssHooks.opacity={get:function(e,t){return at.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=ie.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===ie.trim(o.replace(ot,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=ot.test(o)?o.replace(ot,i):o+" "+i)}}),ie.cssHooks.marginRight=k(ne.reliableMarginRight,function(e,t){return t?ie.swap(e,{display:"inline-block"},tt,[e,"marginRight"]):void 0}),ie.each({margin:"",padding:"",border:"Width"},function(e,t){ie.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[e+Se[r]+t]=o[r]||o[r-2]||o[0];return i}},nt.test(e)||(ie.cssHooks[e+t].set=D)}),ie.fn.extend({css:function(e,t){return De(this,function(e,t,n){var r,i,o={},a=0;if(ie.isArray(t)){for(r=et(e),i=t.length;i>a;a++)o[t[a]]=ie.css(e,t[a],!1,r);return o}return void 0!==n?ie.style(e,t,n):ie.css(e,t)},e,t,arguments.length>1)},show:function(){return A(this,!0)},hide:function(){return A(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){Ae(this)?ie(this).show():ie(this).hide()})}}),ie.Tween=H,H.prototype={constructor:H,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(ie.cssNumber[n]?"":"px")},cur:function(){var e=H.propHooks[this.prop];return e&&e.get?e.get(this):H.propHooks._default.get(this)},run:function(e){var t,n=H.propHooks[this.prop];return this.options.duration?this.pos=t=ie.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):H.propHooks._default.set(this),this}},H.prototype.init.prototype=H.prototype,H.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=ie.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){ie.fx.step[e.prop]?ie.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[ie.cssProps[e.prop]]||ie.cssHooks[e.prop])?ie.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},H.propHooks.scrollTop=H.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},ie.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},ie.fx=H.prototype.init,ie.fx.step={};var pt,ht,mt=/^(?:toggle|show|hide)$/,gt=new RegExp("^(?:([+-])=|)("+ke+")([a-z%]*)$","i"),vt=/queueHooks$/,yt=[F],bt={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=gt.exec(t),o=i&&i[3]||(ie.cssNumber[e]?"":"px"),a=(ie.cssNumber[e]||"px"!==o&&+r)&&gt.exec(ie.css(n.elem,e)),s=1,u=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,ie.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--u)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};ie.Animation=ie.extend(B,{tweener:function(e,t){ie.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var n,r=0,i=e.length;i>r;r++)n=e[r],bt[n]=bt[n]||[],bt[n].unshift(t)},prefilter:function(e,t){t?yt.unshift(e):yt.push(e)}}),ie.speed=function(e,t,n){var r=e&&"object"==typeof e?ie.extend({},e):{complete:n||!n&&t||ie.isFunction(e)&&e,duration:e,easing:n&&t||t&&!ie.isFunction(t)&&t};return r.duration=ie.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in ie.fx.speeds?ie.fx.speeds[r.duration]:ie.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){ie.isFunction(r.old)&&r.old.call(this),r.queue&&ie.dequeue(this,r.queue)},r},ie.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Ae).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=ie.isEmptyObject(e),o=ie.speed(t,n,r),a=function(){var t=B(this,ie.extend({},e),o);(i||ie._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=ie.timers,a=ie._data(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&vt.test(i)&&r(a[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));(t||!n)&&ie.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=ie._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=ie.timers,a=r?r.length:0;for(n.finish=!0,ie.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}}),ie.each(["toggle","show","hide"],function(e,t){var n=ie.fn[t];ie.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(_(t,!0),e,r,i)}}),ie.each({slideDown:_("show"),slideUp:_("hide"),slideToggle:_("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){ie.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),ie.timers=[],ie.fx.tick=function(){var e,t=ie.timers,n=0;for(pt=ie.now();n<t.length;n++)e=t[n],e()||t[n]!==e||t.splice(n--,1);t.length||ie.fx.stop(),pt=void 0},ie.fx.timer=function(e){ie.timers.push(e),e()?ie.fx.start():ie.timers.pop()},ie.fx.interval=13,ie.fx.start=function(){ht||(ht=setInterval(ie.fx.tick,ie.fx.interval))},ie.fx.stop=function(){clearInterval(ht),ht=null},ie.fx.speeds={slow:600,fast:200,_default:400},ie.fn.delay=function(e,t){return e=ie.fx?ie.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},function(){var e,t,n,r,i;t=he.createElement("div"),t.setAttribute("className","t"),t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",r=t.getElementsByTagName("a")[0],n=he.createElement("select"),i=n.appendChild(he.createElement("option")),e=t.getElementsByTagName("input")[0],r.style.cssText="top:1px",ne.getSetAttribute="t"!==t.className,ne.style=/top/.test(r.getAttribute("style")),ne.hrefNormalized="/a"===r.getAttribute("href"),ne.checkOn=!!e.value,ne.optSelected=i.selected,ne.enctype=!!he.createElement("form").enctype,n.disabled=!0,ne.optDisabled=!i.disabled,e=he.createElement("input"),e.setAttribute("value",""),ne.input=""===e.getAttribute("value"),e.value="t",e.setAttribute("type","radio"),ne.radioValue="t"===e.value}();var xt=/\r/g;ie.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=ie.isFunction(e),this.each(function(n){var i;1===this.nodeType&&(i=r?e.call(this,n,ie(this).val()):e,null==i?i="":"number"==typeof i?i+="":ie.isArray(i)&&(i=ie.map(i,function(e){return null==e?"":e+""})),t=ie.valHooks[this.type]||ie.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return t=ie.valHooks[i.type]||ie.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:(n=i.value,"string"==typeof n?n.replace(xt,""):null==n?"":n)}}}),ie.extend({valHooks:{option:{get:function(e){var t=ie.find.attr(e,"value");return null!=t?t:ie.trim(ie.text(e))}},select:{get:function(e){for(var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;s>u;u++)if(n=r[u],(n.selected||u===i)&&(ne.optDisabled?!n.disabled:null===n.getAttribute("disabled"))&&(!n.parentNode.disabled||!ie.nodeName(n.parentNode,"optgroup"))){if(t=ie(n).val(),o)return t;a.push(t)}return a},set:function(e,t){for(var n,r,i=e.options,o=ie.makeArray(t),a=i.length;a--;)if(r=i[a],ie.inArray(ie.valHooks.option.get(r),o)>=0)try{r.selected=n=!0}catch(s){r.scrollHeight}else r.selected=!1;return n||(e.selectedIndex=-1),i}}}}),ie.each(["radio","checkbox"],function(){ie.valHooks[this]={set:function(e,t){return ie.isArray(t)?e.checked=ie.inArray(ie(e).val(),t)>=0:void 0}},ne.checkOn||(ie.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var wt,Tt,Ct=ie.expr.attrHandle,Nt=/^(?:checked|selected)$/i,Et=ne.getSetAttribute,kt=ne.input;ie.fn.extend({attr:function(e,t){return De(this,ie.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){ie.removeAttr(this,e)})}}),ie.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o)return typeof e.getAttribute===Ce?ie.prop(e,t,n):(1===o&&ie.isXMLDoc(e)||(t=t.toLowerCase(),r=ie.attrHooks[t]||(ie.expr.match.bool.test(t)?Tt:wt)),void 0===n?r&&"get"in r&&null!==(i=r.get(e,t))?i:(i=ie.find.attr(e,t),null==i?void 0:i):null!==n?r&&"set"in r&&void 0!==(i=r.set(e,n,t))?i:(e.setAttribute(t,n+""),n):void ie.removeAttr(e,t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(be);if(o&&1===e.nodeType)for(;n=o[i++];)r=ie.propFix[n]||n,ie.expr.match.bool.test(n)?kt&&Et||!Nt.test(n)?e[r]=!1:e[ie.camelCase("default-"+n)]=e[r]=!1:ie.attr(e,n,""),e.removeAttribute(Et?n:r)},attrHooks:{type:{set:function(e,t){if(!ne.radioValue&&"radio"===t&&ie.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}}}),Tt={set:function(e,t,n){return t===!1?ie.removeAttr(e,n):kt&&Et||!Nt.test(n)?e.setAttribute(!Et&&ie.propFix[n]||n,n):e[ie.camelCase("default-"+n)]=e[n]=!0,n}},ie.each(ie.expr.match.bool.source.match(/\w+/g),function(e,t){var n=Ct[t]||ie.find.attr;Ct[t]=kt&&Et||!Nt.test(t)?function(e,t,r){var i,o;return r||(o=Ct[t],Ct[t]=i,i=null!=n(e,t,r)?t.toLowerCase():null,Ct[t]=o),i}:function(e,t,n){return n?void 0:e[ie.camelCase("default-"+t)]?t.toLowerCase():null}}),kt&&Et||(ie.attrHooks.value={set:function(e,t,n){return ie.nodeName(e,"input")?void(e.defaultValue=t):wt&&wt.set(e,t,n)}}),Et||(wt={set:function(e,t,n){var r=e.getAttributeNode(n);return r||e.setAttributeNode(r=e.ownerDocument.createAttribute(n)),r.value=t+="","value"===n||t===e.getAttribute(n)?t:void 0}},Ct.id=Ct.name=Ct.coords=function(e,t,n){var r;return n?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null},ie.valHooks.button={get:function(e,t){var n=e.getAttributeNode(t);return n&&n.specified?n.value:void 0},set:wt.set},ie.attrHooks.contenteditable={set:function(e,t,n){wt.set(e,""===t?!1:t,n)}},ie.each(["width","height"],function(e,t){ie.attrHooks[t]={set:function(e,n){return""===n?(e.setAttribute(t,"auto"),n):void 0}}})),ne.style||(ie.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var St=/^(?:input|select|textarea|button|object)$/i,At=/^(?:a|area)$/i;ie.fn.extend({prop:function(e,t){return De(this,ie.prop,e,t,arguments.length>1)},removeProp:function(e){return e=ie.propFix[e]||e,this.each(function(){try{this[e]=void 0,delete this[e]}catch(t){}})}}),ie.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,a=e.nodeType;if(e&&3!==a&&8!==a&&2!==a)return o=1!==a||!ie.isXMLDoc(e),o&&(t=ie.propFix[t]||t,i=ie.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=ie.find.attr(e,"tabindex");return t?parseInt(t,10):St.test(e.nodeName)||At.test(e.nodeName)&&e.href?0:-1}}}}),ne.hrefNormalized||ie.each(["href","src"],function(e,t){ie.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),ne.optSelected||(ie.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),ie.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ie.propFix[this.toLowerCase()]=this}),ne.enctype||(ie.propFix.enctype="encoding");var Dt=/[\t\r\n\f]/g;ie.fn.extend({addClass:function(e){var t,n,r,i,o,a,s=0,u=this.length,l="string"==typeof e&&e;if(ie.isFunction(e))return this.each(function(t){ie(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(be)||[];u>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Dt," "):" ")){for(o=0;i=t[o++];)r.indexOf(" "+i+" ")<0&&(r+=i+" ");a=ie.trim(r),n.className!==a&&(n.className=a)}return this},removeClass:function(e){var t,n,r,i,o,a,s=0,u=this.length,l=0===arguments.length||"string"==typeof e&&e;if(ie.isFunction(e))return this.each(function(t){ie(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(be)||[];u>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Dt," "):"")){for(o=0;i=t[o++];)for(;r.indexOf(" "+i+" ")>=0;)r=r.replace(" "+i+" "," ");a=e?ie.trim(r):"",n.className!==a&&(n.className=a)}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):ie.isFunction(e)?this.each(function(n){ie(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n)for(var t,r=0,i=ie(this),o=e.match(be)||[];t=o[r++];)i.hasClass(t)?i.removeClass(t):i.addClass(t);else(n===Ce||"boolean"===n)&&(this.className&&ie._data(this,"__className__",this.className),this.className=this.className||e===!1?"":ie._data(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",n=0,r=this.length;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(Dt," ").indexOf(t)>=0)return!0;return!1}}),ie.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){ie.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),ie.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var jt=ie.now(),Lt=/\?/,Ht=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;ie.parseJSON=function(t){if(e.JSON&&e.JSON.parse)return e.JSON.parse(t+"");var n,r=null,i=ie.trim(t+"");return i&&!ie.trim(i.replace(Ht,function(e,t,i,o){return n&&t&&(r=0),0===r?e:(n=i||t,r+=!o-!i,"")}))?Function("return "+i)():ie.error("Invalid JSON: "+t)},ie.parseXML=function(t){var n,r;if(!t||"string"!=typeof t)return null;try{e.DOMParser?(r=new DOMParser,n=r.parseFromString(t,"text/xml")):(n=new ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(t))}catch(i){n=void 0}return n&&n.documentElement&&!n.getElementsByTagName("parsererror").length||ie.error("Invalid XML: "+t),n};var qt,_t,Mt=/#.*$/,Ft=/([?&])_=[^&]*/,Ot=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Bt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Pt=/^(?:GET|HEAD)$/,Rt=/^\/\//,Wt=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,$t={},zt={},It="*/".concat("*");try{_t=location.href}catch(Xt){_t=he.createElement("a"),_t.href="",_t=_t.href}qt=Wt.exec(_t.toLowerCase())||[],ie.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:_t,type:"GET",isLocal:Bt.test(qt[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":It,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":ie.parseJSON,"text xml":ie.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?W(W(e,ie.ajaxSettings),t):W(ie.ajaxSettings,e)},ajaxPrefilter:P($t),ajaxTransport:P(zt),ajax:function(e,t){function n(e,t,n,r){var i,c,v,y,x,T=t;2!==b&&(b=2,s&&clearTimeout(s),l=void 0,a=r||"",w.readyState=e>0?4:0,i=e>=200&&300>e||304===e,n&&(y=$(d,w,n)),y=z(d,y,w,i),i?(d.ifModified&&(x=w.getResponseHeader("Last-Modified"),x&&(ie.lastModified[o]=x),x=w.getResponseHeader("etag"),x&&(ie.etag[o]=x)),204===e||"HEAD"===d.type?T="nocontent":304===e?T="notmodified":(T=y.state,c=y.data,v=y.error,i=!v)):(v=T,(e||!T)&&(T="error",0>e&&(e=0))),w.status=e,w.statusText=(t||T)+"",i?h.resolveWith(f,[c,T,w]):h.rejectWith(f,[w,T,v]),w.statusCode(g),g=void 0,u&&p.trigger(i?"ajaxSuccess":"ajaxError",[w,d,i?c:v]),m.fireWith(f,[w,T]),u&&(p.trigger("ajaxComplete",[w,d]),--ie.active||ie.event.trigger("ajaxStop")))}"object"==typeof e&&(t=e,e=void 0),t=t||{};var r,i,o,a,s,u,l,c,d=ie.ajaxSetup({},t),f=d.context||d,p=d.context&&(f.nodeType||f.jquery)?ie(f):ie.event,h=ie.Deferred(),m=ie.Callbacks("once memory"),g=d.statusCode||{},v={},y={},b=0,x="canceled",w={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c)for(c={};t=Ot.exec(a);)c[t[1].toLowerCase()]=t[2];t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=y[n]=y[n]||e,v[e]=t),this},overrideMimeType:function(e){return b||(d.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)g[t]=[g[t],e[t]];else w.always(e[w.status]);return this},abort:function(e){var t=e||x;return l&&l.abort(t),n(0,t),this}};if(h.promise(w).complete=m.add,w.success=w.done,w.error=w.fail,d.url=((e||d.url||_t)+"").replace(Mt,"").replace(Rt,qt[1]+"//"),d.type=t.method||t.type||d.method||d.type,d.dataTypes=ie.trim(d.dataType||"*").toLowerCase().match(be)||[""],null==d.crossDomain&&(r=Wt.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]===qt[1]&&r[2]===qt[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(qt[3]||("http:"===qt[1]?"80":"443")))),d.data&&d.processData&&"string"!=typeof d.data&&(d.data=ie.param(d.data,d.traditional)),R($t,d,t,w),2===b)return w;u=ie.event&&d.global,u&&0===ie.active++&&ie.event.trigger("ajaxStart"),d.type=d.type.toUpperCase(),d.hasContent=!Pt.test(d.type),o=d.url,d.hasContent||(d.data&&(o=d.url+=(Lt.test(o)?"&":"?")+d.data,delete d.data),d.cache===!1&&(d.url=Ft.test(o)?o.replace(Ft,"$1_="+jt++):o+(Lt.test(o)?"&":"?")+"_="+jt++)),d.ifModified&&(ie.lastModified[o]&&w.setRequestHeader("If-Modified-Since",ie.lastModified[o]),ie.etag[o]&&w.setRequestHeader("If-None-Match",ie.etag[o])),(d.data&&d.hasContent&&d.contentType!==!1||t.contentType)&&w.setRequestHeader("Content-Type",d.contentType),w.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+("*"!==d.dataTypes[0]?", "+It+"; q=0.01":""):d.accepts["*"]);for(i in d.headers)w.setRequestHeader(i,d.headers[i]);if(d.beforeSend&&(d.beforeSend.call(f,w,d)===!1||2===b))return w.abort();x="abort";for(i in{success:1,error:1,complete:1})w[i](d[i]);if(l=R(zt,d,t,w)){w.readyState=1,u&&p.trigger("ajaxSend",[w,d]),d.async&&d.timeout>0&&(s=setTimeout(function(){w.abort("timeout")},d.timeout));try{b=1,l.send(v,n)}catch(T){if(!(2>b))throw T;n(-1,T)}}else n(-1,"No Transport");return w},getJSON:function(e,t,n){return ie.get(e,t,n,"json")},getScript:function(e,t){return ie.get(e,void 0,t,"script")}}),ie.each(["get","post"],function(e,t){ie[t]=function(e,n,r,i){return ie.isFunction(n)&&(i=i||r,r=n,n=void 0),ie.ajax({url:e,type:t,dataType:i,data:n,success:r})}}),ie._evalUrl=function(e){return ie.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},ie.fn.extend({wrapAll:function(e){if(ie.isFunction(e))return this.each(function(t){ie(this).wrapAll(e.call(this,t))});if(this[0]){var t=ie(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return ie.isFunction(e)?this.each(function(t){ie(this).wrapInner(e.call(this,t))}):this.each(function(){var t=ie(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=ie.isFunction(e);return this.each(function(n){ie(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){ie.nodeName(this,"body")||ie(this).replaceWith(this.childNodes)}).end()}}),ie.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!ne.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||ie.css(e,"display"))},ie.expr.filters.visible=function(e){return!ie.expr.filters.hidden(e)};var Ut=/%20/g,Vt=/\[\]$/,Jt=/\r?\n/g,Yt=/^(?:submit|button|image|reset|file)$/i,Gt=/^(?:input|select|textarea|keygen)/i;ie.param=function(e,t){var n,r=[],i=function(e,t){t=ie.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=ie.ajaxSettings&&ie.ajaxSettings.traditional),ie.isArray(e)||e.jquery&&!ie.isPlainObject(e))ie.each(e,function(){i(this.name,this.value)});else for(n in e)I(n,e[n],t,i);return r.join("&").replace(Ut,"+")},ie.fn.extend({serialize:function(){return ie.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=ie.prop(this,"elements");return e?ie.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!ie(this).is(":disabled")&&Gt.test(this.nodeName)&&!Yt.test(e)&&(this.checked||!je.test(e))}).map(function(e,t){var n=ie(this).val();return null==n?null:ie.isArray(n)?ie.map(n,function(e){return{name:t.name,value:e.replace(Jt,"\r\n")}}):{name:t.name,value:n.replace(Jt,"\r\n")}}).get()}}),ie.ajaxSettings.xhr=void 0!==e.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&X()||U()}:X;var Qt=0,Kt={},Zt=ie.ajaxSettings.xhr();e.attachEvent&&e.attachEvent("onunload",function(){for(var e in Kt)Kt[e](void 0,!0)}),ne.cors=!!Zt&&"withCredentials"in Zt,Zt=ne.ajax=!!Zt,Zt&&ie.ajaxTransport(function(e){if(!e.crossDomain||ne.cors){var t;return{send:function(n,r){var i,o=e.xhr(),a=++Qt;if(o.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(i in e.xhrFields)o[i]=e.xhrFields[i];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType),e.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(i in n)void 0!==n[i]&&o.setRequestHeader(i,n[i]+"");o.send(e.hasContent&&e.data||null),t=function(n,i){var s,u,l;if(t&&(i||4===o.readyState))if(delete Kt[a],t=void 0,o.onreadystatechange=ie.noop,i)4!==o.readyState&&o.abort();else{l={},s=o.status,"string"==typeof o.responseText&&(l.text=o.responseText);try{u=o.statusText}catch(c){u=""}s||!e.isLocal||e.crossDomain?1223===s&&(s=204):s=l.text?200:404}l&&r(s,u,l,o.getAllResponseHeaders())},e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=Kt[a]=t:t()},abort:function(){t&&t(void 0,!0)}}}}),ie.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return ie.globalEval(e),e}}}),ie.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),ie.ajaxTransport("script",function(e){if(e.crossDomain){var t,n=he.head||ie("head")[0]||he.documentElement;return{send:function(r,i){t=he.createElement("script"),t.async=!0,e.scriptCharset&&(t.charset=e.scriptCharset),t.src=e.url,t.onload=t.onreadystatechange=function(e,n){(n||!t.readyState||/loaded|complete/.test(t.readyState))&&(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),t=null,n||i(200,"success"))},n.insertBefore(t,n.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var en=[],tn=/(=)\?(?=&|$)|\?\?/;ie.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=en.pop()||ie.expando+"_"+jt++;return this[e]=!0,e}}),ie.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,a,s=t.jsonp!==!1&&(tn.test(t.url)?"url":"string"==typeof t.data&&!(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&tn.test(t.data)&&"data");return s||"jsonp"===t.dataTypes[0]?(i=t.jsonpCallback=ie.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,s?t[s]=t[s].replace(tn,"$1"+i):t.jsonp!==!1&&(t.url+=(Lt.test(t.url)?"&":"?")+t.jsonp+"="+i),t.converters["script json"]=function(){return a||ie.error(i+" was not called"),a[0]},t.dataTypes[0]="json",o=e[i],e[i]=function(){a=arguments},r.always(function(){e[i]=o,t[i]&&(t.jsonpCallback=n.jsonpCallback,en.push(i)),a&&ie.isFunction(o)&&o(a[0]),a=o=void 0}),"script"):void 0}),ie.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||he;var r=de.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=ie.buildFragment([e],t,i),i&&i.length&&ie(i).remove(),ie.merge([],r.childNodes))};var nn=ie.fn.load;ie.fn.load=function(e,t,n){if("string"!=typeof e&&nn)return nn.apply(this,arguments);var r,i,o,a=this,s=e.indexOf(" ");return s>=0&&(r=ie.trim(e.slice(s,e.length)),e=e.slice(0,s)),ie.isFunction(t)?(n=t,t=void 0):t&&"object"==typeof t&&(o="POST"),a.length>0&&ie.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){i=arguments,a.html(r?ie("<div>").append(ie.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){a.each(n,i||[e.responseText,t,e])}),this},ie.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ie.fn[t]=function(e){return this.on(t,e)}}),ie.expr.filters.animated=function(e){return ie.grep(ie.timers,function(t){return e===t.elem}).length};var rn=e.document.documentElement;ie.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l,c=ie.css(e,"position"),d=ie(e),f={};"static"===c&&(e.style.position="relative"),s=d.offset(),o=ie.css(e,"top"),u=ie.css(e,"left"),l=("absolute"===c||"fixed"===c)&&ie.inArray("auto",[o,u])>-1,l?(r=d.position(),a=r.top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),ie.isFunction(t)&&(t=t.call(e,n,s)),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):d.css(f)}},ie.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){ie.offset.setOffset(this,e,t)});var t,n,r={top:0,left:0},i=this[0],o=i&&i.ownerDocument;if(o)return t=o.documentElement,ie.contains(t,i)?(typeof i.getBoundingClientRect!==Ce&&(r=i.getBoundingClientRect()),n=V(o),{top:r.top+(n.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(n.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}):r},position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===ie.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),ie.nodeName(e[0],"html")||(n=e.offset()),n.top+=ie.css(e[0],"borderTopWidth",!0),n.left+=ie.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-ie.css(r,"marginTop",!0),left:t.left-n.left-ie.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||rn;e&&!ie.nodeName(e,"html")&&"static"===ie.css(e,"position");)e=e.offsetParent;return e||rn})}}),ie.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n=/Y/.test(t);ie.fn[e]=function(r){return De(this,function(e,r,i){var o=V(e);return void 0===i?o?t in o?o[t]:o.document.documentElement[r]:e[r]:void(o?o.scrollTo(n?ie(o).scrollLeft():i,n?i:ie(o).scrollTop()):e[r]=i)},e,r,arguments.length,null)}}),ie.each(["top","left"],function(e,t){ie.cssHooks[t]=k(ne.pixelPosition,function(e,n){return n?(n=tt(e,t),rt.test(n)?ie(e).position()[t]+"px":n):void 0})}),ie.each({Height:"height",Width:"width"},function(e,t){ie.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){ie.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),a=n||(r===!0||i===!0?"margin":"border"); return De(this,function(t,n,r){var i;return ie.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(i=t.documentElement,Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])):void 0===r?ie.css(t,n,a):ie.style(t,n,r,a)},t,o?r:void 0,o,null)}})}),ie.fn.size=function(){return this.length},ie.fn.andSelf=ie.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return ie});var on=e.jQuery,an=e.$;return ie.noConflict=function(t){return e.$===ie&&(e.$=an),t&&e.jQuery===ie&&(e.jQuery=on),ie},typeof t===Ce&&(e.jQuery=e.$=ie),ie}); },{}],7:[function(require,module,exports){ "use strict";module.exports=function(d){var e=encodeURIComponent(d.getURL());return{popup:!0,shareText:{bg:"cподеляне",da:"del",de:"teilen",en:"share",es:"compartir",fi:"Jaa",fr:"partager",hr:"podijelite",hu:"megosztás",it:"condividi",ja:"共有",ko:"공유하기",nl:"delen",no:"del",pl:"udostępnij",pt:"compartilhar",ro:"partajează",ru:"поделиться",sk:"zdieľať",sl:"deli",sr:"podeli",sv:"dela",tr:"paylaş",zh:"分享"},name:"addthis",faName:"fa-plus",title:{bg:"Сподели в AddThis",da:"Del på AddThis",de:"Bei AddThis teilen",en:"Share on AddThis",es:"Compartir en AddThis",fi:"Jaa AddThisissä",fr:"Partager sur AddThis",hr:"Podijelite na AddThis",hu:"Megosztás AddThisen",it:"Condividi su AddThis",ja:"AddThis上で共有",ko:"AddThis에서 공유하기",nl:"Delen op AddThis",no:"Del på AddThis",pl:"Udostępnij przez AddThis",pt:"Compartilhar no AddThis",ro:"Partajează pe AddThis",ru:"Поделиться на AddThis",sk:"Zdieľať na AddThis",sl:"Deli na AddThis",sr:"Podeli na AddThis",sv:"Dela på AddThis",tr:"AddThis'ta paylaş",zh:"在AddThis上分享"},shareUrl:"http://api.addthis.com/oexchange/0.8/offer?url="+e+d.getReferrerTrack()}}; },{}],8:[function(require,module,exports){ "use strict";module.exports=function(e){var o=encodeURIComponent(e.getURL());return{popup:!0,shareText:{bg:"cподеляне",da:"del",de:"teilen",en:"share",es:"compartir",fi:"Jaa",fr:"partager",hr:"podijelite",hu:"megosztás",it:"condividi",ja:"共有",ko:"공유하기",nl:"delen",no:"del",pl:"udostępnij",pt:"compartilhar",ro:"partajează",ru:"поделиться",sk:"zdieľať",sl:"deli",sr:"podeli",sv:"dela",tr:"paylaş",zh:"分享"},name:"facebook",faName:"fa-facebook",title:{bg:"Сподели във Facebook",da:"Del på Facebook",de:"Bei Facebook teilen",en:"Share on Facebook",es:"Compartir en Facebook",fi:"Jaa Facebookissa",fr:"Partager sur Facebook",hr:"Podijelite na Facebooku",hu:"Megosztás Facebookon",it:"Condividi su Facebook",ja:"フェイスブック上で共有",ko:"페이스북에서 공유하기",nl:"Delen op Facebook",no:"Del på Facebook",pl:"Udostępnij na Facebooku",pt:"Compartilhar no Facebook",ro:"Partajează pe Facebook",ru:"Поделиться на Facebook",sk:"Zdieľať na Facebooku",sl:"Deli na Facebooku",sr:"Podeli na Facebook-u",sv:"Dela på Facebook",tr:"Facebook'ta paylaş",zh:"在Facebook上分享"},shareUrl:"https://www.facebook.com/sharer/sharer.php?u="+o+e.getReferrerTrack()}}; },{}],9:[function(require,module,exports){ "use strict";module.exports=function(t){var e=encodeURIComponent(t.getURL()),o=t.getMeta("DC.title"),r=t.getMeta("DC.creator"),n=t.getMeta("description");return o.length>0&&r.length>0?o+=" - "+r:o=t.getTitle(),{popup:!0,shareText:"Flattr",name:"flattr",faName:"fa-money",title:{de:"Artikel flattrn",en:"Flattr this"},shareUrl:"https://flattr.com/submit/auto?title="+encodeURIComponent(o)+"&description="+encodeURIComponent(n)+"&category="+encodeURIComponent(t.options.flattrCategory||"text")+"&user_id="+encodeURIComponent(t.options.flattrUser)+"&url="+e+t.getReferrerTrack()}}; },{}],10:[function(require,module,exports){ "use strict";module.exports=function(o){var e=encodeURIComponent(o.getURL());return{popup:!0,shareText:"+1",name:"googleplus",faName:"fa-google-plus",title:{bg:"Сподели в Google+",da:"Del på Google+",de:"Bei Google+ teilen",en:"Share on Google+",es:"Compartir en Google+",fi:"Jaa Google+:ssa",fr:"Partager sur Goolge+",hr:"Podijelite na Google+",hu:"Megosztás Google+on",it:"Condividi su Google+",ja:"Google+上で共有",ko:"Google+에서 공유하기",nl:"Delen op Google+",no:"Del på Google+",pl:"Udostępnij na Google+",pt:"Compartilhar no Google+",ro:"Partajează pe Google+",ru:"Поделиться на Google+",sk:"Zdieľať na Google+",sl:"Deli na Google+",sr:"Podeli na Google+",sv:"Dela på Google+",tr:"Google+'da paylaş",zh:"在Google+上分享"},shareUrl:"https://plus.google.com/share?url="+e+o.getReferrerTrack()}}; },{}],11:[function(require,module,exports){ "use strict";module.exports=function(e){return{blank:!0,popup:!1,shareText:"Info",name:"info",faName:"fa-info",title:{de:"weitere Informationen",en:"more information",es:"más informaciones",fr:"plus d'informations",it:"maggiori informazioni",da:"flere oplysninger",nl:"verdere informatie"},shareUrl:e.getInfoUrl()}}; },{}],12:[function(require,module,exports){ "use strict";module.exports=function(e){var n=encodeURIComponent(e.getURL());return{popup:!0,shareText:{de:"mitteilen",en:"share",es:"compartir",fi:"Jaa",fr:"partager",hr:"podijelite",hu:"megosztás",it:"condividi",ja:"シェア",ko:"공유하기",nl:"delen",no:"del",pl:"udostępnij",pt:"compartilhar",ro:"distribuiți",ru:"поделиться",sk:"zdieľať",sl:"deli",sr:"podeli",sv:"dela",tr:"paylaş",zh:"分享"},name:"linkedin",faName:"fa-linkedin",title:{bg:"Сподели в LinkedIn",da:"Del på LinkedIn",de:"Bei LinkedIn teilen",en:"Share on LinkedIn",es:"Compartir en LinkedIn",fi:"Jaa LinkedInissä",fr:"Partager sur LinkedIn",hr:"Podijelite na LinkedIn",hu:"Megosztás LinkedInen",it:"Condividi su LinkedIn",ja:"LinkedIn上で共有",ko:"LinkedIn에서 공유하기",nl:"Delen op LinkedIn",no:"Del på LinkedIn",pl:"Udostępnij przez LinkedIn",pt:"Compartilhar no LinkedIn",ro:"Partajează pe LinkedIn",ru:"Поделиться на LinkedIn",sk:"Zdieľať na LinkedIn",sl:"Deli na LinkedIn",sr:"Podeli na LinkedIn-u",sv:"Dela på LinkedIn",tr:"LinkedIn'ta paylaş",zh:"在LinkedIn上分享"},shareUrl:"https://www.linkedin.com/cws/share?url="+n+e.getReferrerTrack()}}; },{}],13:[function(require,module,exports){ "use strict";module.exports=function(e){var i=e.getOption("mailUrl");return 0===i.indexOf("mailto:")&&(i+="?subject="+encodeURIComponent(e.getOption("mailSubject")),i+="&body="+encodeURIComponent(e.getOption("mailBody"))),{blank:0===i.indexOf("http"),popup:!1,shareText:"mail",name:"mail",faName:"fa-envelope",title:{bg:"Изпрати по имейл",da:"Sende via e-mail",de:"Per E-Mail versenden",en:"Send by email",es:"Enviar por email",fi:"Lähetä sähköpostitse",fr:"Envoyer par courriel",hr:"Pošaljite emailom",hu:"Elküldés e-mailben",it:"Inviare via email",ja:"電子メールで送信",ko:"이메일로 보내기",nl:"Sturen via e-mail",no:"Send via epost",pl:"Wyślij e-mailem",pt:"Enviar por e-mail",ro:"Trimite prin e-mail",ru:"Отправить по эл. почте",sk:"Poslať e-mailom",sl:"Pošlji po elektronski pošti",sr:"Pošalji putem email-a",sv:"Skicka via e-post",tr:"E-posta ile gönder",zh:"通过电子邮件传送"},shareUrl:i}}; },{}],14:[function(require,module,exports){ "use strict";var url=require("url");module.exports=function(e){var t=e.getMeta("DC.title")||e.getTitle(),r=e.getMeta("DC.creator");r.length>0&&(t+=" - "+r);var i=e.getOption("mediaUrl");i&&i.length<=0&&(i=e.getMeta("og:image"));var n=url.parse("https://www.pinterest.com/pin/create/link/",!0);return n.query.url=e.getURL(),n.query.media=i,n.query.description=t,delete n.search,{popup:!0,shareText:"pin it",name:"pinterest",faName:"fa-pinterest-p",title:{de:"Bei Pinterest pinnen",en:"Pin it on Pinterest",es:"Compartir en Pinterest",fr:"Partager sur Pinterest",it:"Condividi su Pinterest",da:"Del på Pinterest",nl:"Delen op Pinterest"},shareUrl:url.format(n)+e.getReferrerTrack()}}; },{"url":5}],15:[function(require,module,exports){ "use strict";module.exports=function(t){var e=encodeURIComponent(t.getURL()),r=t.getMeta("DC.title"),l=t.getMeta("DC.creator");return r.length>0&&l.length>0?r+=" - "+l:r=t.getTitle(),{popup:!0,shareText:{bg:"cподеляне",da:"del",de:"teilen",en:"share",es:"compartir",fi:"Jaa",fr:"partager",hr:"podijelite",hu:"megosztás",it:"condividi",ja:"共有",ko:"공유하기",nl:"delen",no:"del",pl:"udostępnij",pt:"compartilhar",ro:"partajează",ru:"поделиться",sk:"zdieľať",sl:"deli",sr:"podeli",sv:"dela",tr:"paylaş",zh:"分享"},name:"tumblr",faName:"fa-tumblr",title:{bg:"Сподели в tumblr",da:"Del på tumblr",de:"Bei tumblr teilen",en:"Share on tumblr",es:"Compartir en tumblr",fi:"Jaa tumblrissä",fr:"Partager sur tumblr",hr:"Podijelite na tumblr",hu:"Megosztás tumblren",it:"Condividi su tumblr",ja:"tumblr上で共有",ko:"tumblr에서 공유하기",nl:"Delen op tumblr",no:"Del på tumblr",pl:"Udostępnij przez tumblr",pt:"Compartilhar no tumblr",ro:"Partajează pe tumblr",ru:"Поделиться на tumblr",sk:"Zdieľať na tumblr",sl:"Deli na tumblr",sr:"Podeli na tumblr-u",sv:"Dela på tumblr",tr:"tumblr'ta paylaş",zh:"在tumblr上分享"},shareUrl:"http://tumblr.com/widgets/share/tool?canonicalUrl="+e+t.getReferrerTrack()}}; },{}],16:[function(require,module,exports){ "use strict";var url=require("url"),$=require("jquery"),abbreviateText=function(t,e){var r=$("<div/>").html(t).text();if(r.length<=e)return t;var i=r.substring(0,e-1).lastIndexOf(" ");return r=r.substring(0,i)+"…"};module.exports=function(t){var e=url.parse("https://twitter.com/intent/tweet",!0),r=t.getMeta("DC.title"),i=t.getMeta("DC.creator");return r.length>0&&i.length>0?r+=" - "+i:r=t.getTitle(),e.query.text=abbreviateText(r,120),e.query.url=t.getURL(),null!==t.options.twitterVia&&(e.query.via=t.options.twitterVia),delete e.search,{popup:!0,shareText:"tweet",name:"twitter",faName:"fa-twitter",title:{bg:"Сподели в Twitter",da:"Del på Twitter",de:"Bei Twitter teilen",en:"Share on Twitter",es:"Compartir en Twitter",fi:"Jaa Twitterissä",fr:"Partager sur Twitter",hr:"Podijelite na Twitteru",hu:"Megosztás Twitteren",it:"Condividi su Twitter",ja:"ツイッター上で共有",ko:"트위터에서 공유하기",nl:"Delen op Twitter",no:"Del på Twitter",pl:"Udostępnij na Twitterze",pt:"Compartilhar no Twitter",ro:"Partajează pe Twitter",ru:"Поделиться на Twitter",sk:"Zdieľať na Twitteri",sl:"Deli na Twitterju",sr:"Podeli na Twitter-u",sv:"Dela på Twitter",tr:"Twitter'da paylaş",zh:"在Twitter上分享"},shareUrl:url.format(e)+t.getReferrerTrack()}}; },{"jquery":6,"url":5}],17:[function(require,module,exports){ "use strict";module.exports=function(a){var p=encodeURIComponent(a.getURL()),e=a.getMeta("DC.title"),t=a.getMeta("DC.creator");return e.length>0&&t.length>0?e+=" - "+t:e=a.getTitle(),{popup:!1,shareText:{bg:"cподеляне",da:"del",de:"teilen",en:"share",es:"compartir",fi:"Jaa",fr:"partager",hr:"podijelite",hu:"megosztás",it:"condividi",ja:"共有",ko:"공유하기",nl:"delen",no:"del",pl:"udostępnij",pt:"compartilhar",ro:"partajează",ru:"поделиться",sk:"zdieľať",sl:"deli",sr:"podeli",sv:"dela",tr:"paylaş",zh:"分享"},name:"whatsapp",faName:"fa-whatsapp",title:{bg:"Сподели в Whatsapp",da:"Del på Whatsapp",de:"Bei Whatsapp teilen",en:"Share on Whatsapp",es:"Compartir en Whatsapp",fi:"Jaa WhatsAppissä",fr:"Partager sur Whatsapp",hr:"Podijelite na Whatsapp",hu:"Megosztás WhatsAppen",it:"Condividi su Whatsapp",ja:"Whatsapp上で共有",ko:"Whatsapp에서 공유하기",nl:"Delen op Whatsapp",no:"Del på Whatsapp",pl:"Udostępnij przez WhatsApp",pt:"Compartilhar no Whatsapp",ro:"Partajează pe Whatsapp",ru:"Поделиться на Whatsapp",sk:"Zdieľať na Whatsapp",sl:"Deli na Whatsapp",sr:"Podeli na WhatsApp-u",sv:"Dela på Whatsapp",tr:"Whatsapp'ta paylaş",zh:"在Whatsapp上分享"},shareUrl:"whatsapp://send?text="+encodeURIComponent(e)+"%20"+p+a.getReferrerTrack()}}; },{}],18:[function(require,module,exports){ "use strict";module.exports=function(e){var r=encodeURIComponent(e.getURL());return{popup:!0,shareText:{de:"teilen",en:"share",es:"compartir",fr:"partager",it:"condividi",da:"del",nl:"delen"},name:"xing",faName:"fa-xing",title:{de:"Bei XING teilen",en:"Share on XING",es:"Compartir en XING",fr:"Partager sur XING",it:"Condividi su XING",da:"Del på XING",nl:"Delen op XING"},shareUrl:"https://www.xing.com/social_plugins/share?url="+r+e.getReferrerTrack()}}; },{}],19:[function(require,module,exports){ (function (global){ "use strict";var $=require("jquery"),url=require("url"),Shariff=function(t,e){var r=this;this.element=t,$(t).empty(),this.options=$.extend({},this.defaults,e,$(t).data());var i=[require("./services/addthis"),require("./services/facebook"),require("./services/flattr"),require("./services/googleplus"),require("./services/info"),require("./services/linkedin"),require("./services/mail"),require("./services/pinterest"),require("./services/twitter"),require("./services/whatsapp"),require("./services/xing"),require("./services/tumblr")];this.services=$.map(this.options.services,function(t){var e;return i.forEach(function(i){return i=i(r),i.name===t?(e=i,null):void 0}),e}),this._addButtonList(),null!==this.options.backendUrl&&this.getShares().then($.proxy(this._updateCounts,this))};Shariff.prototype={defaults:{theme:"color",backendUrl:null,infoUrl:"http://ct.de/-2467514",lang:"de",langFallback:"en",mailUrl:function(){var t=url.parse(this.getURL(),!0);return t.query.view="mail",delete t.search,url.format(t)},mailSubject:function(){return this.getMeta("DC.title")||this.getTitle()},mailBody:function(){return"<"+this.getURL()+">"},mediaUrl:null,orientation:"horizontal",referrerTrack:null,services:["twitter","facebook","googleplus","info"],title:function(){return $("head title").text()},twitterVia:null,flattrUser:null,flattrCategory:null,url:function(){var t=global.document.location.href,e=$("link[rel=canonical]").attr("href")||this.getMeta("og:url")||"";return e.length>0&&(e.indexOf("http")<0&&(e=global.document.location.protocol+"//"+global.document.location.host+e),t=e),t}},$socialshareElement:function(){return $(this.element)},getLocalized:function(t,e){return"object"==typeof t[e]?"undefined"==typeof t[e][this.options.lang]?t[e][this.options.langFallback]:t[e][this.options.lang]:"string"==typeof t[e]?t[e]:void 0},getMeta:function(t){var e=$('meta[name="'+t+'"],[property="'+t+'"]').attr("content");return e||""},getInfoUrl:function(){return this.options.infoUrl},getURL:function(){return this.getOption("url")},getOption:function(t){var e=this.options[t];return"function"==typeof e?$.proxy(e,this)():e},getTitle:function(){return this.getOption("title")},getReferrerTrack:function(){return this.options.referrerTrack||""},getShares:function(){var t=url.parse(this.options.backendUrl,!0);return t.query.url=this.getURL(),delete t.search,$.getJSON(url.format(t))},_updateCounts:function(t){var e=this;$.each(t,function(t,r){r>=1e3&&(r=Math.round(r/1e3)+"k"),$(e.element).find("."+t+" a").append('<span class="share_count">'+r)})},_addButtonList:function(){var t=this,e=this.$socialshareElement(),r="theme-"+this.options.theme,i="orientation-"+this.options.orientation,n="col-"+this.options.services.length,a=$("<ul>").addClass(r).addClass(i).addClass(n);this.services.forEach(function(e){var r=$('<li class="shariff-button">').addClass(e.name),i='<span class="share_text">'+t.getLocalized(e,"shareText"),n=$("<a>").attr("href",e.shareUrl).append(i);"undefined"!=typeof e.faName&&n.prepend('<span class="fa '+e.faName+'">'),e.popup?n.attr("rel","popup"):e.blank&&n.attr("target","_blank"),n.attr("title",t.getLocalized(e,"title")),n.attr("role","button"),n.attr("aria-label",t.getLocalized(e,"title")),r.append(n),a.append(r)}),a.on("click",'[rel="popup"]',function(t){t.preventDefault();var e=$(this).attr("href"),r="_blank",i="600",n="460",a="width="+i+",height="+n;global.window.open(e,r,a)}),e.append(a)}},module.exports=Shariff,global.Shariff=Shariff,$(".shariff").each(function(){this.hasOwnProperty("shariff")||(this.shariff=new Shariff(this))}); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./services/addthis":7,"./services/facebook":8,"./services/flattr":9,"./services/googleplus":10,"./services/info":11,"./services/linkedin":12,"./services/mail":13,"./services/pinterest":14,"./services/tumblr":15,"./services/twitter":16,"./services/whatsapp":17,"./services/xing":18,"jquery":6,"url":5}]},{},[19]);
universal_api_project_template/shared/lib/devtools.js
Mikeysax/mikey
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="ctrl-h" changePositionKey="ctrl-w"> <LogMonitor /> </DockMonitor> );
app/components/ToggleOption/index.js
jose4125/stt
/** * * ToggleOption * */ import React from 'react' import { injectIntl, intlShape } from 'react-intl' const ToggleOption = ({ value, message, intl }) => ( <option value={value}> {message ? intl.formatMessage(message) : value} </option> ) ToggleOption.propTypes = { value: React.PropTypes.string.isRequired, message: React.PropTypes.object, intl: intlShape.isRequired, } export default injectIntl(ToggleOption)
src/MessageBox/HeaderLayout1.js
nirhart/wix-style-react
import React from 'react'; import classNames from 'classnames'; import * as styles from './HeaderLayout1.scss'; import SvgX from '../svg/X.js'; const HeaderLayout1 = ({title, onCancel, style, theme}) => { //TODO When deprecation ends, _theme won't be needed. let _theme; if (style) { console.warn('[wix-style-react>HeaderLayout1] Warning. Property \'style\' has been deprecated, and will be removed Jan 1st 2017. Please use \'theme\' instead.'); _theme = style; } else { _theme = theme; } return ( <div className={classNames(styles.header, styles[_theme])} > <span className={styles.titleLabel}> {title} </span> <button className={styles.close} onClick={onCancel}> <SvgX width={9} height={9} thickness={1} color={'white'}/> </button> </div> ); }; HeaderLayout1.defaultProps = { theme: 'blue' }; HeaderLayout1.propTypes = { title: React.PropTypes.node, onCancel: React.PropTypes.func, style: React.PropTypes.oneOf(['red', 'green', 'blue', 'lightGreen']), theme: React.PropTypes.oneOf(['red', 'green', 'blue', 'lightGreen']) }; export default HeaderLayout1;
test/specs/collections/Table/TableRow-test.js
Rohanhacker/Semantic-UI-React
import React from 'react' import * as common from 'test/specs/commonTests' import TableRow from 'src/collections/Table/TableRow' describe('TableRow', () => { common.isConformant(TableRow) common.rendersChildren(TableRow) common.implementsCreateMethod(TableRow) common.implementsTextAlignProp(TableRow) common.implementsVerticalAlignProp(TableRow) common.propKeyOnlyToClassName(TableRow, 'active') common.propKeyOnlyToClassName(TableRow, 'disabled') common.propKeyOnlyToClassName(TableRow, 'error') common.propKeyOnlyToClassName(TableRow, 'negative') common.propKeyOnlyToClassName(TableRow, 'positive') common.propKeyOnlyToClassName(TableRow, 'warning') it('renders as a tr by default', () => { shallow(<TableRow />) .should.have.tagName('tr') }) describe('shorthand', () => { const cells = ['Name', 'Status', 'Notes'] it('renders empty tr with no shorthand', () => { const wrapper = mount(<TableRow />) wrapper.find('td').should.have.lengthOf(0) }) it('renders the cells', () => { const wrapper = mount(<TableRow cells={cells} />) wrapper.find('td').should.have.lengthOf(cells.length) }) it('renders the cells using cellAs', () => { const cellAs = 'th' const wrapper = mount(<TableRow cells={cells} cellAs={cellAs} />) wrapper.find(cellAs).should.have.lengthOf(cells.length) }) }) })
source/src/main/webapp/resources/lib/ext-6.0.1/src/layout/container/Box.js
iLevshevich/ExtJsCRUDMVC
/** * Base Class for HBoxLayout and VBoxLayout Classes. Generally it should not need to be used directly. */ Ext.define('Ext.layout.container.Box', { extend: 'Ext.layout.container.Container', alias: 'layout.box', alternateClassName: 'Ext.layout.BoxLayout', requires: [ 'Ext.layout.container.boxOverflow.None', 'Ext.layout.container.boxOverflow.Scroller', 'Ext.util.Format', 'Ext.dd.DragDropManager', 'Ext.resizer.Splitter' ], type: 'box', config: { /** * @cfg {String} [align="begin"] * Controls how the child items of the container are aligned. The value is used to * position items "perpendicularly". That is, for horizontal boxes (where `vertical` * is `false`), then this will position items vertically. Otherwise, this will position * items horizontally. The acceptable values for this property are best explained in * context with the value of `vertical`. * * If `vertical` is `false` then this layout is behaving as an `hbox` and this config * operates as follows: * * - **begin** : Child items are aligned vertically at the top of the container. * - **middle** : Child items are vertically centered in the container. * - **end** : Child items are aligned vertically at the bottom of the container. * - **stretch** : Child items are stretched vertically to fill the height of the container. * - **stretchmax** : Child items are stretched vertically to the height of the largest item. * * If `vertical` is `true` then this layout is behaving as an `vbox` and this config * operates as follows: * * - **begin** : Child items are aligned horizontally at the left side of the container. * - **middle** : Child items are horizontally centered in the container. * - **end** : Child items are aligned horizontally at the right of the container. * - **stretch** : Child items are stretched horizontally to fill the width of the container. * - **stretchmax** : Child items are stretched horizontally to the size of the largest item. * * For backwards compatibility, the following values are also recognized: * * - **left** : Same as **begin**. * - **top** : Same as **begin**. * - **center** : Same as **middle**. * - **right** : Same as **end**. * - **bottom** : Same as **end**. */ align: 'begin', // end, middle, stretch, strechmax /** * @cfg {Boolean} constrainAlign * Limits the size of {@link #align aligned} components to the size of the container * under certain circumstances. Firstly, the container's height (for `hbox`) or width * (for `vbox`) must not be determined by the size of the child components. Secondly, * the child components must have {@link Ext.AbstractComponent#shrinkWrap shrinkwrap} * enabled for this dimension. */ constrainAlign: false, /** * @cfg {Boolean} [enableSplitters=true] * This flag can be set to `false` to ignore the `split` config on box items. This is * set to `false` by `Ext.layout.container.Accordion`. */ enableSplitters: true, // @cmd-auto-dependency { aliasPrefix: 'box.overflow.' } /** * @cfg {String/Ext.layout.container.boxOverflow.None} * An overflow handler or config object for an overflow handler. This is typically * specified as one of the following strings: * * - `scroller` - Scroller buttons are rendered before and after the content. * - `menu` - Overflowing items are rendered into a menu, and a button is rendered * after the items, which shows the menu when clicked. * * NOTE: This config is currently only supported when box layout is used by the * following components: * * - {@link Ext.toolbar.Toolbar} * - {@link Ext.menu.Menu} * - {@link Ext.toolbar.Breadcrumb} * - {@link Ext.tab.Bar} * * Components where `overflowHandler` is not supported should use * `{@link Ext.Component#scrollable scrollable}:true` if they have overflowing * content. */ overflowHandler: { $value: null, merge: function(newValue, oldValue) { if (typeof newValue === 'string') { newValue = { type: newValue }; } return Ext.merge(oldValue ? Ext.Object.chain(oldValue) : {}, newValue); } }, /** * @cfg {String} padding * Sets the padding to be applied to all child items managed by this layout. * * This property must be specified as a string containing space-separated, numeric * padding values. The order of the sides associated with each value matches the * way CSS processes padding values: * * - If there is only one value, it applies to all sides. * - If there are two values, the top and bottom borders are set to the first * value and the right and left are set to the second. * - If there are three values, the top is set to the first value, the left and * right are set to the second, and the bottom is set to the third. * - If there are four values, they apply to the top, right, bottom, and left, * respectively. */ padding: 0, /** * @cfg {String} pack * Controls how the child items of the container are packed together. Acceptable * configuration values for this property are: * * - **start** - child items are packed together at **left** (HBox) or **top** * (VBox) side of container (*default**) * - **center** - child items are packed together at **mid-width** (HBox) or * **mid-height** (VBox) of container * - **end** - child items are packed together at **right** (HBox) or **bottom** * (VBox) side of container */ pack: 'start', /** * @cfg {String/Ext.Component} stretchMaxPartner * Allows stretchMax calculation to take into account the max perpendicular size * (height for HBox layout and width for VBox layout) of another Box layout when * calculating its maximum perpendicular child size. * * If specified as a string, this may be either a known Container ID, or a * ComponentQuery selector which is rooted at this layout's Container (ie, to find * a sibling, use `"^>#siblingItemId`). */ stretchMaxPartner: undefined, /** * @cfg {Boolean} [vertical=false] * Set to `true` to switch the layout to `vbox`. */ vertical: false, /** * @cfg {"round"/"floor"/"ceil"} [alignRoundingMethod='round'] The Math method * to use for rounding fractional pixels when `{@link #align}:middle` is used. * The possible values are: * * - [round](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round) * - [floor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor) * - [ceil](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil) */ alignRoundingMethod: 'round' }, /** * @cfg {Number} flex * This configuration option is to be applied to **child items** of the container * managed by this layout. Each child item with a flex property will be flexed * (horizontally in `hbox`, vertically in `vbox`) according to each item's * **relative** flex value compared to the sum of all items with a flex value * specified. Any child items that have either a `flex = 0` or `flex = undefined` * will not be 'flexed' (the initial size will not be changed). */ itemCls: Ext.baseCSSPrefix + 'box-item', targetCls: Ext.baseCSSPrefix + 'box-layout-ct', targetElCls: Ext.baseCSSPrefix + 'box-target', innerCls: Ext.baseCSSPrefix + 'box-inner', manageMargins: true, createsInnerCt: true, childEls: [ 'innerCt', 'targetEl' ], renderTpl: [ '{%var oc,l=values.$comp.layout,oh=l.overflowHandler;' + 'if (oh && oh.getPrefixConfig!==Ext.emptyFn) {' + 'if(oc=oh.getPrefixConfig())dh.generateMarkup(oc, out)' + '}%}' + '<div id="{ownerId}-innerCt" data-ref="innerCt" role="presentation" class="{[l.innerCls]}' + '{[oh ? (" " + oh.getOverflowCls(l.direction)) : ""]}">' + '<div id="{ownerId}-targetEl" data-ref="targetEl" class="{targetElCls}" role="presentation">' + '{%this.renderBody(out, values)%}' + '</div>' + '</div>' + '{%if (oh && oh.getSuffixConfig!==Ext.emptyFn) {' + 'if(oc=oh.getSuffixConfig())dh.generateMarkup(oc, out)' + '}%}', { disableFormats: true, definitions: 'var dh=Ext.DomHelper;' } ], constructor: function(config) { var me = this, type; me.callParent(arguments); me.setVertical(me.vertical); // The sort function needs access to properties in this, so must be bound. me.flexSortFn = me.flexSort.bind(me); type = typeof me.padding; if (type === 'string' || type === 'number') { me.padding = Ext.util.Format.parseBox(me.padding); me.padding.height = me.padding.top + me.padding.bottom; me.padding.width = me.padding.left + me.padding.right; } }, _beginRe: /^(?:begin|left|top)$/, _centerRe: /^(?:center|middle)$/, _endRe: /^(?:end|right|bottom)$/, // Matches: `<spaces>digits[.digits]<spaces>%<spaces>` // Captures: `digits[.digits]` _percentageRe: /^\s*(\d+(?:\.\d*)?)\s*[%]\s*$/, getItemSizePolicy: function (item, ownerSizeModel) { var me = this, policy = me.sizePolicy, align = me.align, flex = item.flex, key = align, names = me.names, heightName = names.height, widthName = names.width, width = item[widthName], height = item[heightName], percentageRe = me._percentageRe, percentageWidth = percentageRe.test(width), isStretch = (align === 'stretch'), isStretchMax = (align === 'stretchmax'), constrain = me.constrainAlign; // Getting the size model is expensive, so we only want to do so if we really need it if (!ownerSizeModel && (isStretch || flex || percentageWidth || (constrain && !isStretchMax))) { ownerSizeModel = me.owner.getSizeModel(); } if (isStretch) { // If we are height.shrinkWrap, we behave as if we were stretchmax (for more // details, see beginLayoutCycle)... if (!percentageRe.test(height) && ownerSizeModel[heightName].shrinkWrap) { key = 'stretchmax'; // We leave %age height as stretch since it will not participate in the // stretchmax size calculation. This avoid running such a child in its // shrinkWrap mode prior to supplying the calculated size. } } else if (!isStretchMax) { if (percentageRe.test(height)) { // Height %ages are calculated based on container size, so they are the // same as align=stretch for this purpose... key = 'stretch'; } else if (constrain && !ownerSizeModel[heightName].shrinkWrap) { // Same functionality as stretchmax, only the max is going to be the size // of the container, not the largest item key = 'stretchmax'; } else { key = ''; } } if (flex || percentageWidth) { // If we are width.shrinkWrap, we won't be flexing since that requires a // container width... if (!ownerSizeModel[widthName].shrinkWrap) { policy = policy.flex; // both flex and %age width are calculated } } return policy[key]; }, flexSort: function (a, b) { // We need to sort the flexed items to ensure that we have // the items with max/min width first since when we set the // values we may have the value constrained, so we need to // react accordingly. Precedence is given from the largest // value through to the smallest value var maxWidthName = this.names.maxWidth, minWidthName = this.names.minWidth, infiniteValue = Infinity, aTarget = a.target, bTarget = b.target, aFlex = aTarget.flex, bFlex = bTarget.flex, result = 0, aMin, bMin, aMax, bMax, hasMin, hasMax; aMax = aTarget[maxWidthName] || infiniteValue; bMax = bTarget[maxWidthName] || infiniteValue; aMin = aTarget[minWidthName] || 0; bMin = bTarget[minWidthName] || 0; hasMin = isFinite(aMin) || isFinite(bMin); hasMax = isFinite(aMax) || isFinite(bMax); if (hasMin || hasMax) { if (hasMax) { result = aMax - bMax; } // If the result is 0, it means either // a) hasMax was false // b) The max values were the same if (result === 0 && hasMin) { result = bMin - aMin; } // If 0, it means either the max and/or minimum was the same if (result === 0) { if (hasMax) { result = bFlex - aFlex; } else { result = aFlex - bFlex; } } } return result; }, isItemBoxParent: function (itemContext) { return true; }, isItemShrinkWrap: function (item) { return true; }, roundFlex: function(width) { return Math.floor(width); }, /** * @private * Called by an owning Panel before the Panel begins its collapse process. * Most layouts will not need to override the default Ext.emptyFn implementation. */ beginCollapse: function(child) { var me = this; if (me.direction === 'vertical' && child.collapsedVertical()) { child.collapseMemento.capture(['flex']); delete child.flex; } else if (me.direction === 'horizontal' && child.collapsedHorizontal()) { child.collapseMemento.capture(['flex']); delete child.flex; } }, /** * @private * Called by an owning Panel before the Panel begins its expand process. * Most layouts will not need to override the default Ext.emptyFn implementation. */ beginExpand: function(child) { // Restores the flex if we used to be flexed before child.collapseMemento.restore(['flex']); }, beginLayout: function (ownerContext) { var me = this, owner = me.owner, smp = owner.stretchMaxPartner, style = me.innerCt.dom.style, names = me.names, overflowHandler = me.overflowHandler, scrollable = owner.getScrollable(), scrollPos; ownerContext.boxNames = names; // this must happen before callParent to allow the overflow handler to do its work // that can effect the childItems collection... if (overflowHandler) { overflowHandler.beginLayout(ownerContext); } // get the contextItem for our stretchMax buddy: if (typeof smp === 'string') { smp = Ext.getCmp(smp) || owner.query(smp)[0]; } ownerContext.stretchMaxPartner = smp && ownerContext.context.getCmp(smp); me.callParent(arguments); ownerContext.innerCtContext = ownerContext.getEl('innerCt', me); ownerContext.targetElContext = ownerContext.getEl('targetEl', me); if (scrollable) { ownerContext.ownerScrollable = scrollable; // If we have a scrollable, save the positions regardless of whether we can scroll in that direction // since the scrollable may be configured with x: false, y: false, which means it can only be // controlled programmatically scrollPos = scrollable.getPosition(); // Only restore if the component was actually scrolled in the first place if (scrollPos.x || scrollPos.y) { ownerContext.scrollRestore = scrollPos; } } // Don't allow sizes burned on to the innerCt to influence measurements. style.width = style.height = ''; }, beginLayoutCycle: function (ownerContext, firstCycle) { var me = this, state = ownerContext.state, scrollable = ownerContext.ownerScrollable, align = me.align, names = ownerContext.boxNames, pack = me.pack, centerRe = me._centerRe, overflowHandler = me.overflowHandler, canScroll = ownerContext.state.canScroll, widthModel, heightModel; // this must happen before callParent to allow the overflow handler to do its work // that can effect the childItems collection... if (overflowHandler) { overflowHandler.beginLayoutCycle(ownerContext, firstCycle); } me.callParent(arguments); // Cache several of our string concat/compare results (since width/heightModel can // change if we are invalidated, we cannot do this in beginLayout) ownerContext.parallelSizeModel = widthModel = ownerContext[names.widthModel]; ownerContext.perpendicularSizeModel = heightModel = ownerContext[names.heightModel]; ownerContext.boxOptions = { align: align = { stretch: align === 'stretch', stretchmax: align === 'stretchmax', center: centerRe.test(align), bottom: me._endRe.test(align) }, pack: pack = { center: centerRe.test(pack), end: pack === 'end' } }; // Scrolling can occur if: // a) The owner is configured to scroll in that direction // b) We're not shrink wrapping. If we shrink wrap, we should always size around the content if (scrollable) { if (!canScroll) { // Use getX/getY here to indicate whether we will show visible scrollbars in that direction, we may have // a scrollable and can scroll in that direction without having a visible scrollbar. state.canScroll = { parallel: !widthModel.shrinkWrap && scrollable[names.getX](), perpendicular: !heightModel.shrinkWrap && scrollable[names.getY]() }; } if (!state.actualScroll) { // Store the final calculated state for this cycle in here state.actualScroll = { parallel: false, perpendicular: false }; } } // Consider an hbox w/stretch which means "assign all items the container's height". // The spirit of this request is make all items the same height, but when shrinkWrap // height is also requested, the height of the tallest item determines the height. // This is exactly what the stretchmax option does, so we jiggle the flags here to // act as if stretchmax were requested. if (align.stretch && heightModel.shrinkWrap) { align.stretchmax = true; align.stretch = false; } // This is handy for knowing that we might need to apply height %ages align.nostretch = !(align.stretch || align.stretchmax); // In our example hbox, packing items to the right (end) or center can only work if // there is a container width. So, if we are shrinkWrap, we just turn off the pack // options for the run. if (widthModel.shrinkWrap) { pack.center = pack.end = false; } me.cacheFlexes(ownerContext); // We set the width of the target el equal to the width of the innerCt // when the layout cycle is finished, so we need to clear the width here // to prevent the children from being crushed. // IE needs it because of its scrollIntoView bug: https://sencha.jira.com/browse/EXTJSIV-6520 // Webkit needs it because of its mouse drag bug: https://sencha.jira.com/browse/EXTJSIV-5962 // FF needs it because of a vertical tab bug: https://sencha.jira.com/browse/EXTJSIV-8614 me.targetEl.setWidth(20000); }, /** * This method is called to (re)cache our understanding of flexes. This happens during beginLayoutCycle and may need to * be called again if the flexes are changed during the layout (e.g., like ColumnLayout). * @param {Object} ownerContext * @protected */ cacheFlexes: function (ownerContext) { var me = this, names = ownerContext.boxNames, widthModelName = names.widthModel, heightModelName = names.heightModel, nostretch = ownerContext.boxOptions.align.nostretch, totalFlex = 0, childItems = ownerContext.childItems, i = childItems.length, flexedItems = [], minWidth = 0, smallestHeight = 0, smallestWidth = 0, minWidthName = names.minWidth, minHeightName = names.minHeight, percentageRe = me._percentageRe, percentageWidths = 0, percentageHeights = 0, child, childContext, flex, match, heightModel, widthModel, width, height; while (i--) { childContext = childItems[i]; child = childContext.target; widthModel = childContext[widthModelName]; // check widthModel to see if we are the sizing layout. If so, copy the flex // from the item to the contextItem and add it to totalFlex // if (widthModel.calculated) { childContext.flex = flex = child.flex; if (flex) { totalFlex += flex; flexedItems.push(childContext); minWidth += child[minWidthName] || 0; } else { // a %age width... match = percentageRe.exec(child[names.width]); childContext.percentageParallel = parseFloat(match[1]) / 100; ++percentageWidths; } } // the above means that "childContext.flex" is properly truthy/falsy, which is // often times quite convenient... if (widthModel.configured) { width = child[names.width]; } else { width = child[minWidthName] || 0; } smallestWidth += width; heightModel = childContext[heightModelName]; if (nostretch && heightModel.calculated) { // the only reason we would be calculated height in this case is due to a // height %age... match = percentageRe.exec(child[names.height]); childContext.percentagePerpendicular = parseFloat(match[1]) / 100; ++percentageHeights; } if (heightModel.configured) { height = child[names.height]; } else { height = child[minHeightName] || 0; } if (height > smallestHeight) { smallestHeight = height; } } ownerContext.flexedItems = flexedItems; ownerContext.flexedMinWidth = minWidth; // These dimensions are the smallest possible dimensions (using known sizes) for // the innerCt on each axis ownerContext.smallestWidth = smallestWidth; ownerContext.smallestHeight = smallestHeight; ownerContext.totalFlex = totalFlex; ownerContext.percentageWidths = percentageWidths; ownerContext.percentageHeights = percentageHeights; // The flexed boxes need to be sorted in ascending order of maxSize to work properly // so that unallocated space caused by maxWidth being less than flexed width can be // reallocated to subsequent flexed boxes. Ext.Array.sort(flexedItems, me.flexSortFn); }, calculate: function(ownerContext) { var me = this, names = ownerContext.boxNames, state = ownerContext.state, actualScroll = state.actualScroll, needsScroll = state.needsScroll, canScroll = state.canScroll, plan = state.boxPlan || (state.boxPlan = {}), overflowHandler = me.overflowHandler; plan.targetSize = me.getContainerSize(ownerContext); if (canScroll && !needsScroll) { state.needsScroll = needsScroll = { // Attempt to figure out early on if we need to scroll in the parallel direction. If the perpendicular is // done and we need to scroll, we need to invalidate because it may need recalculation. parallel: canScroll.parallel && plan.targetSize[names.width] < ownerContext.smallestWidth, perpendicular: canScroll.perpendicular && plan.targetSize[names.height] < ownerContext.smallestHeight }; } if (!state.parallelDone) { state.parallelDone = me.calculateParallel(ownerContext, names, plan); } if (!state.perpendicularDone) { state.perpendicularDone = me.calculatePerpendicular(ownerContext, names, plan); } if (state.parallelDone && state.perpendicularDone) { if (canScroll && !state.scrollPass) { if (needsScroll.parallel !== actualScroll.parallel || needsScroll.perpendicular !== actualScroll.perpendicular) { ownerContext.invalidate({ state: { scrollPass: true, canScroll: canScroll, needsScroll: actualScroll } }); me.done = false; return; } } me.publishInnerCtSize(ownerContext); // We always need to run calculateStretchMax, when relevant since we may // have hit a constraint in an earlier calculation. if (me.done && ownerContext.boxOptions.align.stretchmax && !state.stretchMaxDone) { me.calculateStretchMax(ownerContext, names, plan); state.stretchMaxDone = true; } if (overflowHandler) { overflowHandler.calculate(ownerContext); } } else { me.done = false; } }, calculateParallel: function(ownerContext, names, plan) { var me = this, widthShrinkWrap = ownerContext.parallelSizeModel.shrinkWrap, widthName = names.width, childItems = ownerContext.childItems, beforeXName = names.beforeX, afterXName = names.afterX, setWidthName = names.setWidth, childItemsLength = childItems.length, flexedItems = ownerContext.flexedItems, flexedItemsLength = flexedItems.length, pack = ownerContext.boxOptions.pack, padding = me.padding, targetSize = plan.targetSize, containerWidth = targetSize[widthName], state = ownerContext.state, needsScroll = state.needsScroll, canScroll = state.canScroll, totalMargin = 0, left = padding[beforeXName], nonFlexWidth = left + padding[afterXName], scrollbarSize = Ext.getScrollbarSize(), scrollbarWidth = scrollbarSize[names.width], scrollbarHeight = scrollbarSize[names.height], i, childMargins, remainingWidth, remainingFlex, childContext, flex, flexedWidth, contentWidth, childWidth, percentageSpace, availableSpace; // If we are not widthModel.shrinkWrap, we need the width before we can lay out boxes. // This check belongs here so it does not prevent the perpendicular from attempting to // calculate. It may have a dependency on the width, but it may be able to achieve // the correct size without the width. if (!widthShrinkWrap && !targetSize[names.gotWidth]) { return false; } // Gather the total size taken up by non-flexed items: for (i = 0; i < childItemsLength; ++i) { childContext = childItems[i]; childMargins = childContext.marginInfo || childContext.getMarginInfo(); totalMargin += childMargins[widthName]; if (!childContext[names.widthModel].calculated) { childWidth = childContext.getProp(widthName); nonFlexWidth += childWidth; // min/maxWidth safe if (isNaN(nonFlexWidth)) { return false; } } } nonFlexWidth += totalMargin; if (ownerContext.percentageWidths) { percentageSpace = containerWidth - totalMargin; if (isNaN(percentageSpace)) { return false; } for (i = 0; i < childItemsLength; ++i) { childContext = childItems[i]; if (childContext.percentageParallel) { childWidth = Math.ceil(percentageSpace * childContext.percentageParallel); childWidth = childContext.setWidth(childWidth); nonFlexWidth += childWidth; } } } // if we get here, we have all the childWidths for non-flexed items... if (widthShrinkWrap) { availableSpace = 0; plan.tooNarrow = false; } else { availableSpace = containerWidth - nonFlexWidth; if (needsScroll && needsScroll.perpendicular) { availableSpace -= scrollbarHeight; } plan.tooNarrow = availableSpace < ownerContext.flexedMinWidth; if (plan.tooNarrow && canScroll && canScroll.parallel) { state.actualScroll.parallel = true; } } contentWidth = nonFlexWidth; remainingWidth = availableSpace; remainingFlex = ownerContext.totalFlex; // Calculate flexed item sizes: for (i = 0; i < flexedItemsLength; i++) { childContext = flexedItems[i]; flex = childContext.flex; flexedWidth = me.roundFlex((flex / remainingFlex) * remainingWidth); flexedWidth = childContext[setWidthName](flexedWidth); // constrained // due to minWidth constraints, it may be that flexedWidth > remainingWidth contentWidth += flexedWidth; // Remaining space has already had margins subtracted, so just subtract size remainingWidth = Math.max(0, remainingWidth - flexedWidth); // no negatives! remainingFlex -= flex; } if (pack.center) { left += remainingWidth / 2; // If content is too wide to pack to center, do not allow the centering calculation to place it off the left edge. if (left < 0) { left = 0; } } else if (pack.end) { left += remainingWidth; } // Assign parallel position for the boxes: for (i = 0; i < childItemsLength; ++i) { childContext = childItems[i]; childMargins = childContext.marginInfo; // already cached by first loop left += childMargins[beforeXName]; childContext.setProp(names.x, left); // We can read directly from "props.width" because we have already properly // requested it in the calculation of nonFlexedWidths or we calculated it. // We cannot call getProp because that would be inappropriate for flexed items // and we don't need any extra function call overhead: left += childMargins[afterXName] + childContext.props[widthName]; } contentWidth += ownerContext.targetContext.getPaddingInfo()[widthName]; ownerContext.state.contentWidth = contentWidth; // if there is perpendicular overflow, the published parallel content size includes // the size of the perpendicular scrollbar. if (needsScroll && needsScroll.perpendicular) { if (widthShrinkWrap) { contentWidth += scrollbarWidth; } ownerContext[names.hasOverflowY] = true; // tell the component layout to set the parallel size in the dom ownerContext.target.componentLayout[names.setWidthInDom] = true; // IE8 will not create a scrollbar if there is just the *exactly correct* // spare space created for it. We have to force that to happen once all the // styles have been flushed to the DOM (see completeLayout): ownerContext[names.invalidateScrollY] = Ext.isIE8; } ownerContext[names.setContentWidth](contentWidth); return true; }, calculatePerpendicular: function(ownerContext, names, plan) { var me = this, state = ownerContext.state, needsScroll = state.needsScroll, canScroll = state.canScroll, heightShrinkWrap = ownerContext.perpendicularSizeModel.shrinkWrap, targetSize = plan.targetSize, childItems = ownerContext.childItems, childItemsLength = childItems.length, mmax = Math.max, heightName = names.height, setHeightName = names.setHeight, beforeYName = names.beforeY, topPositionName = names.y, padding = me.padding, top = padding[beforeYName], availHeight = targetSize[heightName] - top - padding[names.afterY], align = ownerContext.boxOptions.align, isStretch = align.stretch, // never true if heightShrinkWrap (see beginLayoutCycle) isStretchMax = align.stretchmax, isCenter = align.center, isBottom = align.bottom, constrain = me.constrainAlign, maxHeight = 0, hasPercentageSizes = 0, onBeforeInvalidateChild = me.onBeforeConstrainInvalidateChild, onAfterInvalidateChild = me.onAfterConstrainInvalidateChild, scrollbarHeight = Ext.getScrollbarSize().height, childTop, i, childHeight, childMargins, diff, height, childContext, stretchMaxPartner, stretchMaxChildren, shrinkWrapParallelOverflow, percentagePerpendicular; if (!heightShrinkWrap && !targetSize[names.gotHeight]) { return false; } if (isStretch || ((isCenter || isBottom) && !heightShrinkWrap)) { if (isNaN(availHeight)) { return false; } } // If the intention is to horizontally scroll child components, but the container is too narrow, // then: // if we are shrinkwrapping height: // Set a flag because we are going to expand the height taken by the perpendicular dimension to accommodate the scrollbar // else // We must allow for the parallel scrollbar to intrude into the height if (needsScroll && needsScroll.parallel) { if (heightShrinkWrap) { shrinkWrapParallelOverflow = true; } else { availHeight -= scrollbarHeight; plan.targetSize[heightName] -= scrollbarHeight; } } if (isStretch) { height = availHeight; // never heightShrinkWrap... maxHeight = mmax(height, ownerContext.smallestHeight); } else { for (i = 0; i < childItemsLength; i++) { childContext = childItems[i]; childMargins = (childContext.marginInfo || childContext.getMarginInfo())[heightName]; if (!(percentagePerpendicular = childContext.percentagePerpendicular)) { childHeight = childContext.getProp(heightName); } else { ++hasPercentageSizes; if (heightShrinkWrap) { // height %age items cannot contribute to maxHeight... they are going // to be a %age of that maxHeight! continue; } else { childHeight = percentagePerpendicular * availHeight - childMargins; childHeight = childContext[names.setHeight](childHeight); } } // Summary: // 1) Not shrink wrapping height, so the height is not determined by the children // 2) Constrain is set // 3) The child item is shrink wrapping // 4) It exceeds the max if (!heightShrinkWrap && constrain && childContext[names.heightModel].shrinkWrap && childHeight > availHeight) { childContext.invalidate({ before: onBeforeInvalidateChild, after: onAfterInvalidateChild, layout: me, childHeight: availHeight, names: names }); // By invalidating the height, it could mean the width can change, so we need // to recalculate in the parallel direction. ownerContext.state.parallelDone = false; } // Max perpendicular measurement (used for stretchmax) must take the min perpendicular size of each child into account in case any fall short. if (isNaN(maxHeight = mmax(maxHeight, childHeight + childMargins, childContext.target[names.minHeight] || 0))) { return false; // heightShrinkWrap || isCenter || isStretchMax ?? } } } // If there is going to be a parallel scrollbar maxHeight must include it to the outside world. // ie: a stretchmaxPartner, and the setContentHeight if (shrinkWrapParallelOverflow) { maxHeight += scrollbarHeight; ownerContext[names.hasOverflowX] = true; // tell the component layout to set the perpendicular size in the dom ownerContext.target.componentLayout[names.setHeightInDom] = true; // IE8 will not create a scrollbar if there is just the *exactly correct* // spare space created for it. We have to force that to happen once all // the styles have been flushed to the DOM (see completeLayout): ownerContext[names.invalidateScrollX] = Ext.isIE8; } // If we are associated with another box layout, grab its maxChildHeight // This must happen before we calculate and publish our contentHeight stretchMaxPartner = ownerContext.stretchMaxPartner; if (stretchMaxPartner) { // Publish maxChildHeight as soon as it has been calculated for our partner: ownerContext.setProp('maxChildHeight', maxHeight); stretchMaxChildren = stretchMaxPartner.childItems; // Only wait for maxChildHeight if our partner has visible items: if (stretchMaxChildren && stretchMaxChildren.length) { maxHeight = mmax(maxHeight, stretchMaxPartner.getProp('maxChildHeight')); if (isNaN(maxHeight)) { return false; } } } ownerContext[names.setContentHeight](maxHeight + me.padding[heightName] + ownerContext.targetContext.getPaddingInfo()[heightName]); // We have to publish the contentHeight with the additional scrollbarHeight // to encourage our container to accommodate it, but we must remove the height // of the scrollbar as we go to sizing or centering the children. if (shrinkWrapParallelOverflow) { maxHeight -= scrollbarHeight; } if (maxHeight > targetSize[heightName] && canScroll && canScroll.perpendicular) { state.actualScroll.perpendicular = true; } plan.maxSize = maxHeight; if (isStretchMax) { height = maxHeight; } else if (isCenter || isBottom || hasPercentageSizes) { if (constrain) { height = heightShrinkWrap ? maxHeight : availHeight; } else { height = heightShrinkWrap ? maxHeight : mmax(availHeight, maxHeight); } // When calculating a centered position within the content box of the innerCt, // the width of the borders must be subtracted from the size to yield the // space available to center within. The publishInnerCtSize method explicitly // adds the border widths to the set size of the innerCt. height -= ownerContext.innerCtContext.getBorderInfo()[heightName]; } for (i = 0; i < childItemsLength; i++) { childContext = childItems[i]; childMargins = childContext.marginInfo || childContext.getMarginInfo(); childTop = top + childMargins[beforeYName]; if (isStretch) { childContext[setHeightName](height - childMargins[heightName]); } else { percentagePerpendicular = childContext.percentagePerpendicular; if (heightShrinkWrap && percentagePerpendicular) { childMargins = childContext.marginInfo || childContext.getMarginInfo(); childHeight = percentagePerpendicular * height - childMargins[heightName]; childHeight = childContext.setHeight(childHeight); } if (isCenter) { diff = height - childContext.props[heightName]; if (diff > 0) { childTop = top + Math[me.alignRoundingMethod](diff / 2); } } else if (isBottom) { childTop = mmax(0, height - childTop - childContext.props[heightName]); } } childContext.setProp(topPositionName, childTop); } return true; }, onBeforeConstrainInvalidateChild: function(childContext, options){ // NOTE: No "this" pointer in here... var heightModelName = options.names.heightModel; if (!childContext[heightModelName].constrainedMin) { // if the child hit a min constraint, it needs to be at its configured size, so // we leave the sizeModel alone childContext[heightModelName] = Ext.layout.SizeModel.calculated; } }, onAfterConstrainInvalidateChild: function(childContext, options){ // NOTE: No "this" pointer in here... var names = options.names; // We use 0 here because we know the size exceeds the available size. // This was chosen on purpose, even for align: 'bottom', because it doesn't // make practical sense to place the item at the bottom and then have it overflow // over the top of the container, since it's not possible to scroll to it. As such, // we always put the component at the top to follow normal document flow. childContext.setProp(names.beforeY, 0); if (childContext[names.heightModel].calculated) { childContext[names.setHeight](options.childHeight); } }, calculateStretchMax: function (ownerContext, names, plan) { var me = this, heightName = names.height, widthName = names.width, childItems = ownerContext.childItems, length = childItems.length, height = plan.maxSize, onBeforeStretchMaxInvalidateChild = me.onBeforeStretchMaxInvalidateChild, onAfterStretchMaxInvalidateChild = me.onAfterStretchMaxInvalidateChild, childContext, props, i, childHeight; for (i = 0; i < length; ++i) { childContext = childItems[i]; props = childContext.props; childHeight = height - childContext.getMarginInfo()[heightName]; if (childHeight !== props[heightName] || // if (wrong height ... childContext[names.heightModel].constrained) { // ...or needs invalidation) // When we invalidate a child, since we won't be around to size or position // it, we include an after callback that will be run after the invalidate // that will (re)do that work. The good news here is that we can read the // results of all that from the childContext props. // // We also include a before callback to change the sizeModel to calculated // prior to the layout being invoked. childContext.invalidate({ before: onBeforeStretchMaxInvalidateChild, after: onAfterStretchMaxInvalidateChild, layout: me, // passing this data avoids a 'scope' and its Function.bind childWidth: props[widthName], // subtract margins from the maximum value childHeight: childHeight, childX: props.x, childY: props.y, names: names }); } } }, onBeforeStretchMaxInvalidateChild: function (childContext, options) { // NOTE: No "this" pointer in here... var heightModelName = options.names.heightModel; // Change the childItem to calculated (i.e., "set by ownerCt"). The component layout // of the child can course-correct (like dock layout does for a collapsed panel), // so we must make these changes here before that layout's beginLayoutCycle is // called. if (!childContext[heightModelName].constrainedMax) { // if the child hit a max constraint, it needs to be at its configured size, so // we leave the sizeModel alone... childContext[heightModelName] = Ext.layout.SizeModel.calculated; } }, onAfterStretchMaxInvalidateChild: function (childContext, options) { // NOTE: No "this" pointer in here... var names = options.names, childHeight = options.childHeight, childWidth = options.childWidth; childContext.setProp('x', options.childX); childContext.setProp('y', options.childY); if (childContext[names.heightModel].calculated) { // We need to respect a child that is still not calculated (such as a collapsed // panel)... childContext[names.setHeight](childHeight); } if (childContext[names.widthModel].calculated) { childContext[names.setWidth](childWidth); } }, completeLayout: function(ownerContext) { var me = this, invalidateScrollX = ownerContext.invalidateScrollX, invalidateScrollY = ownerContext.invalidateScrollY, overflowHandler = me.overflowHandler, scrollRestore = ownerContext.scrollRestore, dom, el, overflowX, overflowY, styles; if (overflowHandler) { overflowHandler.completeLayout(ownerContext); } if (invalidateScrollX || invalidateScrollY) { el = me.getTarget(); dom = el.dom; styles = dom.style; if (invalidateScrollX) { // get computed style to see if we are 'auto' overflowX = el.getStyle('overflowX'); if (overflowX === 'auto') { // capture the inline style (if any) so we can restore it later: overflowX = styles.overflowX; styles.overflowX = 'scroll'; // force the scrollbar to appear } else { invalidateScrollX = false; // no work really since not 'auto' } } if (invalidateScrollY) { // get computed style to see if we are 'auto' overflowY = el.getStyle('overflowY'); if (overflowY === 'auto') { // capture the inline style (if any) so we can restore it later: overflowY = styles.overflowY; styles.overflowY = 'scroll'; // force the scrollbar to appear } else { invalidateScrollY = false; // no work really since not 'auto' } } if (invalidateScrollX || invalidateScrollY) { // if (some form of 'auto' in play) // force a reflow... dom.scrollWidth; // jshint ignore:line if (invalidateScrollX) { styles.overflowX = overflowX; // restore inline style } if (invalidateScrollY) { styles.overflowY = overflowY; // restore inline style } } } if (scrollRestore) { ownerContext.ownerScrollable.scrollTo(scrollRestore.x, scrollRestore.y); } }, finishedLayout: function(ownerContext) { var overflowHandler = this.overflowHandler; if (overflowHandler) { overflowHandler.finishedLayout(ownerContext); } this.callParent(arguments); }, getLayoutItems: function() { var items = this.callParent(), n = items.length, lastVisibleItem, hide, i, item, splitAfter, splitBefore, splitter; for (i = 0; i < n; ++i) { if ((item = items[i]).isSplitter) { continue; } splitter = item.splitter; if (item.hidden) { if (splitter) { // hidden items always need to hide their splitter if (!splitter.hidden) { splitter.hidden = true; if (splitter.el) { splitter.el.hide(); } } } continue; } if (splitter) { splitBefore = splitter.collapseTarget === 'next'; } else { // item w/o splitter splitBefore = false; } hide = null; if (lastVisibleItem && splitAfter) { // the last item had a splitter after it so we can keep it and hide // this one if splitBefore if (splitAfter.hidden) { splitAfter.hidden = false; if (splitAfter.el) { splitAfter.el.show(); } } if (splitBefore) { hide = true; } } else if (splitBefore) { hide = !lastVisibleItem; } // else we have no splitter or are !splitBefore, so we defer the fate of this // splitter if (hide !== null && splitter.hidden !== hide) { splitter.hidden = hide; if (splitter.el) { splitter.el.setVisible(!hide); } } splitAfter = !splitBefore && splitter; lastVisibleItem = item; } // If we ended with a visible item and a splitAfter, we need to hide the tail // splitter if (lastVisibleItem && splitAfter && !splitAfter.hidden) { splitAfter.hidden = true; if (splitAfter.el) { splitAfter.el.hide(); } } return items; }, getScrollerEl: function() { return this.innerCt; }, /** * Inserts the splitter for a given region. A reference to the splitter is also stored * on the component as "splitter". * @private */ insertSplitter: function (item, index, hidden, splitterCfg) { var splitter = { xtype: 'splitter', id: item.id + '-splitter', hidden: hidden, splitterFor: item, synthetic: true // not user-defined }, at = index + ((splitterCfg.collapseTarget === 'prev') ? 1 : 0); splitter[this.names.height] = '100%'; if (splitterCfg) { Ext.apply(splitter, splitterCfg); } item.splitter = this.owner.add(at, splitter); }, publishInnerCtSize: function(ownerContext, widthOffset) { widthOffset = widthOffset || 0; var me = this, state = ownerContext.state, names = ownerContext.boxNames, heightName = names.height, widthName = names.width, align = ownerContext.boxOptions.align, padding = me.padding, plan = state.boxPlan, targetSize = plan.targetSize, height = plan.maxSize, needsScroll = state.needsScroll, innerCtContext = ownerContext.innerCtContext, innerCtWidth, innerCtHeight; // The state.canScroll check is on purpose here, all we want to know is whether we have // a scrollable instance, since even if UI scrolling isn't available, we may scroll it // programmatically if (ownerContext.parallelSizeModel.shrinkWrap || (plan.tooNarrow && state.canScroll)) { innerCtWidth = state.contentWidth - ownerContext.targetContext.getPaddingInfo()[widthName]; } else { innerCtWidth = targetSize[widthName]; if (needsScroll && needsScroll.perpendicular) { innerCtWidth -= Ext.getScrollbarSize()[widthName]; } } innerCtWidth -= widthOffset; // Allow the other co-operating objects to know whether the columns overflow the available width. me.owner.tooNarrow = plan.tooNarrow; if (align.stretch) { innerCtHeight = height; } else { innerCtHeight = plan.maxSize + padding[names.beforeY] + padding[names.afterY] + innerCtContext.getBorderInfo()[heightName]; if (!ownerContext.perpendicularSizeModel.shrinkWrap && (align.center || align.bottom)) { innerCtHeight = Math.max(targetSize[heightName], innerCtHeight); } } innerCtContext[names.setWidth](innerCtWidth); innerCtContext[names.setHeight](innerCtHeight); // Fix for an obscure webkit bug (EXTJSIV-5962) caused by the targetEl's 20000px // width. We set a very large width on the targetEl at the beginning of the // layout cycle to prevent any "crushing" effect on the child items, however // in some cases the very large width makes it possible to scroll the innerCt // by dragging on certain child elements. To prevent this from happening we ensure // that the targetEl's width is the same as the innerCt. // IE needs it because of its scrollIntoView bug: https://sencha.jira.com/browse/EXTJSIV-6520 // Webkit needs it because of its mouse drag bug: https://sencha.jira.com/browse/EXTJSIV-5962 // FF needs it because of a vertical tab bug: https://sencha.jira.com/browse/EXTJSIV-8614 ownerContext.targetElContext.setWidth(ownerContext.innerCtContext.props.width - (me.vertical ? 0 : (widthOffset || 0))); // If unable to publish both dimensions, this layout needs to run again if (isNaN(innerCtWidth + innerCtHeight)) { me.done = false; } }, onAdd: function (item, index) { var me = this, // Buttons will gain a split param split = me.enableSplitters && item.split && !item.isButton; me.callParent(arguments); if (split) { if (split === true) { split = { collapseTarget: 'next' }; } else if (Ext.isString(split)) { split = { collapseTarget: split === 'before' ? 'next' : 'prev' }; } else { split = Ext.apply({ collapseTarget: split.side === 'before' ? 'next' : 'prev' }, split); } me.insertSplitter(item, index, !!item.hidden, split); } }, onRemove: function(comp, isDestroying){ var me = this, names = me.names, owner = me.owner, splitter = comp.splitter, overflowHandler = me.overflowHandler, el; me.callParent(arguments); if (splitter && owner.contains(splitter)) { owner.doRemove(splitter, true); comp.splitter = null; } if (overflowHandler) { overflowHandler.onRemove(comp); } if (comp.layoutMarginCap === me.id) { delete comp.layoutMarginCap; } if (!owner.destroying && !isDestroying && comp.rendered) { // Clear top/left styles el = comp.getEl(); if (el) { el.setStyle(names.beforeY, ''); el.setStyle(names.beforeX, ''); // Box layout imposes margin:0 on its child items and the layout provides margins // using its absolute positioning strategy. This has to be reversed on remove. el.setStyle('margin', ''); } } }, applyOverflowHandler: function(overflowHandler, oldOverflowHandler) { var type; if (typeof overflowHandler === 'string') { overflowHandler = { type: overflowHandler }; } type = overflowHandler.type; if (oldOverflowHandler && oldOverflowHandler.type === overflowHandler.type) { delete overflowHandler.type; oldOverflowHandler.setConfig(overflowHandler); return oldOverflowHandler; } overflowHandler.layout = this; return Ext.Factory.boxOverflow(overflowHandler); }, // Overridden method from Ext.layout.container.Container. // Used in the beforeLayout method to render all items into. getRenderTarget: function() { return this.targetEl; }, // Overridden method from Ext.layout.container.Container. // Used by Container classes to insert special DOM elements which must exist in addition to the child components getElementTarget: function() { return this.innerCt; }, //<debug> calculateChildBox: Ext.deprecated(), calculateChildBoxes: Ext.deprecated(), updateChildBoxes: Ext.deprecated(), //</debug> destroy: function() { var me = this; Ext.destroy(me.innerCt, me.overflowHandler); me.flexSortFn = me.innerCt = null; me.callParent(); }, getRenderData: function() { var data = this.callParent(); data.targetElCls = this.targetElCls; return data; }, updateVertical: function (vertical) { var me = this, overflowHandler = me.overflowHandler, owner = me.owner, props = me._props; Ext.apply(me, vertical ? props.vbox : props.hbox); if (overflowHandler && owner && owner.rendered) { overflowHandler.setVertical(vertical); } }, _props: { // HBOX - this key is produced by setVertical 'hbox': { direction: 'horizontal', oppositeDirection: 'vertical', horizontal: true, vertical: false, names: { // parallel beforeX: 'left', beforeScrollX: 'left', leftCap: 'Left', afterX: 'right', width: 'width', contentWidth: 'contentWidth', minWidth: 'minWidth', maxWidth: 'maxWidth', widthCap: 'Width', widthModel: 'widthModel', widthIndex: 0, x: 'x', getX: 'getX', setX: 'setX', scrollLeft: 'scrollLeft', overflowX: 'overflowX', hasOverflowX: 'hasOverflowX', invalidateScrollX: 'invalidateScrollX', parallelMargins: 'lr', // perpendicular center: 'middle', beforeY: 'top', afterY: 'bottom', height: 'height', contentHeight: 'contentHeight', minHeight: 'minHeight', maxHeight: 'maxHeight', heightCap: 'Height', heightModel: 'heightModel', heightIndex: 1, y: 'y', getY: 'getY', setY: 'setY', overflowY: 'overflowY', hasOverflowY: 'hasOverflowY', invalidateScrollY: 'invalidateScrollY', perpendicularMargins: 'tb', // Methods getWidth: 'getWidth', getHeight: 'getHeight', setWidth: 'setWidth', setHeight: 'setHeight', gotWidth: 'gotWidth', gotHeight: 'gotHeight', setContentWidth: 'setContentWidth', setContentHeight: 'setContentHeight', setWidthInDom: 'setWidthInDom', setHeightInDom: 'setHeightInDom', getScrollLeft: 'getScrollLeft', setScrollLeft: 'setScrollLeft', scrollTo: 'scrollTo' }, sizePolicy: { flex: { '': { readsWidth : 0, readsHeight: 1, setsWidth : 1, setsHeight : 0 }, stretch: { readsWidth : 0, readsHeight: 0, setsWidth : 1, setsHeight : 1 }, stretchmax: { readsWidth : 0, readsHeight: 1, setsWidth : 1, setsHeight : 1 } }, '': { readsWidth : 1, readsHeight: 1, setsWidth : 0, setsHeight : 0 }, stretch: { readsWidth : 1, readsHeight: 0, setsWidth : 0, setsHeight : 1 }, stretchmax: { readsWidth : 1, readsHeight: 1, setsWidth : 0, setsHeight : 1 } } }, // VBOX 'vbox': { direction: 'vertical', oppositeDirection: 'horizontal', horizontal: false, vertical: true, names: { // parallel beforeX: 'top', beforeScrollX: 'top', leftCap: 'Top', afterX: 'bottom', width: 'height', contentWidth: 'contentHeight', minWidth: 'minHeight', maxWidth: 'maxHeight', widthCap: 'Height', widthModel: 'heightModel', widthIndex: 1, x: 'y', getX: 'getY', setX: 'setY', scrollLeft: 'scrollTop', overflowX: 'overflowY', hasOverflowX: 'hasOverflowY', invalidateScrollX: 'invalidateScrollY', parallelMargins: 'tb', // perpendicular center: 'center', beforeY: 'left', afterY: 'right', height: 'width', contentHeight: 'contentWidth', minHeight: 'minWidth', maxHeight: 'maxWidth', heightCap: 'Width', heightModel: 'widthModel', heightIndex: 0, y: 'x', getY: 'getX', setY: 'setX', overflowY: 'overflowX', hasOverflowY: 'hasOverflowX', invalidateScrollY: 'invalidateScrollX', perpendicularMargins: 'lr', // Methods getWidth: 'getHeight', getHeight: 'getWidth', setWidth: 'setHeight', setHeight: 'setWidth', gotWidth: 'gotHeight', gotHeight: 'gotWidth', setContentWidth: 'setContentHeight', setContentHeight: 'setContentWidth', setWidthInDom: 'setHeightInDom', setHeightInDom: 'setWidthInDom', getScrollLeft: 'getScrollTop', setScrollLeft: 'setScrollTop', scrollTo: 'scrollTo' }, sizePolicy: { flex: { '': { readsWidth : 1, readsHeight: 0, setsWidth : 0, setsHeight : 1 }, stretch: { readsWidth : 0, readsHeight: 0, setsWidth : 1, setsHeight : 1 }, stretchmax: { readsWidth : 1, readsHeight: 0, setsWidth : 1, setsHeight : 1 } }, '': { readsWidth : 1, readsHeight: 1, setsWidth : 0, setsHeight : 0 }, stretch: { readsWidth : 0, readsHeight: 1, setsWidth : 1, setsHeight : 0 }, stretchmax: { readsWidth : 1, readsHeight: 1, setsWidth : 1, setsHeight : 0 } } } } });
ajax/libs/video.js/4.4.2/video.dev.js
calebmer/cdnjs
/** * @fileoverview Main function src. */ // HTML5 Shiv. Must be in <head> to support older browsers. document.createElement('video'); document.createElement('audio'); document.createElement('track'); /** * Doubles as the main function for users to create a player instance and also * the main library object. * * **ALIASES** videojs, _V_ (deprecated) * * The `vjs` function can be used to initialize or retrieve a player. * * var myPlayer = vjs('my_video_id'); * * @param {String|Element} id Video element or video element ID * @param {Object=} options Optional options object for config/settings * @param {Function=} ready Optional ready callback * @return {vjs.Player} A player instance * @namespace */ var vjs = function(id, options, ready){ var tag; // Element of ID // Allow for element or ID to be passed in // String ID if (typeof id === 'string') { // Adjust for jQuery ID syntax if (id.indexOf('#') === 0) { id = id.slice(1); } // If a player instance has already been created for this ID return it. if (vjs.players[id]) { return vjs.players[id]; // Otherwise get element for ID } else { tag = vjs.el(id); } // ID is a media element } else { tag = id; } // Check for a useable element if (!tag || !tag.nodeName) { // re: nodeName, could be a box div also throw new TypeError('The element or ID supplied is not valid. (videojs)'); // Returns } // Element may have a player attr referring to an already created player instance. // If not, set up a new player and return the instance. return tag['player'] || new vjs.Player(tag, options, ready); }; // Extended name, also available externally, window.videojs var videojs = vjs; window.videojs = window.vjs = vjs; // CDN Version. Used to target right flash swf. vjs.CDN_VERSION = '4.4'; vjs.ACCESS_PROTOCOL = ('https:' == document.location.protocol ? 'https://' : 'http://'); /** * Global Player instance options, surfaced from vjs.Player.prototype.options_ * vjs.options = vjs.Player.prototype.options_ * All options should use string keys so they avoid * renaming by closure compiler * @type {Object} */ vjs.options = { // Default order of fallback technology 'techOrder': ['html5','flash'], // techOrder: ['flash','html5'], 'html5': {}, 'flash': {}, // Default of web browser is 300x150. Should rely on source width/height. 'width': 300, 'height': 150, // defaultVolume: 0.85, 'defaultVolume': 0.00, // The freakin seaguls are driving me crazy! // Included control sets 'children': { 'mediaLoader': {}, 'posterImage': {}, 'textTrackDisplay': {}, 'loadingSpinner': {}, 'bigPlayButton': {}, 'controlBar': {} }, // Default message to show when a video cannot be played. 'notSupportedMessage': 'Sorry, no compatible source and playback ' + 'technology were found for this video. Try using another browser ' + 'like <a href="http://bit.ly/ccMUEC">Chrome</a> or download the ' + 'latest <a href="http://adobe.ly/mwfN1">Adobe Flash Player</a>.' }; // Set CDN Version of swf // The added (+) blocks the replace from changing this 4.4 string if (vjs.CDN_VERSION !== 'GENERATED'+'_CDN_VSN') { videojs.options['flash']['swf'] = vjs.ACCESS_PROTOCOL + 'vjs.zencdn.net/'+vjs.CDN_VERSION+'/video-js.swf'; } /** * Global player list * @type {Object} */ vjs.players = {}; /*! * Custom Universal Module Definition (UMD) * * Video.js will never be a non-browser lib so we can simplify UMD a bunch and * still support requirejs and browserify. This also needs to be closure * compiler compatible, so string keys are used. */ if (typeof define === 'function' && define['amd']) { define([], function(){ return videojs; }); // checking that module is an object too because of umdjs/umd#35 } else if (typeof exports === 'object' && typeof module === 'object') { module['exports'] = videojs; } /** * Core Object/Class for objects that use inheritance + contstructors * * To create a class that can be subclassed itself, extend the CoreObject class. * * var Animal = CoreObject.extend(); * var Horse = Animal.extend(); * * The constructor can be defined through the init property of an object argument. * * var Animal = CoreObject.extend({ * init: function(name, sound){ * this.name = name; * } * }); * * Other methods and properties can be added the same way, or directly to the * prototype. * * var Animal = CoreObject.extend({ * init: function(name){ * this.name = name; * }, * getName: function(){ * return this.name; * }, * sound: '...' * }); * * Animal.prototype.makeSound = function(){ * alert(this.sound); * }; * * To create an instance of a class, use the create method. * * var fluffy = Animal.create('Fluffy'); * fluffy.getName(); // -> Fluffy * * Methods and properties can be overridden in subclasses. * * var Horse = Animal.extend({ * sound: 'Neighhhhh!' * }); * * var horsey = Horse.create('Horsey'); * horsey.getName(); // -> Horsey * horsey.makeSound(); // -> Alert: Neighhhhh! * * @class * @constructor */ vjs.CoreObject = vjs['CoreObject'] = function(){}; // Manually exporting vjs['CoreObject'] here for Closure Compiler // because of the use of the extend/create class methods // If we didn't do this, those functions would get flattend to something like // `a = ...` and `this.prototype` would refer to the global object instead of // CoreObject /** * Create a new object that inherits from this Object * * var Animal = CoreObject.extend(); * var Horse = Animal.extend(); * * @param {Object} props Functions and properties to be applied to the * new object's prototype * @return {vjs.CoreObject} An object that inherits from CoreObject * @this {*} */ vjs.CoreObject.extend = function(props){ var init, subObj; props = props || {}; // Set up the constructor using the supplied init method // or using the init of the parent object // Make sure to check the unobfuscated version for external libs init = props['init'] || props.init || this.prototype['init'] || this.prototype.init || function(){}; // In Resig's simple class inheritance (previously used) the constructor // is a function that calls `this.init.apply(arguments)` // However that would prevent us from using `ParentObject.call(this);` // in a Child constuctor because the `this` in `this.init` // would still refer to the Child and cause an inifinite loop. // We would instead have to do // `ParentObject.prototype.init.apply(this, argumnents);` // Bleh. We're not creating a _super() function, so it's good to keep // the parent constructor reference simple. subObj = function(){ init.apply(this, arguments); }; // Inherit from this object's prototype subObj.prototype = vjs.obj.create(this.prototype); // Reset the constructor property for subObj otherwise // instances of subObj would have the constructor of the parent Object subObj.prototype.constructor = subObj; // Make the class extendable subObj.extend = vjs.CoreObject.extend; // Make a function for creating instances subObj.create = vjs.CoreObject.create; // Extend subObj's prototype with functions and other properties from props for (var name in props) { if (props.hasOwnProperty(name)) { subObj.prototype[name] = props[name]; } } return subObj; }; /** * Create a new instace of this Object class * * var myAnimal = Animal.create(); * * @return {vjs.CoreObject} An instance of a CoreObject subclass * @this {*} */ vjs.CoreObject.create = function(){ // Create a new object that inherits from this object's prototype var inst = vjs.obj.create(this.prototype); // Apply this constructor function to the new object this.apply(inst, arguments); // Return the new object return inst; }; /** * @fileoverview Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/) * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible) * This should work very similarly to jQuery's events, however it's based off the book version which isn't as * robust as jquery's, so there's probably some differences. */ /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * @param {Element|Object} elem Element or object to bind listeners to * @param {String} type Type of event to bind to. * @param {Function} fn Event listener. * @private */ vjs.on = function(elem, type, fn){ var data = vjs.getData(elem); // We need a place to store all our handler data if (!data.handlers) data.handlers = {}; if (!data.handlers[type]) data.handlers[type] = []; if (!fn.guid) fn.guid = vjs.guid++; data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event){ if (data.disabled) return; event = vjs.fixEvent(event); var handlers = data.handlers[event.type]; if (handlers) { // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off. var handlersCopy = handlers.slice(0); for (var m = 0, n = handlersCopy.length; m < n; m++) { if (event.isImmediatePropagationStopped()) { break; } else { handlersCopy[m].call(elem, event); } } } }; } if (data.handlers[type].length == 1) { if (document.addEventListener) { elem.addEventListener(type, data.dispatcher, false); } else if (document.attachEvent) { elem.attachEvent('on' + type, data.dispatcher); } } }; /** * Removes event listeners from an element * @param {Element|Object} elem Object to remove listeners from * @param {String=} type Type of listener to remove. Don't include to remove all events from element. * @param {Function} fn Specific listener to remove. Don't incldue to remove listeners for an event type. * @private */ vjs.off = function(elem, type, fn) { // Don't want to add a cache object through getData if not needed if (!vjs.hasData(elem)) return; var data = vjs.getData(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } // Utility function var removeType = function(t){ data.handlers[t] = []; vjs.cleanUpEvents(elem,t); }; // Are we removing all bound events? if (!type) { for (var t in data.handlers) removeType(t); return; } var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind if (!handlers) return; // If no listener was provided, remove all listeners for type if (!fn) { removeType(type); return; } // We're only removing a single handler if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } vjs.cleanUpEvents(elem, type); }; /** * Clean up the listener cache and dispatchers * @param {Element|Object} elem Element to clean up * @param {String} type Type of event to clean up * @private */ vjs.cleanUpEvents = function(elem, type) { var data = vjs.getData(elem); // Remove the events of a particular type if there are none left if (data.handlers[type].length === 0) { delete data.handlers[type]; // data.handlers[type] = null; // Setting to null was causing an error with data.handlers // Remove the meta-handler from the element if (document.removeEventListener) { elem.removeEventListener(type, data.dispatcher, false); } else if (document.detachEvent) { elem.detachEvent('on' + type, data.dispatcher); } } // Remove the events object if there are no types left if (vjs.isEmpty(data.handlers)) { delete data.handlers; delete data.dispatcher; delete data.disabled; // data.handlers = null; // data.dispatcher = null; // data.disabled = null; } // Finally remove the expando if there is no data left if (vjs.isEmpty(data)) { vjs.removeData(elem); } }; /** * Fix a native event to have standard property values * @param {Object} event Event object to fix * @return {Object} * @private */ vjs.fixEvent = function(event) { function returnTrue() { return true; } function returnFalse() { return false; } // Test if fixing up is needed // Used to check if !event.stopPropagation instead of isPropagationStopped // But native events return true for stopPropagation, but don't have // other expected methods like isPropagationStopped. Seems to be a problem // with the Javascript Ninja code. So we're just overriding all events now. if (!event || !event.isPropagationStopped) { var old = event || window.event; event = {}; // Clone the old object so that we can modify the values event = {}; // IE8 Doesn't like when you mess with native event properties // Firefox returns false for event.hasOwnProperty('type') and other props // which makes copying more difficult. // TODO: Probably best to create a whitelist of event props for (var key in old) { // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation if (key !== 'layerX' && key !== 'layerY' && key !== 'keyboardEvent.keyLocation') { // Chrome 32+ warns if you try to copy deprecated returnValue, but // we still want to if preventDefault isn't supported (IE8). if (!(key == 'returnValue' && old.preventDefault)) { event[key] = old[key]; } } } // The event occurred on this element if (!event.target) { event.target = event.srcElement || document; } // Handle which other element the event is related to event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; // Stop the default browser action event.preventDefault = function () { if (old.preventDefault) { old.preventDefault(); } event.returnValue = false; event.isDefaultPrevented = returnTrue; }; event.isDefaultPrevented = returnFalse; // Stop the event from bubbling event.stopPropagation = function () { if (old.stopPropagation) { old.stopPropagation(); } event.cancelBubble = true; event.isPropagationStopped = returnTrue; }; event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers event.stopImmediatePropagation = function () { if (old.stopImmediatePropagation) { old.stopImmediatePropagation(); } event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; event.isImmediatePropagationStopped = returnFalse; // Handle mouse position if (event.clientX != null) { var doc = document.documentElement, body = document.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Handle key presses event.which = event.charCode || event.keyCode; // Fix button for mouse clicks: // 0 == left; 1 == middle; 2 == right if (event.button != null) { event.button = (event.button & 1 ? 0 : (event.button & 4 ? 1 : (event.button & 2 ? 2 : 0))); } } // Returns fixed-up instance return event; }; /** * Trigger an event for an element * @param {Element|Object} elem Element to trigger an event on * @param {String} event Type of event to trigger * @private */ vjs.trigger = function(elem, event) { // Fetches element data and a reference to the parent (for bubbling). // Don't want to add a data object to cache for every parent, // so checking hasData first. var elemData = (vjs.hasData(elem)) ? vjs.getData(elem) : {}; var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event, // handler; // If an event name was passed as a string, creates an event out of it if (typeof event === 'string') { event = { type:event, target:elem }; } // Normalizes the event properties. event = vjs.fixEvent(event); // If the passed element has a dispatcher, executes the established handlers. if (elemData.dispatcher) { elemData.dispatcher.call(elem, event); } // Unless explicitly stopped or the event does not bubble (e.g. media events) // recursively calls this function to bubble the event up the DOM. if (parent && !event.isPropagationStopped() && event.bubbles !== false) { vjs.trigger(parent, event); // If at the top of the DOM, triggers the default action unless disabled. } else if (!parent && !event.isDefaultPrevented()) { var targetData = vjs.getData(event.target); // Checks if the target has a default action for this event. if (event.target[event.type]) { // Temporarily disables event dispatching on the target as we have already executed the handler. targetData.disabled = true; // Executes the default action. if (typeof event.target[event.type] === 'function') { event.target[event.type](); } // Re-enables event dispatching. targetData.disabled = false; } } // Inform the triggerer if the default was prevented by returning false return !event.isDefaultPrevented(); /* Original version of js ninja events wasn't complete. * We've since updated to the latest version, but keeping this around * for now just in case. */ // // Added in attion to book. Book code was broke. // event = typeof event === 'object' ? // event[vjs.expando] ? // event : // new vjs.Event(type, event) : // new vjs.Event(type); // event.type = type; // if (handler) { // handler.call(elem, event); // } // // Clean up the event in case it is being reused // event.result = undefined; // event.target = elem; }; /** * Trigger a listener only once for an event * @param {Element|Object} elem Element or object to * @param {String} type * @param {Function} fn * @private */ vjs.one = function(elem, type, fn) { var func = function(){ vjs.off(elem, type, func); fn.apply(this, arguments); }; func.guid = fn.guid = fn.guid || vjs.guid++; vjs.on(elem, type, func); }; var hasOwnProp = Object.prototype.hasOwnProperty; /** * Creates an element and applies properties. * @param {String=} tagName Name of tag to be created. * @param {Object=} properties Element properties to be applied. * @return {Element} * @private */ vjs.createEl = function(tagName, properties){ var el, propName; el = document.createElement(tagName || 'div'); for (propName in properties){ if (hasOwnProp.call(properties, propName)) { //el[propName] = properties[propName]; // Not remembering why we were checking for dash // but using setAttribute means you have to use getAttribute // The check for dash checks for the aria-* attributes, like aria-label, aria-valuemin. // The additional check for "role" is because the default method for adding attributes does not // add the attribute "role". My guess is because it's not a valid attribute in some namespaces, although // browsers handle the attribute just fine. The W3C allows for aria-* attributes to be used in pre-HTML5 docs. // http://www.w3.org/TR/wai-aria-primer/#ariahtml. Using setAttribute gets around this problem. if (propName.indexOf('aria-') !== -1 || propName=='role') { el.setAttribute(propName, properties[propName]); } else { el[propName] = properties[propName]; } } } return el; }; /** * Uppercase the first letter of a string * @param {String} string String to be uppercased * @return {String} * @private */ vjs.capitalize = function(string){ return string.charAt(0).toUpperCase() + string.slice(1); }; /** * Object functions container * @type {Object} * @private */ vjs.obj = {}; /** * Object.create shim for prototypal inheritance * * https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create * * @function * @param {Object} obj Object to use as prototype * @private */ vjs.obj.create = Object.create || function(obj){ //Create a new function called 'F' which is just an empty object. function F() {} //the prototype of the 'F' function should point to the //parameter of the anonymous function. F.prototype = obj; //create a new constructor function based off of the 'F' function. return new F(); }; /** * Loop through each property in an object and call a function * whose arguments are (key,value) * @param {Object} obj Object of properties * @param {Function} fn Function to be called on each property. * @this {*} * @private */ vjs.obj.each = function(obj, fn, context){ for (var key in obj) { if (hasOwnProp.call(obj, key)) { fn.call(context || this, key, obj[key]); } } }; /** * Merge two objects together and return the original. * @param {Object} obj1 * @param {Object} obj2 * @return {Object} * @private */ vjs.obj.merge = function(obj1, obj2){ if (!obj2) { return obj1; } for (var key in obj2){ if (hasOwnProp.call(obj2, key)) { obj1[key] = obj2[key]; } } return obj1; }; /** * Merge two objects, and merge any properties that are objects * instead of just overwriting one. Uses to merge options hashes * where deeper default settings are important. * @param {Object} obj1 Object to override * @param {Object} obj2 Overriding object * @return {Object} New object. Obj1 and Obj2 will be untouched. * @private */ vjs.obj.deepMerge = function(obj1, obj2){ var key, val1, val2; // make a copy of obj1 so we're not ovewriting original values. // like prototype.options_ and all sub options objects obj1 = vjs.obj.copy(obj1); for (key in obj2){ if (hasOwnProp.call(obj2, key)) { val1 = obj1[key]; val2 = obj2[key]; // Check if both properties are pure objects and do a deep merge if so if (vjs.obj.isPlain(val1) && vjs.obj.isPlain(val2)) { obj1[key] = vjs.obj.deepMerge(val1, val2); } else { obj1[key] = obj2[key]; } } } return obj1; }; /** * Make a copy of the supplied object * @param {Object} obj Object to copy * @return {Object} Copy of object * @private */ vjs.obj.copy = function(obj){ return vjs.obj.merge({}, obj); }; /** * Check if an object is plain, and not a dom node or any object sub-instance * @param {Object} obj Object to check * @return {Boolean} True if plain, false otherwise * @private */ vjs.obj.isPlain = function(obj){ return !!obj && typeof obj === 'object' && obj.toString() === '[object Object]' && obj.constructor === Object; }; /** * Bind (a.k.a proxy or Context). A simple method for changing the context of a function It also stores a unique id on the function so it can be easily removed from events * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} * @private */ vjs.bind = function(context, fn, uid) { // Make sure the function has a unique ID if (!fn.guid) { fn.guid = vjs.guid++; } // Create the new function that changes the context var ret = function() { return fn.apply(context, arguments); }; // Allow for the ability to individualize this function // Needed in the case where multiple objects might share the same prototype // IF both items add an event listener with the same function, then you try to remove just one // it will remove both because they both have the same guid. // when using this, you need to use the bind method when you remove the listener as well. // currently used in text tracks ret.guid = (uid) ? uid + '_' + fn.guid : fn.guid; return ret; }; /** * Element Data Store. Allows for binding data to an element without putting it directly on the element. * Ex. Event listneres are stored here. * (also from jsninja.com, slightly modified and updated for closure compiler) * @type {Object} * @private */ vjs.cache = {}; /** * Unique ID for an element or function * @type {Number} * @private */ vjs.guid = 1; /** * Unique attribute name to store an element's guid in * @type {String} * @constant * @private */ vjs.expando = 'vdata' + (new Date()).getTime(); /** * Returns the cache object where data for an element is stored * @param {Element} el Element to store data for. * @return {Object} * @private */ vjs.getData = function(el){ var id = el[vjs.expando]; if (!id) { id = el[vjs.expando] = vjs.guid++; vjs.cache[id] = {}; } return vjs.cache[id]; }; /** * Returns the cache object where data for an element is stored * @param {Element} el Element to store data for. * @return {Object} * @private */ vjs.hasData = function(el){ var id = el[vjs.expando]; return !(!id || vjs.isEmpty(vjs.cache[id])); }; /** * Delete data for the element from the cache and the guid attr from getElementById * @param {Element} el Remove data for an element * @private */ vjs.removeData = function(el){ var id = el[vjs.expando]; if (!id) { return; } // Remove all stored data // Changed to = null // http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/ // vjs.cache[id] = null; delete vjs.cache[id]; // Remove the expando property from the DOM node try { delete el[vjs.expando]; } catch(e) { if (el.removeAttribute) { el.removeAttribute(vjs.expando); } else { // IE doesn't appear to support removeAttribute on the document element el[vjs.expando] = null; } } }; /** * Check if an object is empty * @param {Object} obj The object to check for emptiness * @return {Boolean} * @private */ vjs.isEmpty = function(obj) { for (var prop in obj) { // Inlude null properties as empty. if (obj[prop] !== null) { return false; } } return true; }; /** * Add a CSS class name to an element * @param {Element} element Element to add class name to * @param {String} classToAdd Classname to add * @private */ vjs.addClass = function(element, classToAdd){ if ((' '+element.className+' ').indexOf(' '+classToAdd+' ') == -1) { element.className = element.className === '' ? classToAdd : element.className + ' ' + classToAdd; } }; /** * Remove a CSS class name from an element * @param {Element} element Element to remove from class name * @param {String} classToAdd Classname to remove * @private */ vjs.removeClass = function(element, classToRemove){ var classNames, i; if (element.className.indexOf(classToRemove) == -1) { return; } classNames = element.className.split(' '); // no arr.indexOf in ie8, and we don't want to add a big shim for (i = classNames.length - 1; i >= 0; i--) { if (classNames[i] === classToRemove) { classNames.splice(i,1); } } element.className = classNames.join(' '); }; /** * Element for testing browser HTML5 video capabilities * @type {Element} * @constant * @private */ vjs.TEST_VID = vjs.createEl('video'); /** * Useragent for browser testing. * @type {String} * @constant * @private */ vjs.USER_AGENT = navigator.userAgent; /** * Device is an iPhone * @type {Boolean} * @constant * @private */ vjs.IS_IPHONE = (/iPhone/i).test(vjs.USER_AGENT); vjs.IS_IPAD = (/iPad/i).test(vjs.USER_AGENT); vjs.IS_IPOD = (/iPod/i).test(vjs.USER_AGENT); vjs.IS_IOS = vjs.IS_IPHONE || vjs.IS_IPAD || vjs.IS_IPOD; vjs.IOS_VERSION = (function(){ var match = vjs.USER_AGENT.match(/OS (\d+)_/i); if (match && match[1]) { return match[1]; } })(); vjs.IS_ANDROID = (/Android/i).test(vjs.USER_AGENT); vjs.ANDROID_VERSION = (function() { // This matches Android Major.Minor.Patch versions // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned var match = vjs.USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i), major, minor; if (!match) { return null; } major = match[1] && parseFloat(match[1]); minor = match[2] && parseFloat(match[2]); if (major && minor) { return parseFloat(match[1] + '.' + match[2]); } else if (major) { return major; } else { return null; } })(); // Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser vjs.IS_OLD_ANDROID = vjs.IS_ANDROID && (/webkit/i).test(vjs.USER_AGENT) && vjs.ANDROID_VERSION < 2.3; vjs.IS_FIREFOX = (/Firefox/i).test(vjs.USER_AGENT); vjs.IS_CHROME = (/Chrome/i).test(vjs.USER_AGENT); vjs.TOUCH_ENABLED = !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch); /** * Get an element's attribute values, as defined on the HTML tag * Attributs are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * @param {Element} tag Element from which to get tag attributes * @return {Object} * @private */ vjs.getAttributeValues = function(tag){ var obj, knownBooleans, attrs, attrName, attrVal; obj = {}; // known boolean attributes // we can check for matching boolean properties, but older browsers // won't know about HTML5 boolean attributes that we still read from knownBooleans = ','+'autoplay,controls,loop,muted,default'+','; if (tag && tag.attributes && tag.attributes.length > 0) { attrs = tag.attributes; for (var i = attrs.length - 1; i >= 0; i--) { attrName = attrs[i].name; attrVal = attrs[i].value; // check for known booleans // the matching element property will return a value for typeof if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(','+attrName+',') !== -1) { // the value of an included boolean attribute is typically an empty // string ('') which would equal false if we just check for a false value. // we also don't want support bad code like autoplay='false' attrVal = (attrVal !== null) ? true : false; } obj[attrName] = attrVal; } } return obj; }; /** * Get the computed style value for an element * From http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/ * @param {Element} el Element to get style value for * @param {String} strCssRule Style name * @return {String} Style value * @private */ vjs.getComputedDimension = function(el, strCssRule){ var strValue = ''; if(document.defaultView && document.defaultView.getComputedStyle){ strValue = document.defaultView.getComputedStyle(el, '').getPropertyValue(strCssRule); } else if(el.currentStyle){ // IE8 Width/Height support strValue = el['client'+strCssRule.substr(0,1).toUpperCase() + strCssRule.substr(1)] + 'px'; } return strValue; }; /** * Insert an element as the first child node of another * @param {Element} child Element to insert * @param {[type]} parent Element to insert child into * @private */ vjs.insertFirst = function(child, parent){ if (parent.firstChild) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } }; /** * Object to hold browser support information * @type {Object} * @private */ vjs.support = {}; /** * Shorthand for document.getElementById() * Also allows for CSS (jQuery) ID syntax. But nothing other than IDs. * @param {String} id Element ID * @return {Element} Element with supplied ID * @private */ vjs.el = function(id){ if (id.indexOf('#') === 0) { id = id.slice(1); } return document.getElementById(id); }; /** * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * @param {Number} seconds Number of seconds to be turned into a string * @param {Number} guide Number (in seconds) to model the string after * @return {String} Time formatted as H:MM:SS or M:SS * @private */ vjs.formatTime = function(seconds, guide) { // Default to using seconds as guide guide = guide || seconds; var s = Math.floor(seconds % 60), m = Math.floor(seconds / 60 % 60), h = Math.floor(seconds / 3600), gm = Math.floor(guide / 60 % 60), gh = Math.floor(guide / 3600); // handle invalid times if (isNaN(seconds) || seconds === Infinity) { // '-' is false for all relational operators (e.g. <, >=) so this setting // will add the minimum number of fields specified by the guide h = m = s = '-'; } // Check if we need to show hours h = (h > 0 || gh > 0) ? h + ':' : ''; // If hours are showing, we may need to add a leading zero. // Always show at least one digit of minutes. m = (((h || gm >= 10) && m < 10) ? '0' + m : m) + ':'; // Check if leading zero is need for seconds s = (s < 10) ? '0' + s : s; return h + m + s; }; // Attempt to block the ability to select text while dragging controls vjs.blockTextSelection = function(){ document.body.focus(); document.onselectstart = function () { return false; }; }; // Turn off text selection blocking vjs.unblockTextSelection = function(){ document.onselectstart = function () { return true; }; }; /** * Trim whitespace from the ends of a string. * @param {String} string String to trim * @return {String} Trimmed string * @private */ vjs.trim = function(str){ return (str+'').replace(/^\s+|\s+$/g, ''); }; /** * Should round off a number to a decimal place * @param {Number} num Number to round * @param {Number} dec Number of decimal places to round to * @return {Number} Rounded number * @private */ vjs.round = function(num, dec) { if (!dec) { dec = 0; } return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); }; /** * Should create a fake TimeRange object * Mimics an HTML5 time range instance, which has functions that * return the start and end times for a range * TimeRanges are returned by the buffered() method * @param {Number} start Start time in seconds * @param {Number} end End time in seconds * @return {Object} Fake TimeRange object * @private */ vjs.createTimeRange = function(start, end){ return { length: 1, start: function() { return start; }, end: function() { return end; } }; }; /** * Simple http request for retrieving external files (e.g. text tracks) * @param {String} url URL of resource * @param {Function=} onSuccess Success callback * @param {Function=} onError Error callback * @private */ vjs.get = function(url, onSuccess, onError){ var local, request; if (typeof XMLHttpRequest === 'undefined') { window.XMLHttpRequest = function () { try { return new window.ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (e) {} try { return new window.ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (f) {} try { return new window.ActiveXObject('Msxml2.XMLHTTP'); } catch (g) {} throw new Error('This browser does not support XMLHttpRequest.'); }; } request = new XMLHttpRequest(); try { request.open('GET', url); } catch(e) { onError(e); } local = (url.indexOf('file:') === 0 || (window.location.href.indexOf('file:') === 0 && url.indexOf('http') === -1)); request.onreadystatechange = function() { if (request.readyState === 4) { if (request.status === 200 || local && request.status === 0) { onSuccess(request.responseText); } else { if (onError) { onError(); } } } }; try { request.send(); } catch(e) { if (onError) { onError(e); } } }; /** * Add to local storage (may removeable) * @private */ vjs.setLocalStorage = function(key, value){ try { // IE was throwing errors referencing the var anywhere without this var localStorage = window.localStorage || false; if (!localStorage) { return; } localStorage[key] = value; } catch(e) { if (e.code == 22 || e.code == 1014) { // Webkit == 22 / Firefox == 1014 vjs.log('LocalStorage Full (VideoJS)', e); } else { if (e.code == 18) { vjs.log('LocalStorage not allowed (VideoJS)', e); } else { vjs.log('LocalStorage Error (VideoJS)', e); } } } }; /** * Get abosolute version of relative URL. Used to tell flash correct URL. * http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue * @param {String} url URL to make absolute * @return {String} Absolute URL * @private */ vjs.getAbsoluteURL = function(url){ // Check if absolute URL if (!url.match(/^https?:\/\//)) { // Convert to absolute URL. Flash hosted off-site needs an absolute URL. url = vjs.createEl('div', { innerHTML: '<a href="'+url+'">x</a>' }).firstChild.href; } return url; }; // usage: log('inside coolFunc',this,arguments); // http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/ vjs.log = function(){ vjs.log.history = vjs.log.history || []; // store logs to an array for reference vjs.log.history.push(arguments); if(window.console){ window.console.log(Array.prototype.slice.call(arguments)); } }; // Offset Left // getBoundingClientRect technique from John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/ vjs.findPosition = function(el) { var box, docEl, body, clientLeft, scrollLeft, left, clientTop, scrollTop, top; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0 }; } docEl = document.documentElement; body = document.body; clientLeft = docEl.clientLeft || body.clientLeft || 0; scrollLeft = window.pageXOffset || body.scrollLeft; left = box.left + scrollLeft - clientLeft; clientTop = docEl.clientTop || body.clientTop || 0; scrollTop = window.pageYOffset || body.scrollTop; top = box.top + scrollTop - clientTop; return { left: left, top: top }; }; /** * Utility functions namespace * @namespace * @type {Object} */ vjs.util = {}; /** * Merge two options objects, * recursively merging any plain object properties as well. * Previously `deepMerge` * * @param {Object} obj1 Object to override values in * @param {Object} obj2 Overriding object * @return {Object} New object -- obj1 and obj2 will be untouched */ vjs.util.mergeOptions = function(obj1, obj2){ var key, val1, val2; // make a copy of obj1 so we're not ovewriting original values. // like prototype.options_ and all sub options objects obj1 = vjs.obj.copy(obj1); for (key in obj2){ if (obj2.hasOwnProperty(key)) { val1 = obj1[key]; val2 = obj2[key]; // Check if both properties are pure objects and do a deep merge if so if (vjs.obj.isPlain(val1) && vjs.obj.isPlain(val2)) { obj1[key] = vjs.util.mergeOptions(val1, val2); } else { obj1[key] = obj2[key]; } } } return obj1; }; /** * @fileoverview Player Component - Base class for all UI objects * */ /** * Base UI Component class * * Components are embeddable UI objects that are represented by both a * javascript object and an element in the DOM. They can be children of other * components, and can have many children themselves. * * // adding a button to the player * var button = player.addChild('button'); * button.el(); // -> button element * * <div class="video-js"> * <div class="vjs-button">Button</div> * </div> * * Components are also event emitters. * * button.on('click', function(){ * console.log('Button Clicked!'); * }); * * button.trigger('customevent'); * * @param {Object} player Main Player * @param {Object=} options * @class * @constructor * @extends vjs.CoreObject */ vjs.Component = vjs.CoreObject.extend({ /** * the constructor function for the class * * @constructor */ init: function(player, options, ready){ this.player_ = player; // Make a copy of prototype.options_ to protect against overriding global defaults this.options_ = vjs.obj.copy(this.options_); // Updated options with supplied options options = this.options(options); // Get ID from options, element, or create using player ID and unique ID this.id_ = options['id'] || ((options['el'] && options['el']['id']) ? options['el']['id'] : player.id() + '_component_' + vjs.guid++ ); this.name_ = options['name'] || null; // Create element if one wasn't provided in options this.el_ = options['el'] || this.createEl(); this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options this.initChildren(); this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } } }); /** * Dispose of the component and all child components */ vjs.Component.prototype.dispose = function(){ this.trigger({ type: 'dispose', 'bubbles': false }); // Dispose all children. if (this.children_) { for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i].dispose) { this.children_[i].dispose(); } } } // Delete child references this.children_ = null; this.childIndex_ = null; this.childNameIndex_ = null; // Remove all event listeners. this.off(); // Remove element from DOM if (this.el_.parentNode) { this.el_.parentNode.removeChild(this.el_); } vjs.removeData(this.el_); this.el_ = null; }; /** * Reference to main player instance * * @type {vjs.Player} * @private */ vjs.Component.prototype.player_ = true; /** * Return the component's player * * @return {vjs.Player} */ vjs.Component.prototype.player = function(){ return this.player_; }; /** * The component's options object * * @type {Object} * @private */ vjs.Component.prototype.options_; /** * Deep merge of options objects * * Whenever a property is an object on both options objects * the two properties will be merged using vjs.obj.deepMerge. * * This is used for merging options for child components. We * want it to be easy to override individual options on a child * component without having to rewrite all the other default options. * * Parent.prototype.options_ = { * children: { * 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' }, * 'childTwo': {}, * 'childThree': {} * } * } * newOptions = { * children: { * 'childOne': { 'foo': 'baz', 'abc': '123' } * 'childTwo': null, * 'childFour': {} * } * } * * this.options(newOptions); * * RESULT * * { * children: { * 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' }, * 'childTwo': null, // Disabled. Won't be initialized. * 'childThree': {}, * 'childFour': {} * } * } * * @param {Object} obj Object of new option values * @return {Object} A NEW object of this.options_ and obj merged */ vjs.Component.prototype.options = function(obj){ if (obj === undefined) return this.options_; return this.options_ = vjs.util.mergeOptions(this.options_, obj); }; /** * The DOM element for the component * * @type {Element} * @private */ vjs.Component.prototype.el_; /** * Create the component's DOM element * * @param {String=} tagName Element's node type. e.g. 'div' * @param {Object=} attributes An object of element attributes that should be set on the element * @return {Element} */ vjs.Component.prototype.createEl = function(tagName, attributes){ return vjs.createEl(tagName, attributes); }; /** * Get the component's DOM element * * var domEl = myComponent.el(); * * @return {Element} */ vjs.Component.prototype.el = function(){ return this.el_; }; /** * An optional element where, if defined, children will be inserted instead of * directly in `el_` * * @type {Element} * @private */ vjs.Component.prototype.contentEl_; /** * Return the component's DOM element for embedding content. * Will either be el_ or a new element defined in createEl. * * @return {Element} */ vjs.Component.prototype.contentEl = function(){ return this.contentEl_ || this.el_; }; /** * The ID for the component * * @type {String} * @private */ vjs.Component.prototype.id_; /** * Get the component's ID * * var id = myComponent.id(); * * @return {String} */ vjs.Component.prototype.id = function(){ return this.id_; }; /** * The name for the component. Often used to reference the component. * * @type {String} * @private */ vjs.Component.prototype.name_; /** * Get the component's name. The name is often used to reference the component. * * var name = myComponent.name(); * * @return {String} */ vjs.Component.prototype.name = function(){ return this.name_; }; /** * Array of child components * * @type {Array} * @private */ vjs.Component.prototype.children_; /** * Get an array of all child components * * var kids = myComponent.children(); * * @return {Array} The children */ vjs.Component.prototype.children = function(){ return this.children_; }; /** * Object of child components by ID * * @type {Object} * @private */ vjs.Component.prototype.childIndex_; /** * Returns a child component with the provided ID * * @return {vjs.Component} */ vjs.Component.prototype.getChildById = function(id){ return this.childIndex_[id]; }; /** * Object of child components by name * * @type {Object} * @private */ vjs.Component.prototype.childNameIndex_; /** * Returns a child component with the provided name * * @return {vjs.Component} */ vjs.Component.prototype.getChild = function(name){ return this.childNameIndex_[name]; }; /** * Adds a child component inside this component * * myComponent.el(); * // -> <div class='my-component'></div> * myComonent.children(); * // [empty array] * * var myButton = myComponent.addChild('MyButton'); * // -> <div class='my-component'><div class="my-button">myButton<div></div> * // -> myButton === myComonent.children()[0]; * * Pass in options for child constructors and options for children of the child * * var myButton = myComponent.addChild('MyButton', { * text: 'Press Me', * children: { * buttonChildExample: { * buttonChildOption: true * } * } * }); * * @param {String|vjs.Component} child The class name or instance of a child to add * @param {Object=} options Options, including options to be passed to children of the child. * @return {vjs.Component} The child component (created by this process if a string was used) * @suppress {accessControls|checkRegExp|checkTypes|checkVars|const|constantProperty|deprecated|duplicate|es5Strict|fileoverviewTags|globalThis|invalidCasts|missingProperties|nonStandardJsDocs|strictModuleDepCheck|undefinedNames|undefinedVars|unknownDefines|uselessCode|visibility} */ vjs.Component.prototype.addChild = function(child, options){ var component, componentClass, componentName, componentId; // If string, create new component with options if (typeof child === 'string') { componentName = child; // Make sure options is at least an empty object to protect against errors options = options || {}; // Assume name of set is a lowercased name of the UI Class (PlayButton, etc.) componentClass = options['componentClass'] || vjs.capitalize(componentName); // Set name through options options['name'] = componentName; // Create a new object & element for this controls set // If there's no .player_, this is a player // Closure Compiler throws an 'incomplete alias' warning if we use the vjs variable directly. // Every class should be exported, so this should never be a problem here. component = new window['videojs'][componentClass](this.player_ || this, options); // child is a component instance } else { component = child; } this.children_.push(component); if (typeof component.id === 'function') { this.childIndex_[component.id()] = component; } // If a name wasn't used to create the component, check if we can use the // name function of the component componentName = componentName || (component.name && component.name()); if (componentName) { this.childNameIndex_[componentName] = component; } // Add the UI object's element to the container div (box) // Having an element is not required if (typeof component['el'] === 'function' && component['el']()) { this.contentEl().appendChild(component['el']()); } // Return so it can stored on parent object if desired. return component; }; /** * Remove a child component from this component's list of children, and the * child component's element from this component's element * * @param {vjs.Component} component Component to remove */ vjs.Component.prototype.removeChild = function(component){ if (typeof component === 'string') { component = this.getChild(component); } if (!component || !this.children_) return; var childFound = false; for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i] === component) { childFound = true; this.children_.splice(i,1); break; } } if (!childFound) return; this.childIndex_[component.id] = null; this.childNameIndex_[component.name] = null; var compEl = component.el(); if (compEl && compEl.parentNode === this.contentEl()) { this.contentEl().removeChild(component.el()); } }; /** * Add and initialize default child components from options * * // when an instance of MyComponent is created, all children in options * // will be added to the instance by their name strings and options * MyComponent.prototype.options_.children = { * myChildComponent: { * myChildOption: true * } * } */ vjs.Component.prototype.initChildren = function(){ var options = this.options_; if (options && options['children']) { var self = this; // Loop through components and add them to the player vjs.obj.each(options['children'], function(name, opts){ // Allow for disabling default components // e.g. vjs.options['children']['posterImage'] = false if (opts === false) return; // Allow waiting to add components until a specific event is called var tempAdd = function(){ // Set property name on player. Could cause conflicts with other prop names, but it's worth making refs easy. self[name] = self.addChild(name, opts); }; if (opts['loadEvent']) { // this.one(opts.loadEvent, tempAdd) } else { tempAdd(); } }); } }; /** * Allows sub components to stack CSS class names * * @return {String} The constructed class name */ vjs.Component.prototype.buildCSSClass = function(){ // Child classes can include a function that does: // return 'CLASS NAME' + this._super(); return ''; }; /* Events ============================================================================= */ /** * Add an event listener to this component's element * * var myFunc = function(){ * var myPlayer = this; * // Do something when the event is fired * }; * * myPlayer.on("eventName", myFunc); * * The context will be the component. * * @param {String} type The event type e.g. 'click' * @param {Function} fn The event listener * @return {vjs.Component} self */ vjs.Component.prototype.on = function(type, fn){ vjs.on(this.el_, type, vjs.bind(this, fn)); return this; }; /** * Remove an event listener from the component's element * * myComponent.off("eventName", myFunc); * * @param {String=} type Event type. Without type it will remove all listeners. * @param {Function=} fn Event listener. Without fn it will remove all listeners for a type. * @return {vjs.Component} */ vjs.Component.prototype.off = function(type, fn){ vjs.off(this.el_, type, fn); return this; }; /** * Add an event listener to be triggered only once and then removed * * @param {String} type Event type * @param {Function} fn Event listener * @return {vjs.Component} */ vjs.Component.prototype.one = function(type, fn) { vjs.one(this.el_, type, vjs.bind(this, fn)); return this; }; /** * Trigger an event on an element * * myComponent.trigger('eventName'); * * @param {String} type The event type to trigger, e.g. 'click' * @param {Event|Object} event The event object to be passed to the listener * @return {vjs.Component} self */ vjs.Component.prototype.trigger = function(type, event){ vjs.trigger(this.el_, type, event); return this; }; /* Ready ================================================================================ */ /** * Is the component loaded * This can mean different things depending on the component. * * @private * @type {Boolean} */ vjs.Component.prototype.isReady_; /** * Trigger ready as soon as initialization is finished * * Allows for delaying ready. Override on a sub class prototype. * If you set this.isReadyOnInitFinish_ it will affect all components. * Specially used when waiting for the Flash player to asynchrnously load. * * @type {Boolean} * @private */ vjs.Component.prototype.isReadyOnInitFinish_ = true; /** * List of ready listeners * * @type {Array} * @private */ vjs.Component.prototype.readyQueue_; /** * Bind a listener to the component's ready state * * Different from event listeners in that if the ready event has already happend * it will trigger the function immediately. * * @param {Function} fn Ready listener * @return {vjs.Component} */ vjs.Component.prototype.ready = function(fn){ if (fn) { if (this.isReady_) { fn.call(this); } else { if (this.readyQueue_ === undefined) { this.readyQueue_ = []; } this.readyQueue_.push(fn); } } return this; }; /** * Trigger the ready listeners * * @return {vjs.Component} */ vjs.Component.prototype.triggerReady = function(){ this.isReady_ = true; var readyQueue = this.readyQueue_; if (readyQueue && readyQueue.length > 0) { for (var i = 0, j = readyQueue.length; i < j; i++) { readyQueue[i].call(this); } // Reset Ready Queue this.readyQueue_ = []; // Allow for using event listeners also, in case you want to do something everytime a source is ready. this.trigger('ready'); } }; /* Display ============================================================================= */ /** * Add a CSS class name to the component's element * * @param {String} classToAdd Classname to add * @return {vjs.Component} */ vjs.Component.prototype.addClass = function(classToAdd){ vjs.addClass(this.el_, classToAdd); return this; }; /** * Remove a CSS class name from the component's element * * @param {String} classToRemove Classname to remove * @return {vjs.Component} */ vjs.Component.prototype.removeClass = function(classToRemove){ vjs.removeClass(this.el_, classToRemove); return this; }; /** * Show the component element if hidden * * @return {vjs.Component} */ vjs.Component.prototype.show = function(){ this.el_.style.display = 'block'; return this; }; /** * Hide the component element if currently showing * * @return {vjs.Component} */ vjs.Component.prototype.hide = function(){ this.el_.style.display = 'none'; return this; }; /** * Lock an item in its visible state * To be used with fadeIn/fadeOut. * * @return {vjs.Component} * @private */ vjs.Component.prototype.lockShowing = function(){ this.addClass('vjs-lock-showing'); return this; }; /** * Unlock an item to be hidden * To be used with fadeIn/fadeOut. * * @return {vjs.Component} * @private */ vjs.Component.prototype.unlockShowing = function(){ this.removeClass('vjs-lock-showing'); return this; }; /** * Disable component by making it unshowable * * Currently private because we're movign towards more css-based states. * @private */ vjs.Component.prototype.disable = function(){ this.hide(); this.show = function(){}; }; /** * Set or get the width of the component (CSS values) * * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num Optional width number * @param {Boolean} skipListeners Skip the 'resize' event trigger * @return {vjs.Component} This component, when setting the width * @return {Number|String} The width, when getting */ vjs.Component.prototype.width = function(num, skipListeners){ return this.dimension('width', num, skipListeners); }; /** * Get or set the height of the component (CSS values) * * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num New component height * @param {Boolean=} skipListeners Skip the resize event trigger * @return {vjs.Component} This component, when setting the height * @return {Number|String} The height, when getting */ vjs.Component.prototype.height = function(num, skipListeners){ return this.dimension('height', num, skipListeners); }; /** * Set both width and height at the same time * * @param {Number|String} width * @param {Number|String} height * @return {vjs.Component} The component */ vjs.Component.prototype.dimensions = function(width, height){ // Skip resize listeners on width for optimization return this.width(width, true).height(height); }; /** * Get or set width or height * * This is the shared code for the width() and height() methods. * All for an integer, integer + 'px' or integer + '%'; * * Known issue: Hidden elements officially have a width of 0. We're defaulting * to the style.width value and falling back to computedStyle which has the * hidden element issue. Info, but probably not an efficient fix: * http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/ * * @param {String} widthOrHeight 'width' or 'height' * @param {Number|String=} num New dimension * @param {Boolean=} skipListeners Skip resize event trigger * @return {vjs.Component} The component if a dimension was set * @return {Number|String} The dimension if nothing was set * @private */ vjs.Component.prototype.dimension = function(widthOrHeight, num, skipListeners){ if (num !== undefined) { // Check if using css width/height (% or px) and adjust if ((''+num).indexOf('%') !== -1 || (''+num).indexOf('px') !== -1) { this.el_.style[widthOrHeight] = num; } else if (num === 'auto') { this.el_.style[widthOrHeight] = ''; } else { this.el_.style[widthOrHeight] = num+'px'; } // skipListeners allows us to avoid triggering the resize event when setting both width and height if (!skipListeners) { this.trigger('resize'); } // Return component return this; } // Not setting a value, so getting it // Make sure element exists if (!this.el_) return 0; // Get dimension value from style var val = this.el_.style[widthOrHeight]; var pxIndex = val.indexOf('px'); if (pxIndex !== -1) { // Return the pixel value with no 'px' return parseInt(val.slice(0,pxIndex), 10); // No px so using % or no style was set, so falling back to offsetWidth/height // If component has display:none, offset will return 0 // TODO: handle display:none and no dimension style using px } else { return parseInt(this.el_['offset'+vjs.capitalize(widthOrHeight)], 10); // ComputedStyle version. // Only difference is if the element is hidden it will return // the percent value (e.g. '100%'') // instead of zero like offsetWidth returns. // var val = vjs.getComputedStyleValue(this.el_, widthOrHeight); // var pxIndex = val.indexOf('px'); // if (pxIndex !== -1) { // return val.slice(0, pxIndex); // } else { // return val; // } } }; /** * Fired when the width and/or height of the component changes * @event resize */ vjs.Component.prototype.onResize; /** * Emit 'tap' events when touch events are supported * * This is used to support toggling the controls through a tap on the video. * * We're requireing them to be enabled because otherwise every component would * have this extra overhead unnecessarily, on mobile devices where extra * overhead is especially bad. * @private */ vjs.Component.prototype.emitTapEvents = function(){ var touchStart, touchTime, couldBeTap, noTap; // Track the start time so we can determine how long the touch lasted touchStart = 0; this.on('touchstart', function(event) { // Record start time so we can detect a tap vs. "touch and hold" touchStart = new Date().getTime(); // Reset couldBeTap tracking couldBeTap = true; }); noTap = function(){ couldBeTap = false; }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s this.on('touchmove', noTap); this.on('touchleave', noTap); this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate // event this.on('touchend', function(event) { // Proceed only if the touchmove/leave/cancel event didn't happen if (couldBeTap === true) { // Measure how long the touch lasted touchTime = new Date().getTime() - touchStart; // The touch needs to be quick in order to consider it a tap if (touchTime < 250) { this.trigger('tap'); // It may be good to copy the touchend event object and change the // type to tap, if the other event properties aren't exact after // vjs.fixEvent runs (e.g. event.target) } } }); }; /** * Report user touch activity when touch events occur * * User activity is used to determine when controls should show/hide. It's * relatively simple when it comes to mouse events, because any mouse event * should show the controls. So we capture mouse events that bubble up to the * player and report activity when that happens. * * With touch events it isn't as easy. We can't rely on touch events at the * player level, because a tap (touchstart + touchend) on the video itself on * mobile devices is meant to turn controls off (and on). User activity is * checked asynchronously, so what could happen is a tap event on the video * turns the controls off, then the touchend event bubbles up to the player, * which if it reported user activity, would turn the controls right back on. * (We also don't want to completely block touch events from bubbling up) * * Also a touchmove, touch+hold, and anything other than a tap is not supposed * to turn the controls back on on a mobile device. * * Here we're setting the default component behavior to report user activity * whenever touch events happen, and this can be turned off by components that * want touch events to act differently. */ vjs.Component.prototype.enableTouchActivity = function() { var report, touchHolding, touchEnd; // listener for reporting that the user is active report = vjs.bind(this.player(), this.player().reportUserActivity); this.on('touchstart', function() { report(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active clearInterval(touchHolding); // report at the same interval as activityCheck touchHolding = setInterval(report, 250); }); touchEnd = function(event) { report(); // stop the interval that maintains activity if the touch is holding clearInterval(touchHolding); }; this.on('touchmove', report); this.on('touchend', touchEnd); this.on('touchcancel', touchEnd); }; /* Button - Base class for all buttons ================================================================================ */ /** * Base class for all buttons * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.Button = vjs.Component.extend({ /** * @constructor * @inheritDoc */ init: function(player, options){ vjs.Component.call(this, player, options); var touchstart = false; this.on('touchstart', function(event) { // Stop click and other mouse events from triggering also event.preventDefault(); touchstart = true; }); this.on('touchmove', function() { touchstart = false; }); var self = this; this.on('touchend', function(event) { if (touchstart) { self.onClick(event); } event.preventDefault(); }); this.on('click', this.onClick); this.on('focus', this.onFocus); this.on('blur', this.onBlur); } }); vjs.Button.prototype.createEl = function(type, props){ // Add standard Aria and Tabindex info props = vjs.obj.merge({ className: this.buildCSSClass(), innerHTML: '<div class="vjs-control-content"><span class="vjs-control-text">' + (this.buttonText || 'Need Text') + '</span></div>', 'role': 'button', 'aria-live': 'polite', // let the screen reader user know that the text of the button may change tabIndex: 0 }, props); return vjs.Component.prototype.createEl.call(this, type, props); }; vjs.Button.prototype.buildCSSClass = function(){ // TODO: Change vjs-control to vjs-button? return 'vjs-control ' + vjs.Component.prototype.buildCSSClass.call(this); }; // Click - Override with specific functionality for button vjs.Button.prototype.onClick = function(){}; // Focus - Add keyboard functionality to element vjs.Button.prototype.onFocus = function(){ vjs.on(document, 'keyup', vjs.bind(this, this.onKeyPress)); }; // KeyPress (document level) - Trigger click when keys are pressed vjs.Button.prototype.onKeyPress = function(event){ // Check for space bar (32) or enter (13) keys if (event.which == 32 || event.which == 13) { event.preventDefault(); this.onClick(); } }; // Blur - Remove keyboard triggers vjs.Button.prototype.onBlur = function(){ vjs.off(document, 'keyup', vjs.bind(this, this.onKeyPress)); }; /* Slider ================================================================================ */ /** * The base functionality for sliders like the volume bar and seek bar * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.Slider = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // Set property names to bar and handle to match with the child Slider class is looking for this.bar = this.getChild(this.options_['barName']); this.handle = this.getChild(this.options_['handleName']); player.on(this.playerEvent, vjs.bind(this, this.update)); this.on('mousedown', this.onMouseDown); this.on('touchstart', this.onMouseDown); this.on('focus', this.onFocus); this.on('blur', this.onBlur); this.on('click', this.onClick); this.player_.on('controlsvisible', vjs.bind(this, this.update)); // This is actually to fix the volume handle position. http://twitter.com/#!/gerritvanaaken/status/159046254519787520 // this.player_.one('timeupdate', vjs.bind(this, this.update)); player.ready(vjs.bind(this, this.update)); this.boundEvents = {}; } }); vjs.Slider.prototype.createEl = function(type, props) { props = props || {}; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider'; props = vjs.obj.merge({ 'role': 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, tabIndex: 0 }, props); return vjs.Component.prototype.createEl.call(this, type, props); }; vjs.Slider.prototype.onMouseDown = function(event){ event.preventDefault(); vjs.blockTextSelection(); this.boundEvents.move = vjs.bind(this, this.onMouseMove); this.boundEvents.end = vjs.bind(this, this.onMouseUp); vjs.on(document, 'mousemove', this.boundEvents.move); vjs.on(document, 'mouseup', this.boundEvents.end); vjs.on(document, 'touchmove', this.boundEvents.move); vjs.on(document, 'touchend', this.boundEvents.end); this.onMouseMove(event); }; vjs.Slider.prototype.onMouseUp = function() { vjs.unblockTextSelection(); vjs.off(document, 'mousemove', this.boundEvents.move, false); vjs.off(document, 'mouseup', this.boundEvents.end, false); vjs.off(document, 'touchmove', this.boundEvents.move, false); vjs.off(document, 'touchend', this.boundEvents.end, false); this.update(); }; vjs.Slider.prototype.update = function(){ // In VolumeBar init we have a setTimeout for update that pops and update to the end of the // execution stack. The player is destroyed before then update will cause an error if (!this.el_) return; // If scrubbing, we could use a cached value to make the handle keep up with the user's mouse. // On HTML5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later. // var progress = (this.player_.scrubbing) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration(); var barProgress, progress = this.getPercent(), handle = this.handle, bar = this.bar; // Protect against no duration and other division issues if (isNaN(progress)) { progress = 0; } barProgress = progress; // If there is a handle, we need to account for the handle in our calculation for progress bar // so that it doesn't fall short of or extend past the handle. if (handle) { var box = this.el_, boxWidth = box.offsetWidth, handleWidth = handle.el().offsetWidth, // The width of the handle in percent of the containing box // In IE, widths may not be ready yet causing NaN handlePercent = (handleWidth) ? handleWidth / boxWidth : 0, // Get the adjusted size of the box, considering that the handle's center never touches the left or right side. // There is a margin of half the handle's width on both sides. boxAdjustedPercent = 1 - handlePercent, // Adjust the progress that we'll use to set widths to the new adjusted box width adjustedProgress = progress * boxAdjustedPercent; // The bar does reach the left side, so we need to account for this in the bar's width barProgress = adjustedProgress + (handlePercent / 2); // Move the handle from the left based on the adjected progress handle.el().style.left = vjs.round(adjustedProgress * 100, 2) + '%'; } // Set the new bar width bar.el().style.width = vjs.round(barProgress * 100, 2) + '%'; }; vjs.Slider.prototype.calculateDistance = function(event){ var el, box, boxX, boxY, boxW, boxH, handle, pageX, pageY; el = this.el_; box = vjs.findPosition(el); boxW = boxH = el.offsetWidth; handle = this.handle; if (this.options_.vertical) { boxY = box.top; if (event.changedTouches) { pageY = event.changedTouches[0].pageY; } else { pageY = event.pageY; } if (handle) { var handleH = handle.el().offsetHeight; // Adjusted X and Width, so handle doesn't go outside the bar boxY = boxY + (handleH / 2); boxH = boxH - handleH; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, ((boxY - pageY) + boxH) / boxH)); } else { boxX = box.left; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; } else { pageX = event.pageX; } if (handle) { var handleW = handle.el().offsetWidth; // Adjusted X and Width, so handle doesn't go outside the bar boxX = boxX + (handleW / 2); boxW = boxW - handleW; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, (pageX - boxX) / boxW)); } }; vjs.Slider.prototype.onFocus = function(){ vjs.on(document, 'keyup', vjs.bind(this, this.onKeyPress)); }; vjs.Slider.prototype.onKeyPress = function(event){ if (event.which == 37) { // Left Arrow event.preventDefault(); this.stepBack(); } else if (event.which == 39) { // Right Arrow event.preventDefault(); this.stepForward(); } }; vjs.Slider.prototype.onBlur = function(){ vjs.off(document, 'keyup', vjs.bind(this, this.onKeyPress)); }; /** * Listener for click events on slider, used to prevent clicks * from bubbling up to parent elements like button menus. * @param {Object} event Event object */ vjs.Slider.prototype.onClick = function(event){ event.stopImmediatePropagation(); event.preventDefault(); }; /** * SeekBar Behavior includes play progress bar, and seek handle * Needed so it can determine seek position based on handle position/size * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.SliderHandle = vjs.Component.extend(); /** * Default value of the slider * * @type {Number} * @private */ vjs.SliderHandle.prototype.defaultValue = 0; /** @inheritDoc */ vjs.SliderHandle.prototype.createEl = function(type, props) { props = props || {}; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider-handle'; props = vjs.obj.merge({ innerHTML: '<span class="vjs-control-text">'+this.defaultValue+'</span>' }, props); return vjs.Component.prototype.createEl.call(this, 'div', props); }; /* Menu ================================================================================ */ /** * The Menu component is used to build pop up menus, including subtitle and * captions selection menus. * * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.Menu = vjs.Component.extend(); /** * Add a menu item to the menu * @param {Object|String} component Component or component type to add */ vjs.Menu.prototype.addItem = function(component){ this.addChild(component); component.on('click', vjs.bind(this, function(){ this.unlockShowing(); })); }; /** @inheritDoc */ vjs.Menu.prototype.createEl = function(){ var contentElType = this.options().contentElType || 'ul'; this.contentEl_ = vjs.createEl(contentElType, { className: 'vjs-menu-content' }); var el = vjs.Component.prototype.createEl.call(this, 'div', { append: this.contentEl_, className: 'vjs-menu' }); el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons, // where a click on the parent is significant vjs.on(el, 'click', function(event){ event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; /** * The component for a menu item. `<li>` * * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.MenuItem = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.selected(options['selected']); } }); /** @inheritDoc */ vjs.MenuItem.prototype.createEl = function(type, props){ return vjs.Button.prototype.createEl.call(this, 'li', vjs.obj.merge({ className: 'vjs-menu-item', innerHTML: this.options_['label'] }, props)); }; /** * Handle a click on the menu item, and set it to selected */ vjs.MenuItem.prototype.onClick = function(){ this.selected(true); }; /** * Set this menu item as selected or not * @param {Boolean} selected */ vjs.MenuItem.prototype.selected = function(selected){ if (selected) { this.addClass('vjs-selected'); this.el_.setAttribute('aria-selected',true); } else { this.removeClass('vjs-selected'); this.el_.setAttribute('aria-selected',false); } }; /** * A button class with a popup menu * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.MenuButton = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.menu = this.createMenu(); // Add list to element this.addChild(this.menu); // Automatically hide empty menu buttons if (this.items && this.items.length === 0) { this.hide(); } this.on('keyup', this.onKeyPress); this.el_.setAttribute('aria-haspopup', true); this.el_.setAttribute('role', 'button'); } }); /** * Track the state of the menu button * @type {Boolean} * @private */ vjs.MenuButton.prototype.buttonPressed_ = false; vjs.MenuButton.prototype.createMenu = function(){ var menu = new vjs.Menu(this.player_); // Add a title list item to the top if (this.options().title) { menu.el().appendChild(vjs.createEl('li', { className: 'vjs-menu-title', innerHTML: vjs.capitalize(this.kind_), tabindex: -1 })); } this.items = this['createItems'](); if (this.items) { // Add menu items to the menu for (var i = 0; i < this.items.length; i++) { menu.addItem(this.items[i]); } } return menu; }; /** * Create the list of menu items. Specific to each subclass. */ vjs.MenuButton.prototype.createItems = function(){}; /** @inheritDoc */ vjs.MenuButton.prototype.buildCSSClass = function(){ return this.className + ' vjs-menu-button ' + vjs.Button.prototype.buildCSSClass.call(this); }; // Focus - Add keyboard functionality to element // This function is not needed anymore. Instead, the keyboard functionality is handled by // treating the button as triggering a submenu. When the button is pressed, the submenu // appears. Pressing the button again makes the submenu disappear. vjs.MenuButton.prototype.onFocus = function(){}; // Can't turn off list display that we turned on with focus, because list would go away. vjs.MenuButton.prototype.onBlur = function(){}; vjs.MenuButton.prototype.onClick = function(){ // When you click the button it adds focus, which will show the menu indefinitely. // So we'll remove focus when the mouse leaves the button. // Focus is needed for tab navigation. this.one('mouseout', vjs.bind(this, function(){ this.menu.unlockShowing(); this.el_.blur(); })); if (this.buttonPressed_){ this.unpressButton(); } else { this.pressButton(); } }; vjs.MenuButton.prototype.onKeyPress = function(event){ event.preventDefault(); // Check for space bar (32) or enter (13) keys if (event.which == 32 || event.which == 13) { if (this.buttonPressed_){ this.unpressButton(); } else { this.pressButton(); } // Check for escape (27) key } else if (event.which == 27){ if (this.buttonPressed_){ this.unpressButton(); } } }; vjs.MenuButton.prototype.pressButton = function(){ this.buttonPressed_ = true; this.menu.lockShowing(); this.el_.setAttribute('aria-pressed', true); if (this.items && this.items.length > 0) { this.items[0].el().focus(); // set the focus to the title of the submenu } }; vjs.MenuButton.prototype.unpressButton = function(){ this.buttonPressed_ = false; this.menu.unlockShowing(); this.el_.setAttribute('aria-pressed', false); }; /** * An instance of the `vjs.Player` class is created when any of the Video.js setup methods are used to initialize a video. * * ```js * var myPlayer = videojs('example_video_1'); * ``` * * In the follwing example, the `data-setup` attribute tells the Video.js library to create a player instance when the library is ready. * * ```html * <video id="example_video_1" data-setup='{}' controls> * <source src="my-source.mp4" type="video/mp4"> * </video> * ``` * * After an instance has been created it can be accessed globally using `Video('example_video_1')`. * * @class * @extends vjs.Component */ vjs.Player = vjs.Component.extend({ /** * player's constructor function * * @constructs * @method init * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Player options * @param {Function=} ready Ready callback function */ init: function(tag, options, ready){ this.tag = tag; // Store the original tag used to set options // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + vjs.guid++; // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = vjs.obj.merge(this.getTagSettings(tag), options); // Cache for video property values. this.cache_ = {}; // Set poster this.poster_ = options['poster']; // Set controls this.controls_ = options['controls']; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // Run base component initializing with new options. // Builds the element through createEl() // Inits and embeds any child components in opts vjs.Component.call(this, this, options, ready); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (this.controls()) { this.addClass('vjs-controls-enabled'); } else { this.addClass('vjs-controls-disabled'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (vjs.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // Firstplay event implimentation. Not sold on the event yet. // Could probably just check currentTime==0? this.one('play', function(e){ var fpEvent = { type: 'firstplay', target: this.el_ }; // Using vjs.trigger so we can check if default was prevented var keepGoing = vjs.trigger(this.el_, fpEvent); if (!keepGoing) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); } }); this.on('ended', this.onEnded); this.on('play', this.onPlay); this.on('firstplay', this.onFirstPlay); this.on('pause', this.onPause); this.on('progress', this.onProgress); this.on('durationchange', this.onDurationChange); this.on('error', this.onError); this.on('fullscreenchange', this.onFullscreenChange); // Make player easily findable by ID vjs.players[this.id_] = this; if (options['plugins']) { vjs.obj.each(options['plugins'], function(key, val){ this[key](val); }, this); } this.listenForUserActivity(); } }); /** * Player instance options, surfaced using vjs.options * vjs.options = vjs.Player.prototype.options_ * Make changes in vjs.options, not here. * All options should use string keys so they avoid * renaming by closure compiler * @type {Object} * @private */ vjs.Player.prototype.options_ = vjs.options; /** * Destroys the video player and does any necessary cleanup * * myPlayer.dispose(); * * This is especially helpful if you are dynamically adding and removing videos * to/from the DOM. */ vjs.Player.prototype.dispose = function(){ this.trigger('dispose'); // prevent dispose from being called twice this.off('dispose'); // Kill reference to this player vjs.players[this.id_] = null; if (this.tag && this.tag['player']) { this.tag['player'] = null; } if (this.el_ && this.el_['player']) { this.el_['player'] = null; } // Ensure that tracking progress and time progress will stop and plater deleted this.stopTrackingProgress(); this.stopTrackingCurrentTime(); if (this.tech) { this.tech.dispose(); } // Component dispose vjs.Component.prototype.dispose.call(this); }; vjs.Player.prototype.getTagSettings = function(tag){ var options = { 'sources': [], 'tracks': [] }; vjs.obj.merge(options, vjs.getAttributeValues(tag)); // Get tag children settings if (tag.hasChildNodes()) { var children, child, childName, i, j; children = tag.childNodes; for (i=0,j=children.length; i<j; i++) { child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/ childName = child.nodeName.toLowerCase(); if (childName === 'source') { options['sources'].push(vjs.getAttributeValues(child)); } else if (childName === 'track') { options['tracks'].push(vjs.getAttributeValues(child)); } } } return options; }; vjs.Player.prototype.createEl = function(){ var el = this.el_ = vjs.Component.prototype.createEl.call(this, 'div'); var tag = this.tag; // Remove width/height attrs from tag so CSS can make it 100% width/height tag.removeAttribute('width'); tag.removeAttribute('height'); // Empty video tag tracks so the built-in player doesn't use them also. // This may not be fast enough to stop HTML5 browsers from reading the tags // so we'll need to turn off any default tracks if we're manually doing // captions and subtitles. videoElement.textTracks if (tag.hasChildNodes()) { var nodes, nodesLength, i, node, nodeName, removeNodes; nodes = tag.childNodes; nodesLength = nodes.length; removeNodes = []; while (nodesLength--) { node = nodes[nodesLength]; nodeName = node.nodeName.toLowerCase(); if (nodeName === 'track') { removeNodes.push(node); } } for (i=0; i<removeNodes.length; i++) { tag.removeChild(removeNodes[i]); } } // Give video tag ID and class to player div // ID will now reference player box, not the video tag el.id = tag.id; el.className = tag.className; // Update tag id/class for use as HTML5 playback tech // Might think we should do this after embedding in container so .vjs-tech class // doesn't flash 100% width/height, but class only applies with .video-js parent tag.id += '_html5_api'; tag.className = 'vjs-tech'; // Make player findable on elements tag['player'] = el['player'] = this; // Default state of video is paused this.addClass('vjs-paused'); // Make box use width/height of tag, or rely on default implementation // Enforce with CSS since width/height attrs don't work on divs this.width(this.options_['width'], true); // (true) Skip resize listener on load this.height(this.options_['height'], true); // Wrap video tag in div (el/box) container if (tag.parentNode) { tag.parentNode.insertBefore(el, tag); } vjs.insertFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup. return el; }; // /* Media Technology (tech) // ================================================================================ */ // Load/Create an instance of playback technlogy including element and API methods // And append playback element in player div. vjs.Player.prototype.loadTech = function(techName, source){ // Pause and remove current playback technology if (this.tech) { this.unloadTech(); } // get rid of the HTML5 video tag as soon as we are using another tech if (techName !== 'Html5' && this.tag) { vjs.Html5.disposeMediaElement(this.tag); this.tag = null; } this.techName = techName; // Turn off API access because we're loading a new tech that might load asynchronously this.isReady_ = false; var techReady = function(){ this.player_.triggerReady(); // Manually track progress in cases where the browser/flash player doesn't report it. if (!this.features['progressEvents']) { this.player_.manualProgressOn(); } // Manually track timeudpates in cases where the browser/flash player doesn't report it. if (!this.features['timeupdateEvents']) { this.player_.manualTimeUpdatesOn(); } }; // Grab tech-specific options from player options and add source and parent element to use. var techOptions = vjs.obj.merge({ 'source': source, 'parentEl': this.el_ }, this.options_[techName.toLowerCase()]); if (source) { if (source.src == this.cache_.src && this.cache_.currentTime > 0) { techOptions['startTime'] = this.cache_.currentTime; } this.cache_.src = source.src; } // Initialize tech instance this.tech = new window['videojs'][techName](this, techOptions); this.tech.ready(techReady); }; vjs.Player.prototype.unloadTech = function(){ this.isReady_ = false; this.tech.dispose(); // Turn off any manual progress or timeupdate tracking if (this.manualProgress) { this.manualProgressOff(); } if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); } this.tech = false; }; // There's many issues around changing the size of a Flash (or other plugin) object. // First is a plugin reload issue in Firefox that has been around for 11 years: https://bugzilla.mozilla.org/show_bug.cgi?id=90268 // Then with the new fullscreen API, Mozilla and webkit browsers will reload the flash object after going to fullscreen. // To get around this, we're unloading the tech, caching source and currentTime values, and reloading the tech once the plugin is resized. // reloadTech: function(betweenFn){ // vjs.log('unloadingTech') // this.unloadTech(); // vjs.log('unloadedTech') // if (betweenFn) { betweenFn.call(); } // vjs.log('LoadingTech') // this.loadTech(this.techName, { src: this.cache_.src }) // vjs.log('loadedTech') // }, /* Fallbacks for unsupported event types ================================================================================ */ // Manually trigger progress events based on changes to the buffered amount // Many flash players and older HTML5 browsers don't send progress or progress-like events vjs.Player.prototype.manualProgressOn = function(){ this.manualProgress = true; // Trigger progress watching when a source begins loading this.trackProgress(); // Watch for a native progress event call on the tech element // In HTML5, some older versions don't support the progress event // So we're assuming they don't, and turning off manual progress if they do. // As opposed to doing user agent detection this.tech.one('progress', function(){ // Update known progress support for this playback technology this.features['progressEvents'] = true; // Turn off manual progress tracking this.player_.manualProgressOff(); }); }; vjs.Player.prototype.manualProgressOff = function(){ this.manualProgress = false; this.stopTrackingProgress(); }; vjs.Player.prototype.trackProgress = function(){ this.progressInterval = setInterval(vjs.bind(this, function(){ // Don't trigger unless buffered amount is greater than last time // log(this.cache_.bufferEnd, this.buffered().end(0), this.duration()) /* TODO: update for multiple buffered regions */ if (this.cache_.bufferEnd < this.buffered().end(0)) { this.trigger('progress'); } else if (this.bufferedPercent() == 1) { this.stopTrackingProgress(); this.trigger('progress'); // Last update } }), 500); }; vjs.Player.prototype.stopTrackingProgress = function(){ clearInterval(this.progressInterval); }; /*! Time Tracking -------------------------------------------------------------- */ vjs.Player.prototype.manualTimeUpdatesOn = function(){ this.manualTimeUpdates = true; this.on('play', this.trackCurrentTime); this.on('pause', this.stopTrackingCurrentTime); // timeupdate is also called by .currentTime whenever current time is set // Watch for native timeupdate event this.tech.one('timeupdate', function(){ // Update known progress support for this playback technology this.features['timeupdateEvents'] = true; // Turn off manual progress tracking this.player_.manualTimeUpdatesOff(); }); }; vjs.Player.prototype.manualTimeUpdatesOff = function(){ this.manualTimeUpdates = false; this.stopTrackingCurrentTime(); this.off('play', this.trackCurrentTime); this.off('pause', this.stopTrackingCurrentTime); }; vjs.Player.prototype.trackCurrentTime = function(){ if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); } this.currentTimeInterval = setInterval(vjs.bind(this, function(){ this.trigger('timeupdate'); }), 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15 }; // Turn off play progress tracking (when paused or dragging) vjs.Player.prototype.stopTrackingCurrentTime = function(){ clearInterval(this.currentTimeInterval); }; // /* Player event handlers (how the player reacts to certain events) // ================================================================================ */ /** * Fired when the user agent begins looking for media data * @event loadstart */ vjs.Player.prototype.onLoadStart; /** * Fired when the player has initial duration and dimension information * @event loadedmetadata */ vjs.Player.prototype.onLoadedMetaData; /** * Fired when the player has downloaded data at the current playback position * @event loadeddata */ vjs.Player.prototype.onLoadedData; /** * Fired when the player has finished downloading the source data * @event loadedalldata */ vjs.Player.prototype.onLoadedAllData; /** * Fired whenever the media begins or resumes playback * @event play */ vjs.Player.prototype.onPlay = function(){ vjs.removeClass(this.el_, 'vjs-paused'); vjs.addClass(this.el_, 'vjs-playing'); }; /** * Fired the first time a video is played * * Not part of the HLS spec, and we're not sure if this is the best * implementation yet, so use sparingly. If you don't have a reason to * prevent playback, use `myPlayer.one('play');` instead. * * @event firstplay */ vjs.Player.prototype.onFirstPlay = function(){ //If the first starttime attribute is specified //then we will start at the given offset in seconds if(this.options_['starttime']){ this.currentTime(this.options_['starttime']); } this.addClass('vjs-has-started'); }; /** * Fired whenever the media has been paused * @event pause */ vjs.Player.prototype.onPause = function(){ vjs.removeClass(this.el_, 'vjs-playing'); vjs.addClass(this.el_, 'vjs-paused'); }; /** * Fired when the current playback position has changed * * During playback this is fired every 15-250 milliseconds, depnding on the * playback technology in use. * @event timeupdate */ vjs.Player.prototype.onTimeUpdate; /** * Fired while the user agent is downloading media data * @event progress */ vjs.Player.prototype.onProgress = function(){ // Add custom event for when source is finished downloading. if (this.bufferedPercent() == 1) { this.trigger('loadedalldata'); } }; /** * Fired when the end of the media resource is reached (currentTime == duration) * @event ended */ vjs.Player.prototype.onEnded = function(){ if (this.options_['loop']) { this.currentTime(0); this.play(); } }; /** * Fired when the duration of the media resource is first known or changed * @event durationchange */ vjs.Player.prototype.onDurationChange = function(){ // Allows for cacheing value instead of asking player each time. // We need to get the techGet response and check for a value so we don't // accidentally cause the stack to blow up. var duration = this.techGet('duration'); if (duration) { this.duration(duration); } }; /** * Fired when the volume changes * @event volumechange */ vjs.Player.prototype.onVolumeChange; /** * Fired when the player switches in or out of fullscreen mode * @event fullscreenchange */ vjs.Player.prototype.onFullscreenChange = function() { if (this.isFullScreen()) { this.addClass('vjs-fullscreen'); } else { this.removeClass('vjs-fullscreen'); } }; /** * Fired when there is an error in playback * @event error */ vjs.Player.prototype.onError = function(e) { vjs.log('Video Error', e); }; // /* Player API // ================================================================================ */ /** * Object for cached values. * @private */ vjs.Player.prototype.cache_; vjs.Player.prototype.getCache = function(){ return this.cache_; }; // Pass values to the playback tech vjs.Player.prototype.techCall = function(method, arg){ // If it's not ready yet, call method when it is if (this.tech && !this.tech.isReady_) { this.tech.ready(function(){ this[method](arg); }); // Otherwise call method now } else { try { this.tech[method](arg); } catch(e) { vjs.log(e); throw e; } } }; // Get calls can't wait for the tech, and sometimes don't need to. vjs.Player.prototype.techGet = function(method){ if (this.tech && this.tech.isReady_) { // Flash likes to die and reload when you hide or reposition it. // In these cases the object methods go away and we get errors. // When that happens we'll catch the errors and inform tech that it's not ready any more. try { return this.tech[method](); } catch(e) { // When building additional tech libs, an expected method may not be defined yet if (this.tech[method] === undefined) { vjs.log('Video.js: ' + method + ' method not defined for '+this.techName+' playback technology.', e); } else { // When a method isn't available on the object it throws a TypeError if (e.name == 'TypeError') { vjs.log('Video.js: ' + method + ' unavailable on '+this.techName+' playback technology element.', e); this.tech.isReady_ = false; } else { vjs.log(e); } } throw e; } } return; }; /** * start media playback * * myPlayer.play(); * * @return {vjs.Player} self */ vjs.Player.prototype.play = function(){ this.techCall('play'); return this; }; /** * Pause the video playback * * myPlayer.pause(); * * @return {vjs.Player} self */ vjs.Player.prototype.pause = function(){ this.techCall('pause'); return this; }; /** * Check if the player is paused * * var isPaused = myPlayer.paused(); * var isPlaying = !myPlayer.paused(); * * @return {Boolean} false if the media is currently playing, or true otherwise */ vjs.Player.prototype.paused = function(){ // The initial state of paused should be true (in Safari it's actually false) return (this.techGet('paused') === false) ? false : true; }; /** * Get or set the current time (in seconds) * * // get * var whereYouAt = myPlayer.currentTime(); * * // set * myPlayer.currentTime(120); // 2 minutes into the video * * @param {Number|String=} seconds The time to seek to * @return {Number} The time in seconds, when not setting * @return {vjs.Player} self, when the current time is set */ vjs.Player.prototype.currentTime = function(seconds){ if (seconds !== undefined) { this.techCall('setCurrentTime', seconds); // improve the accuracy of manual timeupdates if (this.manualTimeUpdates) { this.trigger('timeupdate'); } return this; } // cache last currentTime and return. default to 0 seconds // // Caching the currentTime is meant to prevent a massive amount of reads on the tech's // currentTime when scrubbing, but may not provide much performace benefit afterall. // Should be tested. Also something has to read the actual current time or the cache will // never get updated. return this.cache_.currentTime = (this.techGet('currentTime') || 0); }; /** * Get the length in time of the video in seconds * * var lengthOfVideo = myPlayer.duration(); * * **NOTE**: The video must have started loading before the duration can be * known, and in the case of Flash, may not be known until the video starts * playing. * * @return {Number} The duration of the video in seconds */ vjs.Player.prototype.duration = function(seconds){ if (seconds !== undefined) { // cache the last set value for optimiized scrubbing (esp. Flash) this.cache_.duration = parseFloat(seconds); return this; } if (this.cache_.duration === undefined) { this.onDurationChange(); } return this.cache_.duration || 0; }; // Calculates how much time is left. Not in spec, but useful. vjs.Player.prototype.remainingTime = function(){ return this.duration() - this.currentTime(); }; // http://dev.w3.org/html5/spec/video.html#dom-media-buffered // Buffered returns a timerange object. // Kind of like an array of portions of the video that have been downloaded. // So far no browsers return more than one range (portion) /** * Get a TimeRange object with the times of the video that have been downloaded * * If you just want the percent of the video that's been downloaded, * use bufferedPercent. * * // Number of different ranges of time have been buffered. Usually 1. * numberOfRanges = bufferedTimeRange.length, * * // Time in seconds when the first range starts. Usually 0. * firstRangeStart = bufferedTimeRange.start(0), * * // Time in seconds when the first range ends * firstRangeEnd = bufferedTimeRange.end(0), * * // Length in seconds of the first time range * firstRangeLength = firstRangeEnd - firstRangeStart; * * @return {Object} A mock TimeRange object (following HTML spec) */ vjs.Player.prototype.buffered = function(){ var buffered = this.techGet('buffered'), start = 0, buflast = buffered.length - 1, // Default end to 0 and store in values end = this.cache_.bufferEnd = this.cache_.bufferEnd || 0; if (buffered && buflast >= 0 && buffered.end(buflast) !== end) { end = buffered.end(buflast); // Storing values allows them be overridden by setBufferedFromProgress this.cache_.bufferEnd = end; } return vjs.createTimeRange(start, end); }; /** * Get the percent (as a decimal) of the video that's been downloaded * * var howMuchIsDownloaded = myPlayer.bufferedPercent(); * * 0 means none, 1 means all. * (This method isn't in the HTML5 spec, but it's very convenient) * * @return {Number} A decimal between 0 and 1 representing the percent */ vjs.Player.prototype.bufferedPercent = function(){ return (this.duration()) ? this.buffered().end(0) / this.duration() : 0; }; /** * Get or set the current volume of the media * * // get * var howLoudIsIt = myPlayer.volume(); * * // set * myPlayer.volume(0.5); // Set volume to half * * 0 is off (muted), 1.0 is all the way up, 0.5 is half way. * * @param {Number} percentAsDecimal The new volume as a decimal percent * @return {Number} The current volume, when getting * @return {vjs.Player} self, when setting */ vjs.Player.prototype.volume = function(percentAsDecimal){ var vol; if (percentAsDecimal !== undefined) { vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); // Force value to between 0 and 1 this.cache_.volume = vol; this.techCall('setVolume', vol); vjs.setLocalStorage('volume', vol); return this; } // Default to 1 when returning current volume. vol = parseFloat(this.techGet('volume')); return (isNaN(vol)) ? 1 : vol; }; /** * Get the current muted state, or turn mute on or off * * // get * var isVolumeMuted = myPlayer.muted(); * * // set * myPlayer.muted(true); // mute the volume * * @param {Boolean=} muted True to mute, false to unmute * @return {Boolean} True if mute is on, false if not, when getting * @return {vjs.Player} self, when setting mute */ vjs.Player.prototype.muted = function(muted){ if (muted !== undefined) { this.techCall('setMuted', muted); return this; } return this.techGet('muted') || false; // Default to false }; // Check if current tech can support native fullscreen // (e.g. with built in controls lik iOS, so not our flash swf) vjs.Player.prototype.supportsFullScreen = function(){ return this.techGet('supportsFullScreen') || false; }; /** * is the player in fullscreen * @type {Boolean} * @private */ vjs.Player.prototype.isFullScreen_ = false; /** * Check if the player is in fullscreen mode * * // get * var fullscreenOrNot = myPlayer.isFullScreen(); * * // set * myPlayer.isFullScreen(true); // tell the player it's in fullscreen * * NOTE: As of the latest HTML5 spec, isFullScreen is no longer an official * property and instead document.fullscreenElement is used. But isFullScreen is * still a valuable property for internal player workings. * * @param {Boolean=} isFS Update the player's fullscreen state * @return {Boolean} true if fullscreen, false if not * @return {vjs.Player} self, when setting */ vjs.Player.prototype.isFullScreen = function(isFS){ if (isFS !== undefined) { this.isFullScreen_ = isFS; return this; } return this.isFullScreen_; }; /** * Increase the size of the video to full screen * * myPlayer.requestFullScreen(); * * In some browsers, full screen is not supported natively, so it enters * "full window mode", where the video fills the browser window. * In browsers and devices that support native full screen, sometimes the * browser's default controls will be shown, and not the Video.js custom skin. * This includes most mobile devices (iOS, Android) and older versions of * Safari. * * @return {vjs.Player} self */ vjs.Player.prototype.requestFullScreen = function(){ var requestFullScreen = vjs.support.requestFullScreen; this.isFullScreen(true); if (requestFullScreen) { // the browser supports going fullscreen at the element level so we can // take the controls fullscreen as well as the video // Trigger fullscreenchange event after change // We have to specifically add this each time, and remove // when cancelling fullscreen. Otherwise if there's multiple // players on a page, they would all be reacting to the same fullscreen // events vjs.on(document, requestFullScreen.eventName, vjs.bind(this, function(e){ this.isFullScreen(document[requestFullScreen.isFullScreen]); // If cancelling fullscreen, remove event listener. if (this.isFullScreen() === false) { vjs.off(document, requestFullScreen.eventName, arguments.callee); } this.trigger('fullscreenchange'); })); this.el_[requestFullScreen.requestFn](); } else if (this.tech.supportsFullScreen()) { // we can't take the video.js controls fullscreen but we can go fullscreen // with native controls this.techCall('enterFullScreen'); } else { // fullscreen isn't supported so we'll just stretch the video element to // fill the viewport this.enterFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * Return the video to its normal size after having been in full screen mode * * myPlayer.cancelFullScreen(); * * @return {vjs.Player} self */ vjs.Player.prototype.cancelFullScreen = function(){ var requestFullScreen = vjs.support.requestFullScreen; this.isFullScreen(false); // Check for browser element fullscreen support if (requestFullScreen) { document[requestFullScreen.cancelFn](); } else if (this.tech.supportsFullScreen()) { this.techCall('exitFullScreen'); } else { this.exitFullWindow(); this.trigger('fullscreenchange'); } return this; }; // When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us. vjs.Player.prototype.enterFullWindow = function(){ this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off this.docOrigOverflow = document.documentElement.style.overflow; // Add listener for esc key to exit fullscreen vjs.on(document, 'keydown', vjs.bind(this, this.fullWindowOnEscKey)); // Hide any scroll bars document.documentElement.style.overflow = 'hidden'; // Apply fullscreen styles vjs.addClass(document.body, 'vjs-full-window'); this.trigger('enterFullWindow'); }; vjs.Player.prototype.fullWindowOnEscKey = function(event){ if (event.keyCode === 27) { if (this.isFullScreen() === true) { this.cancelFullScreen(); } else { this.exitFullWindow(); } } }; vjs.Player.prototype.exitFullWindow = function(){ this.isFullWindow = false; vjs.off(document, 'keydown', this.fullWindowOnEscKey); // Unhide scroll bars. document.documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles vjs.removeClass(document.body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes // this.positionAll(); this.trigger('exitFullWindow'); }; vjs.Player.prototype.selectSource = function(sources){ // Loop through each playback technology in the options order for (var i=0,j=this.options_['techOrder'];i<j.length;i++) { var techName = vjs.capitalize(j[i]), tech = window['videojs'][techName]; // Check if the browser supports this technology if (tech.isSupported()) { // Loop through each source object for (var a=0,b=sources;a<b.length;a++) { var source = b[a]; // Check if source can be played with this technology if (tech['canPlaySource'](source)) { return { source: source, tech: techName }; } } } } return false; }; /** * The source function updates the video source * * There are three types of variables you can pass as the argument. * * **URL String**: A URL to the the video file. Use this method if you are sure * the current playback technology (HTML5/Flash) can support the source you * provide. Currently only MP4 files can be used in both HTML5 and Flash. * * myPlayer.src("http://www.example.com/path/to/video.mp4"); * * **Source Object (or element):** A javascript object containing information * about the source file. Use this method if you want the player to determine if * it can support the file using the type information. * * myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }); * * **Array of Source Objects:** To provide multiple versions of the source so * that it can be played using HTML5 across browsers you can use an array of * source objects. Video.js will detect which version is supported and load that * file. * * myPlayer.src([ * { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }, * { type: "video/webm", src: "http://www.example.com/path/to/video.webm" }, * { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" } * ]); * * @param {String|Object|Array=} source The source URL, object, or array of sources * @return {vjs.Player} self */ vjs.Player.prototype.src = function(source){ // Case: Array of source objects to choose from and pick the best to play if (source instanceof Array) { var sourceTech = this.selectSource(source), techName; if (sourceTech) { source = sourceTech.source; techName = sourceTech.tech; // If this technology is already loaded, set source if (techName == this.techName) { this.src(source); // Passing the source object // Otherwise load this technology with chosen source } else { this.loadTech(techName, source); } } else { this.el_.appendChild(vjs.createEl('p', { innerHTML: this.options()['notSupportedMessage'] })); } // Case: Source object { src: '', type: '' ... } } else if (source instanceof Object) { if (window['videojs'][this.techName]['canPlaySource'](source)) { this.src(source.src); } else { // Send through tech loop to check for a compatible technology. this.src([source]); } // Case: URL String (http://myvideo...) } else { // Cache for getting last set source this.cache_.src = source; if (!this.isReady_) { this.ready(function(){ this.src(source); }); } else { this.techCall('src', source); if (this.options_['preload'] == 'auto') { this.load(); } if (this.options_['autoplay']) { this.play(); } } } return this; }; // Begin loading the src data // http://dev.w3.org/html5/spec/video.html#dom-media-load vjs.Player.prototype.load = function(){ this.techCall('load'); return this; }; // http://dev.w3.org/html5/spec/video.html#dom-media-currentsrc vjs.Player.prototype.currentSrc = function(){ return this.techGet('currentSrc') || this.cache_.src || ''; }; // Attributes/Options vjs.Player.prototype.preload = function(value){ if (value !== undefined) { this.techCall('setPreload', value); this.options_['preload'] = value; return this; } return this.techGet('preload'); }; vjs.Player.prototype.autoplay = function(value){ if (value !== undefined) { this.techCall('setAutoplay', value); this.options_['autoplay'] = value; return this; } return this.techGet('autoplay', value); }; vjs.Player.prototype.loop = function(value){ if (value !== undefined) { this.techCall('setLoop', value); this.options_['loop'] = value; return this; } return this.techGet('loop'); }; /** * the url of the poster image source * @type {String} * @private */ vjs.Player.prototype.poster_; /** * get or set the poster image source url * * ##### EXAMPLE: * * // getting * var currentPoster = myPlayer.poster(); * * // setting * myPlayer.poster('http://example.com/myImage.jpg'); * * @param {String=} [src] Poster image source URL * @return {String} poster URL when getting * @return {vjs.Player} self when setting */ vjs.Player.prototype.poster = function(src){ if (src === undefined) { return this.poster_; } // update the internal poster variable this.poster_ = src; // update the tech's poster this.techCall('setPoster', src); // alert components that the poster has been set this.trigger('posterchange'); }; /** * Whether or not the controls are showing * @type {Boolean} * @private */ vjs.Player.prototype.controls_; /** * Get or set whether or not the controls are showing. * @param {Boolean} controls Set controls to showing or not * @return {Boolean} Controls are showing */ vjs.Player.prototype.controls = function(bool){ if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.controls_ !== bool) { this.controls_ = bool; if (bool) { this.removeClass('vjs-controls-disabled'); this.addClass('vjs-controls-enabled'); this.trigger('controlsenabled'); } else { this.removeClass('vjs-controls-enabled'); this.addClass('vjs-controls-disabled'); this.trigger('controlsdisabled'); } } return this; } return this.controls_; }; vjs.Player.prototype.usingNativeControls_; /** * Toggle native controls on/off. Native controls are the controls built into * devices (e.g. default iPhone controls), Flash, or other techs * (e.g. Vimeo Controls) * * **This should only be set by the current tech, because only the tech knows * if it can support native controls** * * @param {Boolean} bool True signals that native controls are on * @return {vjs.Player} Returns the player * @private */ vjs.Player.prototype.usingNativeControls = function(bool){ if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.usingNativeControls_ !== bool) { this.usingNativeControls_ = bool; if (bool) { this.addClass('vjs-using-native-controls'); /** * player is using the native device controls * * @event usingnativecontrols * @memberof vjs.Player * @instance * @private */ this.trigger('usingnativecontrols'); } else { this.removeClass('vjs-using-native-controls'); /** * player is using the custom HTML controls * * @event usingcustomcontrols * @memberof vjs.Player * @instance * @private */ this.trigger('usingcustomcontrols'); } } return this; } return this.usingNativeControls_; }; vjs.Player.prototype.error = function(){ return this.techGet('error'); }; vjs.Player.prototype.ended = function(){ return this.techGet('ended'); }; vjs.Player.prototype.seeking = function(){ return this.techGet('seeking'); }; // When the player is first initialized, trigger activity so components // like the control bar show themselves if needed vjs.Player.prototype.userActivity_ = true; vjs.Player.prototype.reportUserActivity = function(event){ this.userActivity_ = true; }; vjs.Player.prototype.userActive_ = true; vjs.Player.prototype.userActive = function(bool){ if (bool !== undefined) { bool = !!bool; if (bool !== this.userActive_) { this.userActive_ = bool; if (bool) { // If the user was inactive and is now active we want to reset the // inactivity timer this.userActivity_ = true; this.removeClass('vjs-user-inactive'); this.addClass('vjs-user-active'); this.trigger('useractive'); } else { // We're switching the state to inactive manually, so erase any other // activity this.userActivity_ = false; // Chrome/Safari/IE have bugs where when you change the cursor it can // trigger a mousemove event. This causes an issue when you're hiding // the cursor when the user is inactive, and a mousemove signals user // activity. Making it impossible to go into inactive mode. Specifically // this happens in fullscreen when we really need to hide the cursor. // // When this gets resolved in ALL browsers it can be removed // https://code.google.com/p/chromium/issues/detail?id=103041 this.tech.one('mousemove', function(e){ e.stopPropagation(); e.preventDefault(); }); this.removeClass('vjs-user-active'); this.addClass('vjs-user-inactive'); this.trigger('userinactive'); } } return this; } return this.userActive_; }; vjs.Player.prototype.listenForUserActivity = function(){ var onMouseActivity, onMouseDown, mouseInProgress, onMouseUp, activityCheck, inactivityTimeout; onMouseActivity = vjs.bind(this, this.reportUserActivity); onMouseDown = function() { onMouseActivity(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time // as the activityCheck interval (250) should ensure we never miss the // next activityCheck mouseInProgress = setInterval(onMouseActivity, 250); }; onMouseUp = function(event) { onMouseActivity(); // Stop the interval that maintains activity if the mouse/touch is down clearInterval(mouseInProgress); }; // Any mouse movement will be considered user activity this.on('mousedown', onMouseDown); this.on('mousemove', onMouseActivity); this.on('mouseup', onMouseUp); // Listen for keyboard navigation // Shouldn't need to use inProgress interval because of key repeat this.on('keydown', onMouseActivity); this.on('keyup', onMouseActivity); // Run an interval every 250 milliseconds instead of stuffing everything into // the mousemove/touchmove function itself, to prevent performance degradation. // `this.reportUserActivity` simply sets this.userActivity_ to true, which // then gets picked up by this loop // http://ejohn.org/blog/learning-from-twitter/ activityCheck = setInterval(vjs.bind(this, function() { // Check to see if mouse/touch activity has happened if (this.userActivity_) { // Reset the activity tracker this.userActivity_ = false; // If the user state was inactive, set the state to active this.userActive(true); // Clear any existing inactivity timeout to start the timer over clearTimeout(inactivityTimeout); // In X seconds, if no more activity has occurred the user will be // considered inactive inactivityTimeout = setTimeout(vjs.bind(this, function() { // Protect against the case where the inactivityTimeout can trigger just // before the next user activity is picked up by the activityCheck loop // causing a flicker if (!this.userActivity_) { this.userActive(false); } }), 2000); } }), 250); // Clean up the intervals when we kill the player this.on('dispose', function(){ clearInterval(activityCheck); clearTimeout(inactivityTimeout); }); }; // Methods to add support for // networkState: function(){ return this.techCall('networkState'); }, // readyState: function(){ return this.techCall('readyState'); }, // initialTime: function(){ return this.techCall('initialTime'); }, // startOffsetTime: function(){ return this.techCall('startOffsetTime'); }, // played: function(){ return this.techCall('played'); }, // seekable: function(){ return this.techCall('seekable'); }, // videoTracks: function(){ return this.techCall('videoTracks'); }, // audioTracks: function(){ return this.techCall('audioTracks'); }, // videoWidth: function(){ return this.techCall('videoWidth'); }, // videoHeight: function(){ return this.techCall('videoHeight'); }, // defaultPlaybackRate: function(){ return this.techCall('defaultPlaybackRate'); }, // playbackRate: function(){ return this.techCall('playbackRate'); }, // mediaGroup: function(){ return this.techCall('mediaGroup'); }, // controller: function(){ return this.techCall('controller'); }, // defaultMuted: function(){ return this.techCall('defaultMuted'); } // TODO // currentSrcList: the array of sources including other formats and bitrates // playList: array of source lists in order of playback // RequestFullscreen API (function(){ var prefix, requestFS, div; div = document.createElement('div'); requestFS = {}; // Current W3C Spec // http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html#api // Mozilla Draft: https://wiki.mozilla.org/Gecko:FullScreenAPI#fullscreenchange_event // New: https://dvcs.w3.org/hg/fullscreen/raw-file/529a67b8d9f3/Overview.html if (div.cancelFullscreen !== undefined) { requestFS.requestFn = 'requestFullscreen'; requestFS.cancelFn = 'exitFullscreen'; requestFS.eventName = 'fullscreenchange'; requestFS.isFullScreen = 'fullScreen'; // Webkit (Chrome/Safari) and Mozilla (Firefox) have working implementations // that use prefixes and vary slightly from the new W3C spec. Specifically, // using 'exit' instead of 'cancel', and lowercasing the 'S' in Fullscreen. // Other browsers don't have any hints of which version they might follow yet, // so not going to try to predict by looping through all prefixes. } else { if (document.mozCancelFullScreen) { prefix = 'moz'; requestFS.isFullScreen = prefix + 'FullScreen'; } else { prefix = 'webkit'; requestFS.isFullScreen = prefix + 'IsFullScreen'; } if (div[prefix + 'RequestFullScreen']) { requestFS.requestFn = prefix + 'RequestFullScreen'; requestFS.cancelFn = prefix + 'CancelFullScreen'; } requestFS.eventName = prefix + 'fullscreenchange'; } if (document[requestFS.cancelFn]) { vjs.support.requestFullScreen = requestFS; } })(); /** * Container of main controls * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor * @extends vjs.Component */ vjs.ControlBar = vjs.Component.extend(); vjs.ControlBar.prototype.options_ = { loadEvent: 'play', children: { 'playToggle': {}, 'currentTimeDisplay': {}, 'timeDivider': {}, 'durationDisplay': {}, 'remainingTimeDisplay': {}, 'progressControl': {}, 'fullscreenToggle': {}, 'volumeControl': {}, 'muteToggle': {} // 'volumeMenuButton': {} } }; vjs.ControlBar.prototype.createEl = function(){ return vjs.createEl('div', { className: 'vjs-control-bar' }); }; /** * Button to toggle between play and pause * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.PlayToggle = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); player.on('play', vjs.bind(this, this.onPlay)); player.on('pause', vjs.bind(this, this.onPause)); } }); vjs.PlayToggle.prototype.buttonText = 'Play'; vjs.PlayToggle.prototype.buildCSSClass = function(){ return 'vjs-play-control ' + vjs.Button.prototype.buildCSSClass.call(this); }; // OnClick - Toggle between play and pause vjs.PlayToggle.prototype.onClick = function(){ if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; // OnPlay - Add the vjs-playing class to the element so it can change appearance vjs.PlayToggle.prototype.onPlay = function(){ vjs.removeClass(this.el_, 'vjs-paused'); vjs.addClass(this.el_, 'vjs-playing'); this.el_.children[0].children[0].innerHTML = 'Pause'; // change the button text to "Pause" }; // OnPause - Add the vjs-paused class to the element so it can change appearance vjs.PlayToggle.prototype.onPause = function(){ vjs.removeClass(this.el_, 'vjs-playing'); vjs.addClass(this.el_, 'vjs-paused'); this.el_.children[0].children[0].innerHTML = 'Play'; // change the button text to "Play" }; /** * Displays the current time * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.CurrentTimeDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); player.on('timeupdate', vjs.bind(this, this.updateContent)); } }); vjs.CurrentTimeDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-current-time vjs-time-controls vjs-control' }); this.contentEl_ = vjs.createEl('div', { className: 'vjs-current-time-display', innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00', // label the current time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; vjs.CurrentTimeDisplay.prototype.updateContent = function(){ // Allows for smooth scrubbing, when player can't keep up. var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); this.contentEl_.innerHTML = '<span class="vjs-control-text">Current Time </span>' + vjs.formatTime(time, this.player_.duration()); }; /** * Displays the duration * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.DurationDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // this might need to be changed to 'durationchange' instead of 'timeupdate' eventually, // however the durationchange event fires before this.player_.duration() is set, // so the value cannot be written out using this method. // Once the order of durationchange and this.player_.duration() being set is figured out, // this can be updated. player.on('timeupdate', vjs.bind(this, this.updateContent)); } }); vjs.DurationDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-duration vjs-time-controls vjs-control' }); this.contentEl_ = vjs.createEl('div', { className: 'vjs-duration-display', innerHTML: '<span class="vjs-control-text">Duration Time </span>' + '0:00', // label the duration time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; vjs.DurationDisplay.prototype.updateContent = function(){ var duration = this.player_.duration(); if (duration) { this.contentEl_.innerHTML = '<span class="vjs-control-text">Duration Time </span>' + vjs.formatTime(duration); // label the duration time for screen reader users } }; /** * The separator between the current time and duration * * Can be hidden if it's not needed in the design. * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.TimeDivider = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.TimeDivider.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-divider', innerHTML: '<div><span>/</span></div>' }); }; /** * Displays the time left in the video * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.RemainingTimeDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); player.on('timeupdate', vjs.bind(this, this.updateContent)); } }); vjs.RemainingTimeDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-remaining-time vjs-time-controls vjs-control' }); this.contentEl_ = vjs.createEl('div', { className: 'vjs-remaining-time-display', innerHTML: '<span class="vjs-control-text">Remaining Time </span>' + '-0:00', // label the remaining time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; vjs.RemainingTimeDisplay.prototype.updateContent = function(){ if (this.player_.duration()) { this.contentEl_.innerHTML = '<span class="vjs-control-text">Remaining Time </span>' + '-'+ vjs.formatTime(this.player_.remainingTime()); } // Allows for smooth scrubbing, when player can't keep up. // var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); // this.contentEl_.innerHTML = vjs.formatTime(time, this.player_.duration()); }; /** * Toggle fullscreen video * @param {vjs.Player|Object} player * @param {Object=} options * @class * @extends vjs.Button */ vjs.FullscreenToggle = vjs.Button.extend({ /** * @constructor * @memberof vjs.FullscreenToggle * @instance */ init: function(player, options){ vjs.Button.call(this, player, options); } }); vjs.FullscreenToggle.prototype.buttonText = 'Fullscreen'; vjs.FullscreenToggle.prototype.buildCSSClass = function(){ return 'vjs-fullscreen-control ' + vjs.Button.prototype.buildCSSClass.call(this); }; vjs.FullscreenToggle.prototype.onClick = function(){ if (!this.player_.isFullScreen()) { this.player_.requestFullScreen(); this.el_.children[0].children[0].innerHTML = 'Non-Fullscreen'; // change the button text to "Non-Fullscreen" } else { this.player_.cancelFullScreen(); this.el_.children[0].children[0].innerHTML = 'Fullscreen'; // change the button to "Fullscreen" } }; /** * The Progress Control component contains the seek bar, load progress, * and play progress * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.ProgressControl = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.ProgressControl.prototype.options_ = { children: { 'seekBar': {} } }; vjs.ProgressControl.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-progress-control vjs-control' }); }; /** * Seek Bar and holder for the progress bars * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.SeekBar = vjs.Slider.extend({ /** @constructor */ init: function(player, options){ vjs.Slider.call(this, player, options); player.on('timeupdate', vjs.bind(this, this.updateARIAAttributes)); player.ready(vjs.bind(this, this.updateARIAAttributes)); } }); vjs.SeekBar.prototype.options_ = { children: { 'loadProgressBar': {}, 'playProgressBar': {}, 'seekHandle': {} }, 'barName': 'playProgressBar', 'handleName': 'seekHandle' }; vjs.SeekBar.prototype.playerEvent = 'timeupdate'; vjs.SeekBar.prototype.createEl = function(){ return vjs.Slider.prototype.createEl.call(this, 'div', { className: 'vjs-progress-holder', 'aria-label': 'video progress bar' }); }; vjs.SeekBar.prototype.updateARIAAttributes = function(){ // Allows for smooth scrubbing, when player can't keep up. var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('aria-valuenow',vjs.round(this.getPercent()*100, 2)); // machine readable value of progress bar (percentage complete) this.el_.setAttribute('aria-valuetext',vjs.formatTime(time, this.player_.duration())); // human readable value of progress bar (time complete) }; vjs.SeekBar.prototype.getPercent = function(){ return this.player_.currentTime() / this.player_.duration(); }; vjs.SeekBar.prototype.onMouseDown = function(event){ vjs.Slider.prototype.onMouseDown.call(this, event); this.player_.scrubbing = true; this.videoWasPlaying = !this.player_.paused(); this.player_.pause(); }; vjs.SeekBar.prototype.onMouseMove = function(event){ var newTime = this.calculateDistance(event) * this.player_.duration(); // Don't let video end while scrubbing. if (newTime == this.player_.duration()) { newTime = newTime - 0.1; } // Set new time (tell player to seek to new time) this.player_.currentTime(newTime); }; vjs.SeekBar.prototype.onMouseUp = function(event){ vjs.Slider.prototype.onMouseUp.call(this, event); this.player_.scrubbing = false; if (this.videoWasPlaying) { this.player_.play(); } }; vjs.SeekBar.prototype.stepForward = function(){ this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users }; vjs.SeekBar.prototype.stepBack = function(){ this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users }; /** * Shows load progress * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.LoadProgressBar = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); player.on('progress', vjs.bind(this, this.update)); } }); vjs.LoadProgressBar.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-load-progress', innerHTML: '<span class="vjs-control-text">Loaded: 0%</span>' }); }; vjs.LoadProgressBar.prototype.update = function(){ if (this.el_.style) { this.el_.style.width = vjs.round(this.player_.bufferedPercent() * 100, 2) + '%'; } }; /** * Shows play progress * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.PlayProgressBar = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.PlayProgressBar.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-play-progress', innerHTML: '<span class="vjs-control-text">Progress: 0%</span>' }); }; /** * The Seek Handle shows the current position of the playhead during playback, * and can be dragged to adjust the playhead. * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.SeekHandle = vjs.SliderHandle.extend({ init: function(player, options) { vjs.SliderHandle.call(this, player, options); player.on('timeupdate', vjs.bind(this, this.updateContent)); } }); /** * The default value for the handle content, which may be read by screen readers * * @type {String} * @private */ vjs.SeekHandle.prototype.defaultValue = '00:00'; /** @inheritDoc */ vjs.SeekHandle.prototype.createEl = function() { return vjs.SliderHandle.prototype.createEl.call(this, 'div', { className: 'vjs-seek-handle', 'aria-live': 'off' }); }; vjs.SeekHandle.prototype.updateContent = function() { var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.innerHTML = '<span class="vjs-control-text">' + vjs.formatTime(time, this.player_.duration()) + '</span>'; }; /** * The component for controlling the volume level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeControl = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // hide volume controls when they're not supported by the current tech if (player.tech && player.tech.features && player.tech.features['volumeControl'] === false) { this.addClass('vjs-hidden'); } player.on('loadstart', vjs.bind(this, function(){ if (player.tech.features && player.tech.features['volumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } })); } }); vjs.VolumeControl.prototype.options_ = { children: { 'volumeBar': {} } }; vjs.VolumeControl.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-control vjs-control' }); }; /** * The bar that contains the volume level and can be clicked on to adjust the level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeBar = vjs.Slider.extend({ /** @constructor */ init: function(player, options){ vjs.Slider.call(this, player, options); player.on('volumechange', vjs.bind(this, this.updateARIAAttributes)); player.ready(vjs.bind(this, this.updateARIAAttributes)); setTimeout(vjs.bind(this, this.update), 0); // update when elements is in DOM } }); vjs.VolumeBar.prototype.updateARIAAttributes = function(){ // Current value of volume bar as a percentage this.el_.setAttribute('aria-valuenow',vjs.round(this.player_.volume()*100, 2)); this.el_.setAttribute('aria-valuetext',vjs.round(this.player_.volume()*100, 2)+'%'); }; vjs.VolumeBar.prototype.options_ = { children: { 'volumeLevel': {}, 'volumeHandle': {} }, 'barName': 'volumeLevel', 'handleName': 'volumeHandle' }; vjs.VolumeBar.prototype.playerEvent = 'volumechange'; vjs.VolumeBar.prototype.createEl = function(){ return vjs.Slider.prototype.createEl.call(this, 'div', { className: 'vjs-volume-bar', 'aria-label': 'volume level' }); }; vjs.VolumeBar.prototype.onMouseMove = function(event) { if (this.player_.muted()) { this.player_.muted(false); } this.player_.volume(this.calculateDistance(event)); }; vjs.VolumeBar.prototype.getPercent = function(){ if (this.player_.muted()) { return 0; } else { return this.player_.volume(); } }; vjs.VolumeBar.prototype.stepForward = function(){ this.player_.volume(this.player_.volume() + 0.1); }; vjs.VolumeBar.prototype.stepBack = function(){ this.player_.volume(this.player_.volume() - 0.1); }; /** * Shows volume level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeLevel = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.VolumeLevel.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-level', innerHTML: '<span class="vjs-control-text"></span>' }); }; /** * The volume handle can be dragged to adjust the volume level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeHandle = vjs.SliderHandle.extend(); vjs.VolumeHandle.prototype.defaultValue = '00:00'; /** @inheritDoc */ vjs.VolumeHandle.prototype.createEl = function(){ return vjs.SliderHandle.prototype.createEl.call(this, 'div', { className: 'vjs-volume-handle' }); }; /** * A button component for muting the audio * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.MuteToggle = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); player.on('volumechange', vjs.bind(this, this.update)); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech.features && player.tech.features['volumeControl'] === false) { this.addClass('vjs-hidden'); } player.on('loadstart', vjs.bind(this, function(){ if (player.tech.features && player.tech.features['volumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } })); } }); vjs.MuteToggle.prototype.createEl = function(){ return vjs.Button.prototype.createEl.call(this, 'div', { className: 'vjs-mute-control vjs-control', innerHTML: '<div><span class="vjs-control-text">Mute</span></div>' }); }; vjs.MuteToggle.prototype.onClick = function(){ this.player_.muted( this.player_.muted() ? false : true ); }; vjs.MuteToggle.prototype.update = function(){ var vol = this.player_.volume(), level = 3; if (vol === 0 || this.player_.muted()) { level = 0; } else if (vol < 0.33) { level = 1; } else if (vol < 0.67) { level = 2; } // Don't rewrite the button text if the actual text doesn't change. // This causes unnecessary and confusing information for screen reader users. // This check is needed because this function gets called every time the volume level is changed. if(this.player_.muted()){ if(this.el_.children[0].children[0].innerHTML!='Unmute'){ this.el_.children[0].children[0].innerHTML = 'Unmute'; // change the button text to "Unmute" } } else { if(this.el_.children[0].children[0].innerHTML!='Mute'){ this.el_.children[0].children[0].innerHTML = 'Mute'; // change the button text to "Mute" } } /* TODO improve muted icon classes */ for (var i = 0; i < 4; i++) { vjs.removeClass(this.el_, 'vjs-vol-'+i); } vjs.addClass(this.el_, 'vjs-vol-'+level); }; /** * Menu button with a popup for showing the volume slider. * @constructor */ vjs.VolumeMenuButton = vjs.MenuButton.extend({ /** @constructor */ init: function(player, options){ vjs.MenuButton.call(this, player, options); // Same listeners as MuteToggle player.on('volumechange', vjs.bind(this, this.update)); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech.features && player.tech.features.volumeControl === false) { this.addClass('vjs-hidden'); } player.on('loadstart', vjs.bind(this, function(){ if (player.tech.features && player.tech.features.volumeControl === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } })); this.addClass('vjs-menu-button'); } }); vjs.VolumeMenuButton.prototype.createMenu = function(){ var menu = new vjs.Menu(this.player_, { contentElType: 'div' }); var vc = new vjs.VolumeBar(this.player_, vjs.obj.merge({vertical: true}, this.options_.volumeBar)); menu.addChild(vc); return menu; }; vjs.VolumeMenuButton.prototype.onClick = function(){ vjs.MuteToggle.prototype.onClick.call(this); vjs.MenuButton.prototype.onClick.call(this); }; vjs.VolumeMenuButton.prototype.createEl = function(){ return vjs.Button.prototype.createEl.call(this, 'div', { className: 'vjs-volume-menu-button vjs-menu-button vjs-control', innerHTML: '<div><span class="vjs-control-text">Mute</span></div>' }); }; vjs.VolumeMenuButton.prototype.update = vjs.MuteToggle.prototype.update; /* Poster Image ================================================================================ */ /** * The component that handles showing the poster image. * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.PosterImage = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); if (player.poster()) { this.src(player.poster()); } if (!player.poster() || !player.controls()) { this.hide(); } player.on('posterchange', vjs.bind(this, function(){ this.src(player.poster()); })); player.on('play', vjs.bind(this, this.hide)); } }); // use the test el to check for backgroundSize style support var _backgroundSizeSupported = 'backgroundSize' in vjs.TEST_VID.style; vjs.PosterImage.prototype.createEl = function(){ var el = vjs.createEl('div', { className: 'vjs-poster', // Don't want poster to be tabbable. tabIndex: -1 }); if (!_backgroundSizeSupported) { // setup an img element as a fallback for IE8 el.appendChild(vjs.createEl('img')); } return el; }; vjs.PosterImage.prototype.src = function(url){ var el = this.el(); // getter // can't think of a need for a getter here // see #838 if on is needed in the future // still don't want a getter to set src as undefined if (url === undefined) { return; } // setter // To ensure the poster image resizes while maintaining its original aspect // ratio, use a div with `background-size` when available. For browsers that // do not support `background-size` (e.g. IE8), fall back on using a regular // img element. if (_backgroundSizeSupported) { el.style.backgroundImage = 'url("' + url + '")'; } else { el.firstChild.src = url; } }; vjs.PosterImage.prototype.onClick = function(){ // Only accept clicks when controls are enabled if (this.player().controls()) { this.player_.play(); } }; /* Loading Spinner ================================================================================ */ /** * Loading spinner for waiting events * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.LoadingSpinner = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); player.on('canplay', vjs.bind(this, this.hide)); player.on('canplaythrough', vjs.bind(this, this.hide)); player.on('playing', vjs.bind(this, this.hide)); player.on('seeked', vjs.bind(this, this.hide)); player.on('seeking', vjs.bind(this, this.show)); // in some browsers seeking does not trigger the 'playing' event, // so we also need to trap 'seeked' if we are going to set a // 'seeking' event player.on('seeked', vjs.bind(this, this.hide)); player.on('error', vjs.bind(this, this.show)); // Not showing spinner on stalled any more. Browsers may stall and then not trigger any events that would remove the spinner. // Checked in Chrome 16 and Safari 5.1.2. http://help.videojs.com/discussions/problems/883-why-is-the-download-progress-showing // player.on('stalled', vjs.bind(this, this.show)); player.on('waiting', vjs.bind(this, this.show)); } }); vjs.LoadingSpinner.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-loading-spinner' }); }; /* Big Play Button ================================================================================ */ /** * Initial play button. Shows before the video has played. The hiding of the * big play button is done via CSS and player states. * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.BigPlayButton = vjs.Button.extend(); vjs.BigPlayButton.prototype.createEl = function(){ return vjs.Button.prototype.createEl.call(this, 'div', { className: 'vjs-big-play-button', innerHTML: '<span aria-hidden="true"></span>', 'aria-label': 'play video' }); }; vjs.BigPlayButton.prototype.onClick = function(){ this.player_.play(); }; /** * @fileoverview Media Technology Controller - Base class for media playback * technology controllers like Flash and HTML5 */ /** * Base class for media (HTML5 Video, Flash) controllers * @param {vjs.Player|Object} player Central player instance * @param {Object=} options Options object * @constructor */ vjs.MediaTechController = vjs.Component.extend({ /** @constructor */ init: function(player, options, ready){ options = options || {}; // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options.reportTouchActivity = false; vjs.Component.call(this, player, options, ready); this.initControlsListeners(); } }); /** * Set up click and touch listeners for the playback element * On desktops, a click on the video itself will toggle playback, * on a mobile device a click on the video toggles controls. * (toggling controls is done by toggling the user state between active and * inactive) * * A tap can signal that a user has become active, or has become inactive * e.g. a quick tap on an iPhone movie should reveal the controls. Another * quick tap should hide them again (signaling the user is in an inactive * viewing state) * * In addition to this, we still want the user to be considered inactive after * a few seconds of inactivity. * * Note: the only part of iOS interaction we can't mimic with this setup * is a touch and hold on the video element counting as activity in order to * keep the controls showing, but that shouldn't be an issue. A touch and hold on * any controls will still keep the user active */ vjs.MediaTechController.prototype.initControlsListeners = function(){ var player, tech, activateControls, deactivateControls; tech = this; player = this.player(); var activateControls = function(){ if (player.controls() && !player.usingNativeControls()) { tech.addControlsListeners(); } }; deactivateControls = vjs.bind(tech, tech.removeControlsListeners); // Set up event listeners once the tech is ready and has an element to apply // listeners to this.ready(activateControls); player.on('controlsenabled', activateControls); player.on('controlsdisabled', deactivateControls); }; vjs.MediaTechController.prototype.addControlsListeners = function(){ var userWasActive; // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do // trigger mousedown/up. // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object // Any touch events are set to block the mousedown event from happening this.on('mousedown', this.onClick); // If the controls were hidden we don't want that to change without a tap event // so we'll check if the controls were already showing before reporting user // activity this.on('touchstart', function(event) { // Stop the mouse events from also happening event.preventDefault(); userWasActive = this.player_.userActive(); }); this.on('touchmove', function(event) { if (userWasActive){ this.player().reportUserActivity(); } }); // Turn on component tap events this.emitTapEvents(); // The tap listener needs to come after the touchend listener because the tap // listener cancels out any reportedUserActivity when setting userActive(false) this.on('tap', this.onTap); }; /** * Remove the listeners used for click and tap controls. This is needed for * toggling to controls disabled, where a tap/touch should do nothing. */ vjs.MediaTechController.prototype.removeControlsListeners = function(){ // We don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off('tap'); this.off('touchstart'); this.off('touchmove'); this.off('touchleave'); this.off('touchcancel'); this.off('touchend'); this.off('click'); this.off('mousedown'); }; /** * Handle a click on the media element. By default will play/pause the media. */ vjs.MediaTechController.prototype.onClick = function(event){ // We're using mousedown to detect clicks thanks to Flash, but mousedown // will also be triggered with right-clicks, so we need to prevent that if (event.button !== 0) return; // When controls are disabled a click should not toggle playback because // the click is considered a control if (this.player().controls()) { if (this.player().paused()) { this.player().play(); } else { this.player().pause(); } } }; /** * Handle a tap on the media element. By default it will toggle the user * activity state, which hides and shows the controls. */ vjs.MediaTechController.prototype.onTap = function(){ this.player().userActive(!this.player().userActive()); }; vjs.MediaTechController.prototype.features = { 'volumeControl': true, // Resizing plugins using request fullscreen reloads the plugin 'fullscreenResize': false, // Optional events that we can manually mimic with timers // currently not triggered by video-js-swf 'progressEvents': false, 'timeupdateEvents': false }; vjs.media = {}; /** * List of default API methods for any MediaTechController * @type {String} */ vjs.media.ApiMethods = 'play,pause,paused,currentTime,setCurrentTime,duration,buffered,volume,setVolume,muted,setMuted,width,height,supportsFullScreen,enterFullScreen,src,load,currentSrc,preload,setPreload,autoplay,setAutoplay,loop,setLoop,error,networkState,readyState,seeking,initialTime,startOffsetTime,played,seekable,ended,videoTracks,audioTracks,videoWidth,videoHeight,textTracks,defaultPlaybackRate,playbackRate,mediaGroup,controller,controls,defaultMuted'.split(','); // Create placeholder methods for each that warn when a method isn't supported by the current playback technology function createMethod(methodName){ return function(){ throw new Error('The "'+methodName+'" method is not available on the playback technology\'s API'); }; } for (var i = vjs.media.ApiMethods.length - 1; i >= 0; i--) { var methodName = vjs.media.ApiMethods[i]; vjs.MediaTechController.prototype[vjs.media.ApiMethods[i]] = createMethod(methodName); } /** * @fileoverview HTML5 Media Controller - Wrapper for HTML5 Media API */ /** * HTML5 Media Controller - Wrapper for HTML5 Media API * @param {vjs.Player|Object} player * @param {Object=} options * @param {Function=} ready * @constructor */ vjs.Html5 = vjs.MediaTechController.extend({ /** @constructor */ init: function(player, options, ready){ // volume cannot be changed from 1 on iOS this.features['volumeControl'] = vjs.Html5.canControlVolume(); // In iOS, if you move a video element in the DOM, it breaks video playback. this.features['movingMediaElementInDOM'] = !vjs.IS_IOS; // HTML video is able to automatically resize when going to fullscreen this.features['fullscreenResize'] = true; vjs.MediaTechController.call(this, player, options, ready); this.setupTriggers(); var source = options['source']; // If the element source is already set, we may have missed the loadstart event, and want to trigger it. // We don't want to set the source again and interrupt playback. if (source && this.el_.currentSrc === source.src && this.el_.networkState > 0) { player.trigger('loadstart'); // Otherwise set the source if one was provided. } else if (source) { this.el_.src = source.src; } // Determine if native controls should be used // Our goal should be to get the custom controls on mobile solid everywhere // so we can remove this all together. Right now this will block custom // controls on touch enabled laptops like the Chrome Pixel if (vjs.TOUCH_ENABLED && player.options()['nativeControlsForTouch'] !== false) { this.useNativeControls(); } // Chrome and Safari both have issues with autoplay. // In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work. // In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays) // This fixes both issues. Need to wait for API, so it updates displays correctly player.ready(function(){ if (this.tag && this.options_['autoplay'] && this.paused()) { delete this.tag['poster']; // Chrome Fix. Fixed in Chrome v16. this.play(); } }); this.triggerReady(); } }); vjs.Html5.prototype.dispose = function(){ vjs.MediaTechController.prototype.dispose.call(this); }; vjs.Html5.prototype.createEl = function(){ var player = this.player_, // If possible, reuse original tag for HTML5 playback technology element el = player.tag, newEl, clone; // Check if this browser supports moving the element into the box. // On the iPhone video will break if you move the element, // So we have to create a brand new element. if (!el || this.features['movingMediaElementInDOM'] === false) { // If the original tag is still there, clone and remove it. if (el) { clone = el.cloneNode(false); vjs.Html5.disposeMediaElement(el); el = clone; player.tag = null; } else { el = vjs.createEl('video', { id:player.id() + '_html5_api', className:'vjs-tech' }); } // associate the player with the new tag el['player'] = player; vjs.insertFirst(el, player.el()); } // Update specific tag settings, in case they were overridden var attrs = ['autoplay','preload','loop','muted']; for (var i = attrs.length - 1; i >= 0; i--) { var attr = attrs[i]; if (player.options_[attr] !== null) { el[attr] = player.options_[attr]; } } return el; // jenniisawesome = true; }; // Make video events trigger player events // May seem verbose here, but makes other APIs possible. vjs.Html5.prototype.setupTriggers = function(){ for (var i = vjs.Html5.Events.length - 1; i >= 0; i--) { vjs.on(this.el_, vjs.Html5.Events[i], vjs.bind(this.player_, this.eventHandler)); } }; // Triggers removed using this.off when disposed vjs.Html5.prototype.eventHandler = function(e){ this.trigger(e); // No need for media events to bubble up. e.stopPropagation(); }; vjs.Html5.prototype.useNativeControls = function(){ var tech, player, controlsOn, controlsOff, cleanUp; tech = this; player = this.player(); // If the player controls are enabled turn on the native controls tech.setControls(player.controls()); // Update the native controls when player controls state is updated controlsOn = function(){ tech.setControls(true); }; controlsOff = function(){ tech.setControls(false); }; player.on('controlsenabled', controlsOn); player.on('controlsdisabled', controlsOff); // Clean up when not using native controls anymore cleanUp = function(){ player.off('controlsenabled', controlsOn); player.off('controlsdisabled', controlsOff); }; tech.on('dispose', cleanUp); player.on('usingcustomcontrols', cleanUp); // Update the state of the player to using native controls player.usingNativeControls(true); }; vjs.Html5.prototype.play = function(){ this.el_.play(); }; vjs.Html5.prototype.pause = function(){ this.el_.pause(); }; vjs.Html5.prototype.paused = function(){ return this.el_.paused; }; vjs.Html5.prototype.currentTime = function(){ return this.el_.currentTime; }; vjs.Html5.prototype.setCurrentTime = function(seconds){ try { this.el_.currentTime = seconds; } catch(e) { vjs.log(e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady); } }; vjs.Html5.prototype.duration = function(){ return this.el_.duration || 0; }; vjs.Html5.prototype.buffered = function(){ return this.el_.buffered; }; vjs.Html5.prototype.volume = function(){ return this.el_.volume; }; vjs.Html5.prototype.setVolume = function(percentAsDecimal){ this.el_.volume = percentAsDecimal; }; vjs.Html5.prototype.muted = function(){ return this.el_.muted; }; vjs.Html5.prototype.setMuted = function(muted){ this.el_.muted = muted; }; vjs.Html5.prototype.width = function(){ return this.el_.offsetWidth; }; vjs.Html5.prototype.height = function(){ return this.el_.offsetHeight; }; vjs.Html5.prototype.supportsFullScreen = function(){ if (typeof this.el_.webkitEnterFullScreen == 'function') { // Seems to be broken in Chromium/Chrome && Safari in Leopard if (/Android/.test(vjs.USER_AGENT) || !/Chrome|Mac OS X 10.5/.test(vjs.USER_AGENT)) { return true; } } return false; }; vjs.Html5.prototype.enterFullScreen = function(){ var video = this.el_; if (video.paused && video.networkState <= video.HAVE_METADATA) { // attempt to prime the video element for programmatic access // this isn't necessary on the desktop but shouldn't hurt this.el_.play(); // playing and pausing synchronously during the transition to fullscreen // can get iOS ~6.1 devices into a play/pause loop setTimeout(function(){ video.pause(); video.webkitEnterFullScreen(); }, 0); } else { video.webkitEnterFullScreen(); } }; vjs.Html5.prototype.exitFullScreen = function(){ this.el_.webkitExitFullScreen(); }; vjs.Html5.prototype.src = function(src){ this.el_.src = src; }; vjs.Html5.prototype.load = function(){ this.el_.load(); }; vjs.Html5.prototype.currentSrc = function(){ return this.el_.currentSrc; }; vjs.Html5.prototype.poster = function(){ return this.el_.poster; }; vjs.Html5.prototype.setPoster = function(val){ this.el_.poster = val; }; vjs.Html5.prototype.preload = function(){ return this.el_.preload; }; vjs.Html5.prototype.setPreload = function(val){ this.el_.preload = val; }; vjs.Html5.prototype.autoplay = function(){ return this.el_.autoplay; }; vjs.Html5.prototype.setAutoplay = function(val){ this.el_.autoplay = val; }; vjs.Html5.prototype.controls = function(){ return this.el_.controls; } vjs.Html5.prototype.setControls = function(val){ this.el_.controls = !!val; } vjs.Html5.prototype.loop = function(){ return this.el_.loop; }; vjs.Html5.prototype.setLoop = function(val){ this.el_.loop = val; }; vjs.Html5.prototype.error = function(){ return this.el_.error; }; vjs.Html5.prototype.seeking = function(){ return this.el_.seeking; }; vjs.Html5.prototype.ended = function(){ return this.el_.ended; }; vjs.Html5.prototype.defaultMuted = function(){ return this.el_.defaultMuted; }; /* HTML5 Support Testing ---------------------------------------------------- */ vjs.Html5.isSupported = function(){ return !!vjs.TEST_VID.canPlayType; }; vjs.Html5.canPlaySource = function(srcObj){ // IE9 on Windows 7 without MediaPlayer throws an error here // https://github.com/videojs/video.js/issues/519 try { return !!vjs.TEST_VID.canPlayType(srcObj.type); } catch(e) { return ''; } // TODO: Check Type // If no Type, check ext // Check Media Type }; vjs.Html5.canControlVolume = function(){ var volume = vjs.TEST_VID.volume; vjs.TEST_VID.volume = (volume / 2) + 0.1; return volume !== vjs.TEST_VID.volume; }; // List of all HTML5 events (various uses). vjs.Html5.Events = 'loadstart,suspend,abort,error,emptied,stalled,loadedmetadata,loadeddata,canplay,canplaythrough,playing,waiting,seeking,seeked,ended,durationchange,timeupdate,progress,play,pause,ratechange,volumechange'.split(','); vjs.Html5.disposeMediaElement = function(el){ if (!el) { return; } el['player'] = null; if (el.parentNode) { el.parentNode.removeChild(el); } // remove any child track or source nodes to prevent their loading while(el.hasChildNodes()) { el.removeChild(el.firstChild); } // remove any src reference. not setting `src=''` because that causes a warning // in firefox el.removeAttribute('src'); // force the media element to update its loading state by calling load() if (typeof el.load === 'function') { el.load(); } }; // HTML5 Feature detection and Device Fixes --------------------------------- // // Override Android 2.2 and less canPlayType method which is broken if (vjs.IS_OLD_ANDROID) { document.createElement('video').constructor.prototype.canPlayType = function(type){ return (type && type.toLowerCase().indexOf('video/mp4') != -1) ? 'maybe' : ''; }; } /** * @fileoverview VideoJS-SWF - Custom Flash Player with HTML5-ish API * https://github.com/zencoder/video-js-swf * Not using setupTriggers. Using global onEvent func to distribute events */ /** * Flash Media Controller - Wrapper for fallback SWF API * * @param {vjs.Player} player * @param {Object=} options * @param {Function=} ready * @constructor */ vjs.Flash = vjs.MediaTechController.extend({ /** @constructor */ init: function(player, options, ready){ vjs.MediaTechController.call(this, player, options, ready); var source = options['source'], // Which element to embed in parentEl = options['parentEl'], // Create a temporary element to be replaced by swf object placeHolder = this.el_ = vjs.createEl('div', { id: player.id() + '_temp_flash' }), // Generate ID for swf object objId = player.id()+'_flash_api', // Store player options in local var for optimization // TODO: switch to using player methods instead of options // e.g. player.autoplay(); playerOptions = player.options_, // Merge default flashvars with ones passed in to init flashVars = vjs.obj.merge({ // SWF Callback Functions 'readyFunction': 'videojs.Flash.onReady', 'eventProxyFunction': 'videojs.Flash.onEvent', 'errorEventProxyFunction': 'videojs.Flash.onError', // Player Settings 'autoplay': playerOptions.autoplay, 'preload': playerOptions.preload, 'loop': playerOptions.loop, 'muted': playerOptions.muted }, options['flashVars']), // Merge default parames with ones passed in params = vjs.obj.merge({ 'wmode': 'opaque', // Opaque is needed to overlay controls, but can affect playback performance 'bgcolor': '#000000' // Using bgcolor prevents a white flash when the object is loading }, options['params']), // Merge default attributes with ones passed in attributes = vjs.obj.merge({ 'id': objId, 'name': objId, // Both ID and Name needed or swf to identifty itself 'class': 'vjs-tech' }, options['attributes']), lastSeekTarget ; // If source was supplied pass as a flash var. if (source) { if (source.type && vjs.Flash.isStreamingType(source.type)) { var parts = vjs.Flash.streamToParts(source.src); flashVars['rtmpConnection'] = encodeURIComponent(parts.connection); flashVars['rtmpStream'] = encodeURIComponent(parts.stream); } else { flashVars['src'] = encodeURIComponent(vjs.getAbsoluteURL(source.src)); } } this['setCurrentTime'] = function(time){ lastSeekTarget = time; this.el_.vjs_setProperty('currentTime', time); }; this['currentTime'] = function(time){ // when seeking make the reported time keep up with the requested time // by reading the time we're seeking to if (this.seeking()) { return lastSeekTarget; } return this.el_.vjs_getProperty('currentTime'); }; // Add placeholder to player div vjs.insertFirst(placeHolder, parentEl); // Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers // This allows resetting the playhead when we catch the reload if (options['startTime']) { this.ready(function(){ this.load(); this.play(); this.currentTime(options['startTime']); }); } // firefox doesn't bubble mousemove events to parent. videojs/video-js-swf#37 // bugzilla bug: https://bugzilla.mozilla.org/show_bug.cgi?id=836786 if (vjs.IS_FIREFOX) { this.ready(function(){ vjs.on(this.el(), 'mousemove', vjs.bind(this, function(){ // since it's a custom event, don't bubble higher than the player this.player().trigger({ 'type':'mousemove', 'bubbles': false }); })); }); } // Flash iFrame Mode // In web browsers there are multiple instances where changing the parent element or visibility of a plugin causes the plugin to reload. // - Firefox just about always. https://bugzilla.mozilla.org/show_bug.cgi?id=90268 (might be fixed by version 13) // - Webkit when hiding the plugin // - Webkit and Firefox when using requestFullScreen on a parent element // Loading the flash plugin into a dynamically generated iFrame gets around most of these issues. // Issues that remain include hiding the element and requestFullScreen in Firefox specifically // There's on particularly annoying issue with this method which is that Firefox throws a security error on an offsite Flash object loaded into a dynamically created iFrame. // Even though the iframe was inserted into a page on the web, Firefox + Flash considers it a local app trying to access an internet file. // I tried mulitple ways of setting the iframe src attribute but couldn't find a src that worked well. Tried a real/fake source, in/out of domain. // Also tried a method from stackoverflow that caused a security error in all browsers. http://stackoverflow.com/questions/2486901/how-to-set-document-domain-for-a-dynamically-generated-iframe // In the end the solution I found to work was setting the iframe window.location.href right before doing a document.write of the Flash object. // The only downside of this it seems to trigger another http request to the original page (no matter what's put in the href). Not sure why that is. // NOTE (2012-01-29): Cannot get Firefox to load the remote hosted SWF into a dynamically created iFrame // Firefox 9 throws a security error, unleess you call location.href right before doc.write. // Not sure why that even works, but it causes the browser to look like it's continuously trying to load the page. // Firefox 3.6 keeps calling the iframe onload function anytime I write to it, causing an endless loop. if (options['iFrameMode'] === true && !vjs.IS_FIREFOX) { // Create iFrame with vjs-tech class so it's 100% width/height var iFrm = vjs.createEl('iframe', { 'id': objId + '_iframe', 'name': objId + '_iframe', 'className': 'vjs-tech', 'scrolling': 'no', 'marginWidth': 0, 'marginHeight': 0, 'frameBorder': 0 }); // Update ready function names in flash vars for iframe window flashVars['readyFunction'] = 'ready'; flashVars['eventProxyFunction'] = 'events'; flashVars['errorEventProxyFunction'] = 'errors'; // Tried multiple methods to get this to work in all browsers // Tried embedding the flash object in the page first, and then adding a place holder to the iframe, then replacing the placeholder with the page object. // The goal here was to try to load the swf URL in the parent page first and hope that got around the firefox security error // var newObj = vjs.Flash.embed(options['swf'], placeHolder, flashVars, params, attributes); // (in onload) // var temp = vjs.createEl('a', { id:'asdf', innerHTML: 'asdf' } ); // iDoc.body.appendChild(temp); // Tried embedding the flash object through javascript in the iframe source. // This works in webkit but still triggers the firefox security error // iFrm.src = 'javascript: document.write('"+vjs.Flash.getEmbedCode(options['swf'], flashVars, params, attributes)+"');"; // Tried an actual local iframe just to make sure that works, but it kills the easiness of the CDN version if you require the user to host an iframe // We should add an option to host the iframe locally though, because it could help a lot of issues. // iFrm.src = "iframe.html"; // Wait until iFrame has loaded to write into it. vjs.on(iFrm, 'load', vjs.bind(this, function(){ var iDoc, iWin = iFrm.contentWindow; // The one working method I found was to use the iframe's document.write() to create the swf object // This got around the security issue in all browsers except firefox. // I did find a hack where if I call the iframe's window.location.href='', it would get around the security error // However, the main page would look like it was loading indefinitely (URL bar loading spinner would never stop) // Plus Firefox 3.6 didn't work no matter what I tried. // if (vjs.USER_AGENT.match('Firefox')) { // iWin.location.href = ''; // } // Get the iFrame's document depending on what the browser supports iDoc = iFrm.contentDocument ? iFrm.contentDocument : iFrm.contentWindow.document; // Tried ensuring both document domains were the same, but they already were, so that wasn't the issue. // Even tried adding /. that was mentioned in a browser security writeup // document.domain = document.domain+'/.'; // iDoc.domain = document.domain+'/.'; // Tried adding the object to the iframe doc's innerHTML. Security error in all browsers. // iDoc.body.innerHTML = swfObjectHTML; // Tried appending the object to the iframe doc's body. Security error in all browsers. // iDoc.body.appendChild(swfObject); // Using document.write actually got around the security error that browsers were throwing. // Again, it's a dynamically generated (same domain) iframe, loading an external Flash swf. // Not sure why that's a security issue, but apparently it is. iDoc.write(vjs.Flash.getEmbedCode(options['swf'], flashVars, params, attributes)); // Setting variables on the window needs to come after the doc write because otherwise they can get reset in some browsers // So far no issues with swf ready event being called before it's set on the window. iWin['player'] = this.player_; // Create swf ready function for iFrame window iWin['ready'] = vjs.bind(this.player_, function(currSwf){ var el = iDoc.getElementById(currSwf), player = this, tech = player.tech; // Update reference to playback technology element tech.el_ = el; // Make sure swf is actually ready. Sometimes the API isn't actually yet. vjs.Flash.checkReady(tech); }); // Create event listener for all swf events iWin['events'] = vjs.bind(this.player_, function(swfID, eventName){ var player = this; if (player && player.techName === 'flash') { player.trigger(eventName); } }); // Create error listener for all swf errors iWin['errors'] = vjs.bind(this.player_, function(swfID, eventName){ vjs.log('Flash Error', eventName); }); })); // Replace placeholder with iFrame (it will load now) placeHolder.parentNode.replaceChild(iFrm, placeHolder); // If not using iFrame mode, embed as normal object } else { vjs.Flash.embed(options['swf'], placeHolder, flashVars, params, attributes); } } }); vjs.Flash.prototype.dispose = function(){ vjs.MediaTechController.prototype.dispose.call(this); }; vjs.Flash.prototype.play = function(){ this.el_.vjs_play(); }; vjs.Flash.prototype.pause = function(){ this.el_.vjs_pause(); }; vjs.Flash.prototype.src = function(src){ if (vjs.Flash.isStreamingSrc(src)) { src = vjs.Flash.streamToParts(src); this.setRtmpConnection(src.connection); this.setRtmpStream(src.stream); } else { // Make sure source URL is abosolute. src = vjs.getAbsoluteURL(src); this.el_.vjs_src(src); } // Currently the SWF doesn't autoplay if you load a source later. // e.g. Load player w/ no source, wait 2s, set src. if (this.player_.autoplay()) { var tech = this; setTimeout(function(){ tech.play(); }, 0); } }; vjs.Flash.prototype.currentSrc = function(){ var src = this.el_.vjs_getProperty('currentSrc'); // no src, check and see if RTMP if (src == null) { var connection = this.rtmpConnection(), stream = this.rtmpStream(); if (connection && stream) { src = vjs.Flash.streamFromParts(connection, stream); } } return src; }; vjs.Flash.prototype.load = function(){ this.el_.vjs_load(); }; vjs.Flash.prototype.poster = function(){ this.el_.vjs_getProperty('poster'); }; vjs.Flash.prototype.setPoster = function(){ // poster images are not handled by the Flash tech so make this a no-op }; vjs.Flash.prototype.buffered = function(){ return vjs.createTimeRange(0, this.el_.vjs_getProperty('buffered')); }; vjs.Flash.prototype.supportsFullScreen = function(){ return false; // Flash does not allow fullscreen through javascript }; vjs.Flash.prototype.enterFullScreen = function(){ return false; }; // Create setters and getters for attributes var api = vjs.Flash.prototype, readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(','), readOnly = 'error,currentSrc,networkState,readyState,seeking,initialTime,duration,startOffsetTime,paused,played,seekable,ended,videoTracks,audioTracks,videoWidth,videoHeight,textTracks'.split(','); // Overridden: buffered, currentTime /** * @this {*} * @private */ var createSetter = function(attr){ var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1); api['set'+attrUpper] = function(val){ return this.el_.vjs_setProperty(attr, val); }; }; /** * @this {*} * @private */ var createGetter = function(attr){ api[attr] = function(){ return this.el_.vjs_getProperty(attr); }; }; (function(){ var i; // Create getter and setters for all read/write attributes for (i = 0; i < readWrite.length; i++) { createGetter(readWrite[i]); createSetter(readWrite[i]); } // Create getters for read-only attributes for (i = 0; i < readOnly.length; i++) { createGetter(readOnly[i]); } })(); /* Flash Support Testing -------------------------------------------------------- */ vjs.Flash.isSupported = function(){ return vjs.Flash.version()[0] >= 10; // return swfobject.hasFlashPlayerVersion('10'); }; vjs.Flash.canPlaySource = function(srcObj){ var type; if (!srcObj.type) { return ''; } type = srcObj.type.replace(/;.*/,'').toLowerCase(); if (type in vjs.Flash.formats || type in vjs.Flash.streamingFormats) { return 'maybe'; } }; vjs.Flash.formats = { 'video/flv': 'FLV', 'video/x-flv': 'FLV', 'video/mp4': 'MP4', 'video/m4v': 'MP4' }; vjs.Flash.streamingFormats = { 'rtmp/mp4': 'MP4', 'rtmp/flv': 'FLV' }; vjs.Flash['onReady'] = function(currSwf){ var el = vjs.el(currSwf); // Get player from box // On firefox reloads, el might already have a player var player = el['player'] || el.parentNode['player'], tech = player.tech; // Reference player on tech element el['player'] = player; // Update reference to playback technology element tech.el_ = el; vjs.Flash.checkReady(tech); }; // The SWF isn't alwasy ready when it says it is. Sometimes the API functions still need to be added to the object. // If it's not ready, we set a timeout to check again shortly. vjs.Flash.checkReady = function(tech){ // Check if API property exists if (tech.el().vjs_getProperty) { // If so, tell tech it's ready tech.triggerReady(); // Otherwise wait longer. } else { setTimeout(function(){ vjs.Flash.checkReady(tech); }, 50); } }; // Trigger events from the swf on the player vjs.Flash['onEvent'] = function(swfID, eventName){ var player = vjs.el(swfID)['player']; player.trigger(eventName); }; // Log errors from the swf vjs.Flash['onError'] = function(swfID, err){ var player = vjs.el(swfID)['player']; player.trigger('error'); vjs.log('Flash Error', err, swfID); }; // Flash Version Check vjs.Flash.version = function(){ var version = '0,0,0'; // IE try { version = new window.ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; // other browsers } catch(e) { try { if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin){ version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; } } catch(err) {} } return version.split(','); }; // Flash embedding method. Only used in non-iframe mode vjs.Flash.embed = function(swf, placeHolder, flashVars, params, attributes){ var code = vjs.Flash.getEmbedCode(swf, flashVars, params, attributes), // Get element by embedding code and retrieving created element obj = vjs.createEl('div', { innerHTML: code }).childNodes[0], par = placeHolder.parentNode ; placeHolder.parentNode.replaceChild(obj, placeHolder); // IE6 seems to have an issue where it won't initialize the swf object after injecting it. // This is a dumb fix var newObj = par.childNodes[0]; setTimeout(function(){ newObj.style.display = 'block'; }, 1000); return obj; }; vjs.Flash.getEmbedCode = function(swf, flashVars, params, attributes){ var objTag = '<object type="application/x-shockwave-flash"', flashVarsString = '', paramsString = '', attrsString = ''; // Convert flash vars to string if (flashVars) { vjs.obj.each(flashVars, function(key, val){ flashVarsString += (key + '=' + val + '&amp;'); }); } // Add swf, flashVars, and other default params params = vjs.obj.merge({ 'movie': swf, 'flashvars': flashVarsString, 'allowScriptAccess': 'always', // Required to talk to swf 'allowNetworking': 'all' // All should be default, but having security issues. }, params); // Create param tags string vjs.obj.each(params, function(key, val){ paramsString += '<param name="'+key+'" value="'+val+'" />'; }); attributes = vjs.obj.merge({ // Add swf to attributes (need both for IE and Others to work) 'data': swf, // Default to 100% width/height 'width': '100%', 'height': '100%' }, attributes); // Create Attributes string vjs.obj.each(attributes, function(key, val){ attrsString += (key + '="' + val + '" '); }); return objTag + attrsString + '>' + paramsString + '</object>'; }; vjs.Flash.streamFromParts = function(connection, stream) { return connection + '&' + stream; }; vjs.Flash.streamToParts = function(src) { var parts = { connection: '', stream: '' }; if (! src) { return parts; } // Look for the normal URL separator we expect, '&'. // If found, we split the URL into two pieces around the // first '&'. var connEnd = src.indexOf('&'); var streamBegin; if (connEnd !== -1) { streamBegin = connEnd + 1; } else { // If there's not a '&', we use the last '/' as the delimiter. connEnd = streamBegin = src.lastIndexOf('/') + 1; if (connEnd === 0) { // really, there's not a '/'? connEnd = streamBegin = src.length; } } parts.connection = src.substring(0, connEnd); parts.stream = src.substring(streamBegin, src.length); return parts; }; vjs.Flash.isStreamingType = function(srcType) { return srcType in vjs.Flash.streamingFormats; }; // RTMP has four variations, any string starting // with one of these protocols should be valid vjs.Flash.RTMP_RE = /^rtmp[set]?:\/\//i; vjs.Flash.isStreamingSrc = function(src) { return vjs.Flash.RTMP_RE.test(src); }; /** * The Media Loader is the component that decides which playback technology to load * when the player is initialized. * * @constructor */ vjs.MediaLoader = vjs.Component.extend({ /** @constructor */ init: function(player, options, ready){ vjs.Component.call(this, player, options, ready); // If there are no sources when the player is initialized, // load the first supported playback technology. if (!player.options_['sources'] || player.options_['sources'].length === 0) { for (var i=0,j=player.options_['techOrder']; i<j.length; i++) { var techName = vjs.capitalize(j[i]), tech = window['videojs'][techName]; // Check if the browser supports this technology if (tech && tech.isSupported()) { player.loadTech(techName); break; } } } else { // // Loop through playback technologies (HTML5, Flash) and check for support. // // Then load the best source. // // A few assumptions here: // // All playback technologies respect preload false. player.src(player.options_['sources']); } } }); /** * @fileoverview Text Tracks * Text tracks are tracks of timed text events. * Captions - text displayed over the video for the hearing impared * Subtitles - text displayed over the video for those who don't understand langauge in the video * Chapters - text displayed in a menu allowing the user to jump to particular points (chapters) in the video * Descriptions (not supported yet) - audio descriptions that are read back to the user by a screen reading device */ // Player Additions - Functions add to the player object for easier access to tracks /** * List of associated text tracks * @type {Array} * @private */ vjs.Player.prototype.textTracks_; /** * Get an array of associated text tracks. captions, subtitles, chapters, descriptions * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks * @return {Array} Array of track objects * @private */ vjs.Player.prototype.textTracks = function(){ this.textTracks_ = this.textTracks_ || []; return this.textTracks_; }; /** * Add a text track * In addition to the W3C settings we allow adding additional info through options. * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack * @param {String} kind Captions, subtitles, chapters, descriptions, or metadata * @param {String=} label Optional label * @param {String=} language Optional language * @param {Object=} options Additional track options, like src * @private */ vjs.Player.prototype.addTextTrack = function(kind, label, language, options){ var tracks = this.textTracks_ = this.textTracks_ || []; options = options || {}; options['kind'] = kind; options['label'] = label; options['language'] = language; // HTML5 Spec says default to subtitles. // Uppercase first letter to match class names var Kind = vjs.capitalize(kind || 'subtitles'); // Create correct texttrack class. CaptionsTrack, etc. var track = new window['videojs'][Kind + 'Track'](this, options); tracks.push(track); // If track.dflt() is set, start showing immediately // TODO: Add a process to deterime the best track to show for the specific kind // Incase there are mulitple defaulted tracks of the same kind // Or the user has a set preference of a specific language that should override the default // if (track.dflt()) { // this.ready(vjs.bind(track, track.show)); // } return track; }; /** * Add an array of text tracks. captions, subtitles, chapters, descriptions * Track objects will be stored in the player.textTracks() array * @param {Array} trackList Array of track elements or objects (fake track elements) * @private */ vjs.Player.prototype.addTextTracks = function(trackList){ var trackObj; for (var i = 0; i < trackList.length; i++) { trackObj = trackList[i]; this.addTextTrack(trackObj['kind'], trackObj['label'], trackObj['language'], trackObj); } return this; }; // Show a text track // disableSameKind: disable all other tracks of the same kind. Value should be a track kind (captions, etc.) vjs.Player.prototype.showTextTrack = function(id, disableSameKind){ var tracks = this.textTracks_, i = 0, j = tracks.length, track, showTrack, kind; // Find Track with same ID for (;i<j;i++) { track = tracks[i]; if (track.id() === id) { track.show(); showTrack = track; // Disable tracks of the same kind } else if (disableSameKind && track.kind() == disableSameKind && track.mode() > 0) { track.disable(); } } // Get track kind from shown track or disableSameKind kind = (showTrack) ? showTrack.kind() : ((disableSameKind) ? disableSameKind : false); // Trigger trackchange event, captionstrackchange, subtitlestrackchange, etc. if (kind) { this.trigger(kind+'trackchange'); } return this; }; /** * The base class for all text tracks * * Handles the parsing, hiding, and showing of text track cues * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.TextTrack = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // Apply track info to track object // Options will often be a track element // Build ID if one doesn't exist this.id_ = options['id'] || ('vjs_' + options['kind'] + '_' + options['language'] + '_' + vjs.guid++); this.src_ = options['src']; // 'default' is a reserved keyword in js so we use an abbreviated version this.dflt_ = options['default'] || options['dflt']; this.title_ = options['title']; this.language_ = options['srclang']; this.label_ = options['label']; this.cues_ = []; this.activeCues_ = []; this.readyState_ = 0; this.mode_ = 0; this.player_.on('fullscreenchange', vjs.bind(this, this.adjustFontSize)); } }); /** * Track kind value. Captions, subtitles, etc. * @private */ vjs.TextTrack.prototype.kind_; /** * Get the track kind value * @return {String} */ vjs.TextTrack.prototype.kind = function(){ return this.kind_; }; /** * Track src value * @private */ vjs.TextTrack.prototype.src_; /** * Get the track src value * @return {String} */ vjs.TextTrack.prototype.src = function(){ return this.src_; }; /** * Track default value * If default is used, subtitles/captions to start showing * @private */ vjs.TextTrack.prototype.dflt_; /** * Get the track default value. ('default' is a reserved keyword) * @return {Boolean} */ vjs.TextTrack.prototype.dflt = function(){ return this.dflt_; }; /** * Track title value * @private */ vjs.TextTrack.prototype.title_; /** * Get the track title value * @return {String} */ vjs.TextTrack.prototype.title = function(){ return this.title_; }; /** * Language - two letter string to represent track language, e.g. 'en' for English * Spec def: readonly attribute DOMString language; * @private */ vjs.TextTrack.prototype.language_; /** * Get the track language value * @return {String} */ vjs.TextTrack.prototype.language = function(){ return this.language_; }; /** * Track label e.g. 'English' * Spec def: readonly attribute DOMString label; * @private */ vjs.TextTrack.prototype.label_; /** * Get the track label value * @return {String} */ vjs.TextTrack.prototype.label = function(){ return this.label_; }; /** * All cues of the track. Cues have a startTime, endTime, text, and other properties. * Spec def: readonly attribute TextTrackCueList cues; * @private */ vjs.TextTrack.prototype.cues_; /** * Get the track cues * @return {Array} */ vjs.TextTrack.prototype.cues = function(){ return this.cues_; }; /** * ActiveCues is all cues that are currently showing * Spec def: readonly attribute TextTrackCueList activeCues; * @private */ vjs.TextTrack.prototype.activeCues_; /** * Get the track active cues * @return {Array} */ vjs.TextTrack.prototype.activeCues = function(){ return this.activeCues_; }; /** * ReadyState describes if the text file has been loaded * const unsigned short NONE = 0; * const unsigned short LOADING = 1; * const unsigned short LOADED = 2; * const unsigned short ERROR = 3; * readonly attribute unsigned short readyState; * @private */ vjs.TextTrack.prototype.readyState_; /** * Get the track readyState * @return {Number} */ vjs.TextTrack.prototype.readyState = function(){ return this.readyState_; }; /** * Mode describes if the track is showing, hidden, or disabled * const unsigned short OFF = 0; * const unsigned short HIDDEN = 1; (still triggering cuechange events, but not visible) * const unsigned short SHOWING = 2; * attribute unsigned short mode; * @private */ vjs.TextTrack.prototype.mode_; /** * Get the track mode * @return {Number} */ vjs.TextTrack.prototype.mode = function(){ return this.mode_; }; /** * Change the font size of the text track to make it larger when playing in fullscreen mode * and restore it to its normal size when not in fullscreen mode. */ vjs.TextTrack.prototype.adjustFontSize = function(){ if (this.player_.isFullScreen()) { // Scale the font by the same factor as increasing the video width to the full screen window width. // Additionally, multiply that factor by 1.4, which is the default font size for // the caption track (from the CSS) this.el_.style.fontSize = screen.width / this.player_.width() * 1.4 * 100 + '%'; } else { // Change the font size of the text track back to its original non-fullscreen size this.el_.style.fontSize = ''; } }; /** * Create basic div to hold cue text * @return {Element} */ vjs.TextTrack.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-' + this.kind_ + ' vjs-text-track' }); }; /** * Show: Mode Showing (2) * Indicates that the text track is active. If no attempt has yet been made to obtain the track's cues, the user agent will perform such an attempt momentarily. * The user agent is maintaining a list of which cues are active, and events are being fired accordingly. * In addition, for text tracks whose kind is subtitles or captions, the cues are being displayed over the video as appropriate; * for text tracks whose kind is descriptions, the user agent is making the cues available to the user in a non-visual fashion; * and for text tracks whose kind is chapters, the user agent is making available to the user a mechanism by which the user can navigate to any point in the media resource by selecting a cue. * The showing by default state is used in conjunction with the default attribute on track elements to indicate that the text track was enabled due to that attribute. * This allows the user agent to override the state if a later track is discovered that is more appropriate per the user's preferences. */ vjs.TextTrack.prototype.show = function(){ this.activate(); this.mode_ = 2; // Show element. vjs.Component.prototype.show.call(this); }; /** * Hide: Mode Hidden (1) * Indicates that the text track is active, but that the user agent is not actively displaying the cues. * If no attempt has yet been made to obtain the track's cues, the user agent will perform such an attempt momentarily. * The user agent is maintaining a list of which cues are active, and events are being fired accordingly. */ vjs.TextTrack.prototype.hide = function(){ // When hidden, cues are still triggered. Disable to stop triggering. this.activate(); this.mode_ = 1; // Hide element. vjs.Component.prototype.hide.call(this); }; /** * Disable: Mode Off/Disable (0) * Indicates that the text track is not active. Other than for the purposes of exposing the track in the DOM, the user agent is ignoring the text track. * No cues are active, no events are fired, and the user agent will not attempt to obtain the track's cues. */ vjs.TextTrack.prototype.disable = function(){ // If showing, hide. if (this.mode_ == 2) { this.hide(); } // Stop triggering cues this.deactivate(); // Switch Mode to Off this.mode_ = 0; }; /** * Turn on cue tracking. Tracks that are showing OR hidden are active. */ vjs.TextTrack.prototype.activate = function(){ // Load text file if it hasn't been yet. if (this.readyState_ === 0) { this.load(); } // Only activate if not already active. if (this.mode_ === 0) { // Update current cue on timeupdate // Using unique ID for bind function so other tracks don't remove listener this.player_.on('timeupdate', vjs.bind(this, this.update, this.id_)); // Reset cue time on media end this.player_.on('ended', vjs.bind(this, this.reset, this.id_)); // Add to display if (this.kind_ === 'captions' || this.kind_ === 'subtitles') { this.player_.getChild('textTrackDisplay').addChild(this); } } }; /** * Turn off cue tracking. */ vjs.TextTrack.prototype.deactivate = function(){ // Using unique ID for bind function so other tracks don't remove listener this.player_.off('timeupdate', vjs.bind(this, this.update, this.id_)); this.player_.off('ended', vjs.bind(this, this.reset, this.id_)); this.reset(); // Reset // Remove from display this.player_.getChild('textTrackDisplay').removeChild(this); }; // A readiness state // One of the following: // // Not loaded // Indicates that the text track is known to exist (e.g. it has been declared with a track element), but its cues have not been obtained. // // Loading // Indicates that the text track is loading and there have been no fatal errors encountered so far. Further cues might still be added to the track. // // Loaded // Indicates that the text track has been loaded with no fatal errors. No new cues will be added to the track except if the text track corresponds to a MutableTextTrack object. // // Failed to load // Indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in some way (e.g. URL could not be resolved, network error, unknown text track format). Some or all of the cues are likely missing and will not be obtained. vjs.TextTrack.prototype.load = function(){ // Only load if not loaded yet. if (this.readyState_ === 0) { this.readyState_ = 1; vjs.get(this.src_, vjs.bind(this, this.parseCues), vjs.bind(this, this.onError)); } }; vjs.TextTrack.prototype.onError = function(err){ this.error = err; this.readyState_ = 3; this.trigger('error'); }; // Parse the WebVTT text format for cue times. // TODO: Separate parser into own class so alternative timed text formats can be used. (TTML, DFXP) vjs.TextTrack.prototype.parseCues = function(srcContent) { var cue, time, text, lines = srcContent.split('\n'), line = '', id; for (var i=1, j=lines.length; i<j; i++) { // Line 0 should be 'WEBVTT', so skipping i=0 line = vjs.trim(lines[i]); // Trim whitespace and linebreaks if (line) { // Loop until a line with content // First line could be an optional cue ID // Check if line has the time separator if (line.indexOf('-->') == -1) { id = line; // Advance to next line for timing. line = vjs.trim(lines[++i]); } else { id = this.cues_.length; } // First line - Number cue = { id: id, // Cue Number index: this.cues_.length // Position in Array }; // Timing line time = line.split(' --> '); cue.startTime = this.parseCueTime(time[0]); cue.endTime = this.parseCueTime(time[1]); // Additional lines - Cue Text text = []; // Loop until a blank line or end of lines // Assumeing trim('') returns false for blank lines while (lines[++i] && (line = vjs.trim(lines[i]))) { text.push(line); } cue.text = text.join('<br/>'); // Add this cue this.cues_.push(cue); } } this.readyState_ = 2; this.trigger('loaded'); }; vjs.TextTrack.prototype.parseCueTime = function(timeText) { var parts = timeText.split(':'), time = 0, hours, minutes, other, seconds, ms; // Check if optional hours place is included // 00:00:00.000 vs. 00:00.000 if (parts.length == 3) { hours = parts[0]; minutes = parts[1]; other = parts[2]; } else { hours = 0; minutes = parts[0]; other = parts[1]; } // Break other (seconds, milliseconds, and flags) by spaces // TODO: Make additional cue layout settings work with flags other = other.split(/\s+/); // Remove seconds. Seconds is the first part before any spaces. seconds = other.splice(0,1)[0]; // Could use either . or , for decimal seconds = seconds.split(/\.|,/); // Get milliseconds ms = parseFloat(seconds[1]); seconds = seconds[0]; // hours => seconds time += parseFloat(hours) * 3600; // minutes => seconds time += parseFloat(minutes) * 60; // Add seconds time += parseFloat(seconds); // Add milliseconds if (ms) { time += ms/1000; } return time; }; // Update active cues whenever timeupdate events are triggered on the player. vjs.TextTrack.prototype.update = function(){ if (this.cues_.length > 0) { // Get curent player time var time = this.player_.currentTime(); // Check if the new time is outside the time box created by the the last update. if (this.prevChange === undefined || time < this.prevChange || this.nextChange <= time) { var cues = this.cues_, // Create a new time box for this state. newNextChange = this.player_.duration(), // Start at beginning of the timeline newPrevChange = 0, // Start at end reverse = false, // Set the direction of the loop through the cues. Optimized the cue check. newCues = [], // Store new active cues. // Store where in the loop the current active cues are, to provide a smart starting point for the next loop. firstActiveIndex, lastActiveIndex, cue, i; // Loop vars // Check if time is going forwards or backwards (scrubbing/rewinding) // If we know the direction we can optimize the starting position and direction of the loop through the cues array. if (time >= this.nextChange || this.nextChange === undefined) { // NextChange should happen // Forwards, so start at the index of the first active cue and loop forward i = (this.firstActiveIndex !== undefined) ? this.firstActiveIndex : 0; } else { // Backwards, so start at the index of the last active cue and loop backward reverse = true; i = (this.lastActiveIndex !== undefined) ? this.lastActiveIndex : cues.length - 1; } while (true) { // Loop until broken cue = cues[i]; // Cue ended at this point if (cue.endTime <= time) { newPrevChange = Math.max(newPrevChange, cue.endTime); if (cue.active) { cue.active = false; } // No earlier cues should have an active start time. // Nevermind. Assume first cue could have a duration the same as the video. // In that case we need to loop all the way back to the beginning. // if (reverse && cue.startTime) { break; } // Cue hasn't started } else if (time < cue.startTime) { newNextChange = Math.min(newNextChange, cue.startTime); if (cue.active) { cue.active = false; } // No later cues should have an active start time. if (!reverse) { break; } // Cue is current } else { if (reverse) { // Add cue to front of array to keep in time order newCues.splice(0,0,cue); // If in reverse, the first current cue is our lastActiveCue if (lastActiveIndex === undefined) { lastActiveIndex = i; } firstActiveIndex = i; } else { // Add cue to end of array newCues.push(cue); // If forward, the first current cue is our firstActiveIndex if (firstActiveIndex === undefined) { firstActiveIndex = i; } lastActiveIndex = i; } newNextChange = Math.min(newNextChange, cue.endTime); newPrevChange = Math.max(newPrevChange, cue.startTime); cue.active = true; } if (reverse) { // Reverse down the array of cues, break if at first if (i === 0) { break; } else { i--; } } else { // Walk up the array fo cues, break if at last if (i === cues.length - 1) { break; } else { i++; } } } this.activeCues_ = newCues; this.nextChange = newNextChange; this.prevChange = newPrevChange; this.firstActiveIndex = firstActiveIndex; this.lastActiveIndex = lastActiveIndex; this.updateDisplay(); this.trigger('cuechange'); } } }; // Add cue HTML to display vjs.TextTrack.prototype.updateDisplay = function(){ var cues = this.activeCues_, html = '', i=0,j=cues.length; for (;i<j;i++) { html += '<span class="vjs-tt-cue">'+cues[i].text+'</span>'; } this.el_.innerHTML = html; }; // Set all loop helper values back vjs.TextTrack.prototype.reset = function(){ this.nextChange = 0; this.prevChange = this.player_.duration(); this.firstActiveIndex = 0; this.lastActiveIndex = 0; }; // Create specific track types /** * The track component for managing the hiding and showing of captions * * @constructor */ vjs.CaptionsTrack = vjs.TextTrack.extend(); vjs.CaptionsTrack.prototype.kind_ = 'captions'; // Exporting here because Track creation requires the track kind // to be available on global object. e.g. new window['videojs'][Kind + 'Track'] /** * The track component for managing the hiding and showing of subtitles * * @constructor */ vjs.SubtitlesTrack = vjs.TextTrack.extend(); vjs.SubtitlesTrack.prototype.kind_ = 'subtitles'; /** * The track component for managing the hiding and showing of chapters * * @constructor */ vjs.ChaptersTrack = vjs.TextTrack.extend(); vjs.ChaptersTrack.prototype.kind_ = 'chapters'; /* Text Track Display ============================================================================= */ // Global container for both subtitle and captions text. Simple div container. /** * The component for displaying text track cues * * @constructor */ vjs.TextTrackDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options, ready){ vjs.Component.call(this, player, options, ready); // This used to be called during player init, but was causing an error // if a track should show by default and the display hadn't loaded yet. // Should probably be moved to an external track loader when we support // tracks that don't need a display. if (player.options_['tracks'] && player.options_['tracks'].length > 0) { this.player_.addTextTracks(player.options_['tracks']); } } }); vjs.TextTrackDisplay.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-text-track-display' }); }; /** * The specific menu item type for selecting a language within a text track kind * * @constructor */ vjs.TextTrackMenuItem = vjs.MenuItem.extend({ /** @constructor */ init: function(player, options){ var track = this.track = options['track']; // Modify options for parent MenuItem class's init. options['label'] = track.label(); options['selected'] = track.dflt(); vjs.MenuItem.call(this, player, options); this.player_.on(track.kind() + 'trackchange', vjs.bind(this, this.update)); } }); vjs.TextTrackMenuItem.prototype.onClick = function(){ vjs.MenuItem.prototype.onClick.call(this); this.player_.showTextTrack(this.track.id_, this.track.kind()); }; vjs.TextTrackMenuItem.prototype.update = function(){ this.selected(this.track.mode() == 2); }; /** * A special menu item for turning of a specific type of text track * * @constructor */ vjs.OffTextTrackMenuItem = vjs.TextTrackMenuItem.extend({ /** @constructor */ init: function(player, options){ // Create pseudo track info // Requires options['kind'] options['track'] = { kind: function() { return options['kind']; }, player: player, label: function(){ return options['kind'] + ' off'; }, dflt: function(){ return false; }, mode: function(){ return false; } }; vjs.TextTrackMenuItem.call(this, player, options); this.selected(true); } }); vjs.OffTextTrackMenuItem.prototype.onClick = function(){ vjs.TextTrackMenuItem.prototype.onClick.call(this); this.player_.showTextTrack(this.track.id_, this.track.kind()); }; vjs.OffTextTrackMenuItem.prototype.update = function(){ var tracks = this.player_.textTracks(), i=0, j=tracks.length, track, off = true; for (;i<j;i++) { track = tracks[i]; if (track.kind() == this.track.kind() && track.mode() == 2) { off = false; } } this.selected(off); }; /** * The base class for buttons that toggle specific text track types (e.g. subtitles) * * @constructor */ vjs.TextTrackButton = vjs.MenuButton.extend({ /** @constructor */ init: function(player, options){ vjs.MenuButton.call(this, player, options); if (this.items.length <= 1) { this.hide(); } } }); // vjs.TextTrackButton.prototype.buttonPressed = false; // vjs.TextTrackButton.prototype.createMenu = function(){ // var menu = new vjs.Menu(this.player_); // // Add a title list item to the top // // menu.el().appendChild(vjs.createEl('li', { // // className: 'vjs-menu-title', // // innerHTML: vjs.capitalize(this.kind_), // // tabindex: -1 // // })); // this.items = this.createItems(); // // Add menu items to the menu // for (var i = 0; i < this.items.length; i++) { // menu.addItem(this.items[i]); // } // // Add list to element // this.addChild(menu); // return menu; // }; // Create a menu item for each text track vjs.TextTrackButton.prototype.createItems = function(){ var items = [], track; // Add an OFF menu item to turn all tracks off items.push(new vjs.OffTextTrackMenuItem(this.player_, { 'kind': this.kind_ })); for (var i = 0; i < this.player_.textTracks().length; i++) { track = this.player_.textTracks()[i]; if (track.kind() === this.kind_) { items.push(new vjs.TextTrackMenuItem(this.player_, { 'track': track })); } } return items; }; /** * The button component for toggling and selecting captions * * @constructor */ vjs.CaptionsButton = vjs.TextTrackButton.extend({ /** @constructor */ init: function(player, options, ready){ vjs.TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label','Captions Menu'); } }); vjs.CaptionsButton.prototype.kind_ = 'captions'; vjs.CaptionsButton.prototype.buttonText = 'Captions'; vjs.CaptionsButton.prototype.className = 'vjs-captions-button'; /** * The button component for toggling and selecting subtitles * * @constructor */ vjs.SubtitlesButton = vjs.TextTrackButton.extend({ /** @constructor */ init: function(player, options, ready){ vjs.TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label','Subtitles Menu'); } }); vjs.SubtitlesButton.prototype.kind_ = 'subtitles'; vjs.SubtitlesButton.prototype.buttonText = 'Subtitles'; vjs.SubtitlesButton.prototype.className = 'vjs-subtitles-button'; // Chapters act much differently than other text tracks // Cues are navigation vs. other tracks of alternative languages /** * The button component for toggling and selecting chapters * * @constructor */ vjs.ChaptersButton = vjs.TextTrackButton.extend({ /** @constructor */ init: function(player, options, ready){ vjs.TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label','Chapters Menu'); } }); vjs.ChaptersButton.prototype.kind_ = 'chapters'; vjs.ChaptersButton.prototype.buttonText = 'Chapters'; vjs.ChaptersButton.prototype.className = 'vjs-chapters-button'; // Create a menu item for each text track vjs.ChaptersButton.prototype.createItems = function(){ var items = [], track; for (var i = 0; i < this.player_.textTracks().length; i++) { track = this.player_.textTracks()[i]; if (track.kind() === this.kind_) { items.push(new vjs.TextTrackMenuItem(this.player_, { 'track': track })); } } return items; }; vjs.ChaptersButton.prototype.createMenu = function(){ var tracks = this.player_.textTracks(), i = 0, j = tracks.length, track, chaptersTrack, items = this.items = []; for (;i<j;i++) { track = tracks[i]; if (track.kind() == this.kind_ && track.dflt()) { if (track.readyState() < 2) { this.chaptersTrack = track; track.on('loaded', vjs.bind(this, this.createMenu)); return; } else { chaptersTrack = track; break; } } } var menu = this.menu = new vjs.Menu(this.player_); menu.el_.appendChild(vjs.createEl('li', { className: 'vjs-menu-title', innerHTML: vjs.capitalize(this.kind_), tabindex: -1 })); if (chaptersTrack) { var cues = chaptersTrack.cues_, cue, mi; i = 0; j = cues.length; for (;i<j;i++) { cue = cues[i]; mi = new vjs.ChaptersTrackMenuItem(this.player_, { 'track': chaptersTrack, 'cue': cue }); items.push(mi); menu.addChild(mi); } } if (this.items.length > 0) { this.show(); } return menu; }; /** * @constructor */ vjs.ChaptersTrackMenuItem = vjs.MenuItem.extend({ /** @constructor */ init: function(player, options){ var track = this.track = options['track'], cue = this.cue = options['cue'], currentTime = player.currentTime(); // Modify options for parent MenuItem class's init. options['label'] = cue.text; options['selected'] = (cue.startTime <= currentTime && currentTime < cue.endTime); vjs.MenuItem.call(this, player, options); track.on('cuechange', vjs.bind(this, this.update)); } }); vjs.ChaptersTrackMenuItem.prototype.onClick = function(){ vjs.MenuItem.prototype.onClick.call(this); this.player_.currentTime(this.cue.startTime); this.update(this.cue.startTime); }; vjs.ChaptersTrackMenuItem.prototype.update = function(){ var cue = this.cue, currentTime = this.player_.currentTime(); // vjs.log(currentTime, cue.startTime); this.selected(cue.startTime <= currentTime && currentTime < cue.endTime); }; // Add Buttons to controlBar vjs.obj.merge(vjs.ControlBar.prototype.options_['children'], { 'subtitlesButton': {}, 'captionsButton': {}, 'chaptersButton': {} }); // vjs.Cue = vjs.Component.extend({ // /** @constructor */ // init: function(player, options){ // vjs.Component.call(this, player, options); // } // }); /** * @fileoverview Add JSON support * @suppress {undefinedVars} * (Compiler doesn't like JSON not being declared) */ /** * Javascript JSON implementation * (Parse Method Only) * https://github.com/douglascrockford/JSON-js/blob/master/json2.js * Only using for parse method when parsing data-setup attribute JSON. * @suppress {undefinedVars} * @namespace * @private */ vjs.JSON; if (typeof window.JSON !== 'undefined' && window.JSON.parse === 'function') { vjs.JSON = window.JSON; } else { vjs.JSON = {}; var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; /** * parse the json * * @memberof vjs.JSON * @param {String} text The JSON string to parse * @param {Function=} [reviver] Optional function that can transform the results * @return {Object|Array} The parsed JSON */ vjs.JSON.parse = function (text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({'': j}, '') : j; } throw new SyntaxError('JSON.parse(): invalid or malformed JSON data'); }; } /** * @fileoverview Functions for automatically setting up a player * based on the data-setup attribute of the video tag */ // Automatically set up any tags that have a data-setup attribute vjs.autoSetup = function(){ var options, vid, player, vids = document.getElementsByTagName('video'); // Check if any media elements exist if (vids && vids.length > 0) { for (var i=0,j=vids.length; i<j; i++) { vid = vids[i]; // Check if element exists, has getAttribute func. // IE seems to consider typeof el.getAttribute == 'object' instead of 'function' like expected, at least when loading the player immediately. if (vid && vid.getAttribute) { // Make sure this player hasn't already been set up. if (vid['player'] === undefined) { options = vid.getAttribute('data-setup'); // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if (options !== null) { // Parse options JSON // If empty string, make it a parsable json object. options = vjs.JSON.parse(options || '{}'); // Create new video.js instance. player = videojs(vid, options); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { vjs.autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finisehd loading. } else if (!vjs.windowLoaded) { vjs.autoSetupTimeout(1); } }; // Pause to let the DOM keep processing vjs.autoSetupTimeout = function(wait){ setTimeout(vjs.autoSetup, wait); }; if (document.readyState === 'complete') { vjs.windowLoaded = true; } else { vjs.one(window, 'load', function(){ vjs.windowLoaded = true; }); } // Run Auto-load players // You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version) vjs.autoSetupTimeout(1); /** * the method for registering a video.js plugin * * @param {String} name The name of the plugin * @param {Function} init The function that is run when the player inits */ vjs.plugin = function(name, init){ vjs.Player.prototype[name] = init; };
webroot/javascript/lib/slickgrid/lib/jquery-1.7.min.js
MaxLeap/MyBaaS
/*! jQuery v1.7 jquery.com | jquery.org/license */ (function(a,b){function cA(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cx(a){if(!cm[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cn||(cn=c.createElement("iframe"),cn.frameBorder=cn.width=cn.height=0),b.appendChild(cn);if(!co||!cn.createElement)co=(cn.contentWindow||cn.contentDocument).document,co.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),co.close();d=co.createElement(a),co.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cn)}cm[a]=e}return cm[a]}function cw(a,b){var c={};f.each(cs.concat.apply([],cs.slice(0,b)),function(){c[this]=a});return c}function cv(){ct=b}function cu(){setTimeout(cv,0);return ct=f.now()}function cl(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ck(){try{return new a.XMLHttpRequest}catch(b){}}function ce(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 cd(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 cc(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bG.test(a)?d(a,e):cc(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)cc(a+"["+e+"]",b[e],c,d);else d(a,b)}function cb(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 ca(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===bV,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=ca(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=ca(a,c,d,e,"*",g));return l}function b_(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bR),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 bE(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bz:bA;if(d>0){c!=="border"&&f.each(e,function(){c||(d-=parseFloat(f.css(a,"padding"+this))||0),c==="margin"?d+=parseFloat(f.css(a,c+this))||0:d-=parseFloat(f.css(a,"border"+this+"Width"))||0});return d+"px"}d=bB(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0,c&&f.each(e,function(){d+=parseFloat(f.css(a,"padding"+this))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+this+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+this))||0)});return d+"px"}function br(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bi,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bq(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bp(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bp)}function bp(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bo(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bn(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 bm(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 bl(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function X(a){var b=Y.split(" "),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function W(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(R.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 V(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function N(){return!0}function M(){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 K(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(K,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=/\d/,n=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,o=/^[\],:{}\s]*$/,p=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,q=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,r=/(?:^|:|,)(?:\s*\[)+/g,s=/(webkit)[ \/]([\w.]+)/,t=/(opera)(?:.*version)?[ \/]([\w.]+)/,u=/(msie) ([\w.]+)/,v=/(mozilla)(?:.*? rv:([\w.]+))?/,w=/-([a-z]|[0-9])/ig,x=/^-ms-/,y=function(a,b){return(b+"").toUpperCase()},z=d.userAgent,A,B,C,D=Object.prototype.toString,E=Object.prototype.hasOwnProperty,F=Array.prototype.push,G=Array.prototype.slice,H=String.prototype.trim,I=Array.prototype.indexOf,J={};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=n.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",length:0,size:function(){return this.length},toArray:function(){return G.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)?F.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(),B.add(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(G.apply(this,arguments),"slice",G.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:F,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;B.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!B){B=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",C,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",C),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&K()}}},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 a!=null&&m.test(a)&&!isNaN(a)},type:function(a){return a==null?String(a):J[D.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!E.call(a,"constructor")&&!E.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||E.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(o.test(b.replace(p,"@").replace(q,"]").replace(r,"")))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(x,"ms-").replace(w,y)},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:H?function(a){return a==null?"":H.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)?F.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(I)return I.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=G.call(arguments,2),g=function(){return a.apply(c,f.concat(G.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=s.exec(a)||t.exec(a)||u.exec(a)||a.indexOf("compatible")<0&&v.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){J["[object "+b+"]"]=b.toLowerCase()}),A=e.uaMatch(z),A.browser&&(e.browser[A.browser]=!0,e.browser.version=A.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?C=function(){c.removeEventListener("DOMContentLoaded",C,!1),e.ready()}:c.attachEvent&&(C=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",C),e.ready())}),typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return e});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(){return i.done.apply(i,arguments).fail.apply(i,arguments)},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 a=c.createElement("div"),b=c.documentElement,d,e,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;a.setAttribute("className","t"),a.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/><nav></nav>",d=a.getElementsByTagName("*"),e=a.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=a.getElementsByTagName("input")[0],k={leadingWhitespace:a.firstChild.nodeType===3,tbody:!a.getElementsByTagName("tbody").length,htmlSerialize:!!a.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,unknownElems:!!a.getElementsByTagName("nav").length,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:a.className!=="t",enctype:!!c.createElement("form").enctype,submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,k.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,k.optDisabled=!h.disabled;try{delete a.test}catch(v){k.deleteExpando=!1}!a.addEventListener&&a.attachEvent&&a.fireEvent&&(a.attachEvent("onclick",function(){k.noCloneEvent=!1}),a.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),k.radioValue=i.value==="t",i.setAttribute("checked","checked"),a.appendChild(i),l=c.createDocumentFragment(),l.appendChild(a.lastChild),k.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,a.innerHTML="",a.style.width=a.style.paddingLeft="1px",m=c.getElementsByTagName("body")[0],o=c.createElement(m?"div":"body"),p={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},m&&f.extend(p,{position:"absolute",left:"-999px",top:"-999px"});for(t in p)o.style[t]=p[t];o.appendChild(a),n=m||b,n.insertBefore(o,n.firstChild),k.appendChecked=i.checked,k.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,k.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",k.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",q=a.getElementsByTagName("td"),u=q[0].offsetHeight===0,q[0].style.display="",q[1].style.display="none",k.reliableHiddenOffsets=u&&q[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",a.appendChild(j),k.reliableMarginRight=(parseInt((c.defaultView.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(a.attachEvent)for(t in{submit:1,change:1,focusin:1})s="on"+t,u=s in a,u||(a.setAttribute(s,"return;"),u=typeof a[s]=="function"),k[t+"Bubbles"]=u;f(function(){var a,b,d,e,g,h,i=1,j="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",l="visibility:hidden;border:0;",n="style='"+j+"border:5px solid #000;padding:0;'",p="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>";m=c.getElementsByTagName("body")[0];!m||(a=c.createElement("div"),a.style.cssText=l+"width:0;height:0;position:static;top:0;margin-top:"+i+"px",m.insertBefore(a,m.firstChild),o=c.createElement("div"),o.style.cssText=j+l,o.innerHTML=p,a.appendChild(o),b=o.firstChild,d=b.firstChild,g=b.nextSibling.firstChild.firstChild,h={doesNotAddBorder:d.offsetTop!==5,doesAddBorderForTableAndCells:g.offsetTop===5},d.style.position="fixed",d.style.top="20px",h.fixedPosition=d.offsetTop===20||d.offsetTop===15,d.style.position=d.style.top="",b.style.overflow="hidden",b.style.position="relative",h.subtractsBorderForOverflowNotVisible=d.offsetTop===-5,h.doesNotIncludeMarginInBodyOffset=m.offsetTop!==i,m.removeChild(a),o=a=null,f.extend(k,h))}),o.innerHTML="",n.removeChild(o),o=l=g=h=m=j=a=i=null;return k}(),f.boxModel=f.support.boxModel;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[f.expando]:a[f.expando]&&f.expando,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[f.expando]=n=++f.uuid:n=f.expando),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[f.expando]:f.expando;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)?b=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[f.expando]:a.removeAttribute?a.removeAttribute(f.expando):a[f.expando]=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){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}return b}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}})}}),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)return b;if(e&&c in f.attrFn)return f(a)[c](d);if(!("getAttribute"in a))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 b}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(a.nodeType===1){d=(b||"").split(p),g=d.length;for(;h<g;h++)e=d[h].toLowerCase(),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)return b;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=/\.(.*)$/,A=/^(?:textarea|input|select)$/i,B=/\./g,C=/ /g,D=/[^\w\s.|`]/g,E=/^([^\.]*)?(?:\.(.+))?$/,F=/\bhover(\.\S+)?/,G=/^key/,H=/^(?:mouse|contextmenu)|click/,I=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,J=function(a){var b=I.exec(a);b&& (b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},K=function(a,b){return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||a.id===b[2])&&(!b[3]||b[3].test(a.className))},L=function(a){return f.event.special.hover?a:a.replace(F,"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=L(c).split(" ");for(k=0;k<c.length;k++){l=E.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,namespace:n.join(".")},p),g&&(o.quick=J(g),!o.quick&&f.expr.match.POS.test(g)&&(o.isPositional=!0)),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){var e=f.hasData(a)&&f._data(a),g,h,i,j,k,l,m,n,o,p,q;if(!!e&&!!(m=e.events)){b=L(b||"").split(" ");for(g=0;g<b.length;g++){h=E.exec(b[g])||[],i=h[1],j=h[2];if(!i){j=j?"."+j:"";for(l in m)f.event.remove(a,l+j,c,d);return}n=f.event.special[i]||{},i=(d?n.delegateType:n.bindType)||i,p=m[i]||[],k=p.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;if(c||j||d||n.remove)for(l=0;l<p.length;l++){q=p[l];if(!c||c.guid===q.guid)if(!j||j.test(q.namespace))if(!d||d===q.selector||d==="**"&&q.selector)p.splice(l--,1),q.selector&&p.delegateCount--,n.remove&&n.remove.call(a,q)}else p.length=0;p.length===0&&k!==p.length&&((!n.teardown||n.teardown.call(a,j)===!1)&&f.removeEvent(a,i,e.handle),delete m[i])}f.isEmptyObject(m)&&(o=e.handle,o&&(o.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;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:"",(g||!e)&&c.preventDefault();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,n=null;for(m=e.parentNode;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;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);if(c.isPropagationStopped())break}c.type=h,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=(f.event.special[c.type]||{}).handle,j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click"))for(m=c.target;m!=this;m=m.parentNode||this){o={},q=[];for(k=0;k<e;k++)r=d[k],s=r.selector,t=o[s],r.isPositional?t=(t||(o[s]=f(s))).index(m)>=0:t===b&&(t=o[s]=r.quick?K(m,r.quick):f(m).is(s)),t&&q.push(r);q.length&&j.push({elem:m,matches:q})}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){p=j[k],c.currentTarget=p.elem;for(l=0;l<p.matches.length&&!c.isImmediatePropagationStopped();l++){r=p.matches[l];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=(i||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 wheelDelta".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},focus:{delegateType:"focusin",noBubble:!0},blur:{delegateType:"focusout",noBubble:!0},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()?N:M):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=N;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=N;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=N,this.stopPropagation()},isDefaultPrevented:M,isPropagationStopped:M,isImmediatePropagationStopped:M},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]=f.event.special[b]={delegateType:b,bindType:b,handle:function(a){var b=this,c=a.relatedTarget,d=a.handleObj,e=d.selector,g,h;if(!c||d.origType===a.type||c!==b&&!f.contains(b,c))g=a.type,a.type=d.origType,h=d.handler.apply(this,arguments),a.type=g;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&&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(A.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&&(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;A.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&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 A.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=M;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=M);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.bind(b,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),G.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),H.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"Syntax error, unrecognized expression: "+a};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1){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 O=/Until$/,P=/^(?:parents|prevUntil|prevAll)/,Q=/,/,R=/^.[^:#\[\.,]*$/,S=Array.prototype.slice,T=f.expr.match.POS,U={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(W(this,a,!1),"not",a)},filter:function(a){return this.pushStack(W(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?T.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=T.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(V(c[0])||V(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),g=S.call(arguments);O.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!U[a]?f.unique(e):e,(this.length>1||Q.test(d))&&P.test(a)&&(e=e.reverse());return this.pushStack(e,a,g.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 Y="abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",Z=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,_=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,ba=/<([\w:]+)/,bb=/<tbody/i,bc=/<|&#?\w+;/,bd=/<(?:script|style)/i,be=/<(?:script|object|embed|option|style)/i,bf=new RegExp("<(?:"+Y.replace(" ","|")+")","i"),bg=/checked\s*(?:[^=]|=\s*.checked.)/i,bh=/\/(java|ecma)script/i,bi=/^\s*<!(?:\[CDATA\[|\-\-)/,bj={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,"",""]},bk=X(c);bj.optgroup=bj.option,bj.tbody=bj.tfoot=bj.colgroup=bj.caption=bj.thead,bj.th=bj.td,f.support.htmlSerialize||(bj._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){return this.each(function(){f(this).wrapAll(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(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after" ,arguments);a.push.apply(a,f(arguments[0]).toArray());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(Z,""):null;if(typeof a=="string"&&!bd.test(a)&&(f.support.leadingWhitespace||!$.test(a))&&!bj[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(_,"<$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"&&bg.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?bl(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,br)}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)==="<"&&!be.test(j)&&(f.support.checkClone||!bg.test(j))&&!f.support.unknownElems&&bf.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=a.cloneNode(!0),e,g,h;if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bn(a,d),e=bo(a),g=bo(d);for(h=0;e[h];++h)g[h]&&bn(e[h],g[h])}if(b){bm(a,d);if(c){e=bo(a),g=bo(d);for(h=0;e[h];++h)bm(e[h],g[h])}}e=g=null;return d},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(!bc.test(k))k=b.createTextNode(k);else{k=k.replace(_,"<$1></$2>");var l=(ba.exec(k)||["",""])[1].toLowerCase(),m=bj[l]||bj._default,n=m[0],o=b.createElement("div");b===c?bk.appendChild(o):X(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=bb.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&&$.test(k)&&o.insertBefore(b.createTextNode($.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++)bq(k[i]);else bq(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||bh.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 bs=/alpha\([^)]*\)/i,bt=/opacity=([^)]*)/,bu=/([A-Z]|^ms)/g,bv=/^-?\d+(?:px)?$/i,bw=/^-?\d/,bx=/^([\-+])=([\-+.\de]+)/,by={position:"absolute",visibility:"hidden",display:"block"},bz=["Left","Right"],bA=["Top","Bottom"],bB,bC,bD;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=bB(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=bx.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(bB)return bB(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 bE(a,b,d);f.swap(a,by,function(){e=bE(a,b,d)});return e}},set:function(a,b){if(!bv.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bt.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(bs,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bs.test(g)?g.replace(bs,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=bB(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bC=function(a,c){var d,e,g;c=c.replace(bu,"-$1").toLowerCase();if(!(e=a.ownerDocument.defaultView))return b;if(g=e.getComputedStyle(a,null))d=g.getPropertyValue(c),d===""&&!f.contains(a.ownerDocument.documentElement,a)&&(d=f.style(a,c));return d}),c.documentElement.currentStyle&&(bD=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bv.test(f)&&bw.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}),bB=bC||bD,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 bF=/%20/g,bG=/\[\]$/,bH=/\r?\n/g,bI=/#.*$/,bJ=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bK=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bL=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bM=/^(?:GET|HEAD)$/,bN=/^\/\//,bO=/\?/,bP=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bQ=/^(?:select|textarea)/i,bR=/\s+/,bS=/([?&])_=[^&]*/,bT=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bU=f.fn.load,bV={},bW={},bX,bY,bZ=["*/"]+["*"];try{bX=e.href}catch(b$){bX=c.createElement("a"),bX.href="",bX=bX.href}bY=bT.exec(bX.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bU)return bU.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(bP,"")).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||bQ.test(this.nodeName)||bK.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(bH,"\r\n")}}):{name:b.name,value:c.replace(bH,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.bind(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?cb(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),cb(a,b);return a},ajaxSettings:{url:bX,isLocal:bL.test(bY[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","*":bZ},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:b_(bV),ajaxTransport:b_(bW),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?cd(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=ce(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=bJ.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(bI,"").replace(bN,bY[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bR),d.crossDomain==null&&(r=bT.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bY[1]&&r[2]==bY[2]&&(r[3]||(r[1]==="http:"?80:443))==(bY[3]||(bY[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),ca(bV,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bM.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bO.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bS,"$1_="+x);d.url=y+(y===d.url?(bO.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]!=="*"?", "+bZ+"; 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=ca(bW,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){s<2?w(-1,z):f.error(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)cc(g,a[g],c,e);return d.join("&").replace(bF,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cf=f.now(),cg=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cf++}}),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&&(cg.test(b.url)||e&&cg.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(cg,l),b.url===j&&(e&&(k=k.replace(cg,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 ch=a.ActiveXObject?function(){for(var a in cj)cj[a](0,1)}:!1,ci=0,cj;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ck()||cl()}:ck,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,ch&&delete cj[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=++ci,ch&&(cj||(cj={},f(a).unload(ch)),cj[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cm={},cn,co,cp=/^(?:toggle|show|hide)$/,cq=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cr,cs=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],ct;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cw("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",cx(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(cw("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(cw("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||cx(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],cp.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=cq.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].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:cw("show",1),slideUp:cw("hide",1),slideToggle:cw("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=ct||cu(),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)&&!cr&&(cr=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=ct||cu(),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(cr),cr=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))}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cy=/^t(?:able|d|h)$/i,cz=/^(?: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=cA(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||!cy.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=cz.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&&!cz.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=cA(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=cA(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})(window);
ajax/libs/yui/3.17.0/event-focus/event-focus-debug.js
hhbyyh/cdnjs
/* YUI 3.17.0 (build ce55cc9) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('event-focus', function (Y, NAME) { /** * Adds bubbling and delegation support to DOM events focus and blur. * * @module event * @submodule event-focus */ var Event = Y.Event, YLang = Y.Lang, isString = YLang.isString, arrayIndex = Y.Array.indexOf, useActivate = (function() { // Changing the structure of this test, so that it doesn't use inline JS in HTML, // which throws an exception in Win8 packaged apps, due to additional security restrictions: // http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences var supported = false, doc = Y.config.doc, p; if (doc) { p = doc.createElement("p"); p.setAttribute("onbeforeactivate", ";"); // onbeforeactivate is a function in IE8+. // onbeforeactivate is a string in IE6,7 (unfortunate, otherwise we could have just checked for function below). // onbeforeactivate is a function in IE10, in a Win8 App environment (no exception running the test). // onbeforeactivate is undefined in Webkit/Gecko. // onbeforeactivate is a function in Webkit/Gecko if it's a supported event (e.g. onclick). supported = (p.onbeforeactivate !== undefined); } return supported; }()); function define(type, proxy, directEvent) { var nodeDataKey = '_' + type + 'Notifiers'; Y.Event.define(type, { _useActivate : useActivate, _attach: function (el, notifier, delegate) { if (Y.DOM.isWindow(el)) { return Event._attach([type, function (e) { notifier.fire(e); }, el]); } else { return Event._attach( [proxy, this._proxy, el, this, notifier, delegate], { capture: true }); } }, _proxy: function (e, notifier, delegate) { var target = e.target, currentTarget = e.currentTarget, notifiers = target.getData(nodeDataKey), yuid = Y.stamp(currentTarget._node), defer = (useActivate || target !== currentTarget), directSub; notifier.currentTarget = (delegate) ? target : currentTarget; notifier.container = (delegate) ? currentTarget : null; // Maintain a list to handle subscriptions from nested // containers div#a>div#b>input #a.on(focus..) #b.on(focus..), // use one focus or blur subscription that fires notifiers from // #b then #a to emulate bubble sequence. if (!notifiers) { notifiers = {}; target.setData(nodeDataKey, notifiers); // only subscribe to the element's focus if the target is // not the current target ( if (defer) { directSub = Event._attach( [directEvent, this._notify, target._node]).sub; directSub.once = true; } } else { // In old IE, defer is always true. In capture-phase browsers, // The delegate subscriptions will be encountered first, which // will establish the notifiers data and direct subscription // on the node. If there is also a direct subscription to the // node's focus/blur, it should not call _notify because the // direct subscription from the delegate sub(s) exists, which // will call _notify. So this avoids _notify being called // twice, unnecessarily. defer = true; } if (!notifiers[yuid]) { notifiers[yuid] = []; } notifiers[yuid].push(notifier); if (!defer) { this._notify(e); } }, _notify: function (e, container) { var currentTarget = e.currentTarget, notifierData = currentTarget.getData(nodeDataKey), axisNodes = currentTarget.ancestors(), doc = currentTarget.get('ownerDocument'), delegates = [], // Used to escape loops when there are no more // notifiers to consider count = notifierData ? Y.Object.keys(notifierData).length : 0, target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret; // clear the notifications list (mainly for delegation) currentTarget.clearData(nodeDataKey); // Order the delegate subs by their placement in the parent axis axisNodes.push(currentTarget); // document.get('ownerDocument') returns null // which we'll use to prevent having duplicate Nodes in the list if (doc) { axisNodes.unshift(doc); } // ancestors() returns the Nodes from top to bottom axisNodes._nodes.reverse(); if (count) { // Store the count for step 2 tmp = count; axisNodes.some(function (node) { var yuid = Y.stamp(node), notifiers = notifierData[yuid], i, len; if (notifiers) { count--; for (i = 0, len = notifiers.length; i < len; ++i) { if (notifiers[i].handle.sub.filter) { delegates.push(notifiers[i]); } } } return !count; }); count = tmp; } // Walk up the parent axis, notifying direct subscriptions and // testing delegate filters. while (count && (target = axisNodes.shift())) { yuid = Y.stamp(target); notifiers = notifierData[yuid]; if (notifiers) { for (i = 0, len = notifiers.length; i < len; ++i) { notifier = notifiers[i]; sub = notifier.handle.sub; match = true; e.currentTarget = target; if (sub.filter) { match = sub.filter.apply(target, [target, e].concat(sub.args || [])); // No longer necessary to test against this // delegate subscription for the nodes along // the parent axis. delegates.splice( arrayIndex(delegates, notifier), 1); } if (match) { // undefined for direct subs e.container = notifier.container; ret = notifier.fire(e); } if (ret === false || e.stopped === 2) { break; } } delete notifiers[yuid]; count--; } if (e.stopped !== 2) { // delegates come after subs targeting this specific node // because they would not normally report until they'd // bubbled to the container node. for (i = 0, len = delegates.length; i < len; ++i) { notifier = delegates[i]; sub = notifier.handle.sub; if (sub.filter.apply(target, [target, e].concat(sub.args || []))) { e.container = notifier.container; e.currentTarget = target; ret = notifier.fire(e); } if (ret === false || e.stopped === 2 || // If e.stopPropagation() is called, notify any // delegate subs from the same container, but break // once the container changes. This emulates // delegate() behavior for events like 'click' which // won't notify delegates higher up the parent axis. (e.stopped && delegates[i+1] && delegates[i+1].container !== notifier.container)) { break; } } } if (e.stopped) { break; } } }, on: function (node, sub, notifier) { sub.handle = this._attach(node._node, notifier); }, detach: function (node, sub) { sub.handle.detach(); }, delegate: function (node, sub, notifier, filter) { if (isString(filter)) { sub.filter = function (target) { return Y.Selector.test(target._node, filter, node === target ? null : node._node); }; } sub.handle = this._attach(node._node, notifier, true); }, detachDelegate: function (node, sub) { sub.handle.detach(); } }, true); } // For IE, we need to defer to focusin rather than focus because // `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate, // el.onfocusin, doSomething, then el.onfocus. All others support capture // phase focus, which executes before doSomething. To guarantee consistent // behavior for this use case, IE's direct subscriptions are made against // focusin so subscribers will be notified before js following el.focus() is // executed. if (useActivate) { // name capture phase direct subscription define("focus", "beforeactivate", "focusin"); define("blur", "beforedeactivate", "focusout"); } else { define("focus", "focus", "focus"); define("blur", "blur", "blur"); } }, '3.17.0', {"requires": ["event-synthetic"]});
test/app/entry.js
mbaasy/react-router-path-extractor-webpack-plugin
'use strict' import React from 'react' import { render } from 'react-dom' import { renderToString } from 'react-dom/server' import { RouterContext, Router, browserHistory, match, createMemoryHistory } from 'react-router' import routes from './routes' const template = (html, assets) => (` <!DOCTYPE html> <html> <head> <title>ReactRouterPathExtractorWebpackPlugin Test</title> <meta charset='utf-8' /> </head> <body> <div id='outlet'>${html}</div> <script src='/${assets.main}'></script> </body> </html> `) if (typeof document !== 'undefined') { render( <Router history={browserHistory} routes={routes} /> , document.getElementById('outlet')) } export default (locals, callback) => { const history = createMemoryHistory() const location = history.createLocation(locals.path) match({routes, location}, (error, redirectLocation, renderProps) => { if (error) { return callback(error) } const html = renderToString( <RouterContext {...renderProps} /> ) callback(null, template(html, locals.assets)) }) }
src/components/map/EventMarker.js
ReactPoland/react-community
import React from 'react'; import PropTypes from 'prop-types'; import { Marker, Popup } from 'react-leaflet-universal'; import styles from './Map.scss'; const EventMarker = ({ marker }) => { return ( <Marker position={[marker.lat, marker.lng]}> <Popup> <div className={styles.MarkerPopup}> <h3> <a href={marker.link}>{marker.title}</a> </h3> <p>{marker.description}</p> </div> </Popup> </Marker> ); }; EventMarker.propTypes = { marker: PropTypes.object.isRequired }; export default EventMarker;
app/javascript/mastodon/components/__tests__/avatar-test.js
PlantsNetwork/mastodon
import React from 'react'; import renderer from 'react-test-renderer'; import { fromJS } from 'immutable'; import Avatar from '../avatar'; describe('<Avatar />', () => { const account = fromJS({ username: 'alice', acct: 'alice', display_name: 'Alice', avatar: '/animated/alice.gif', avatar_static: '/static/alice.jpg', }); const size = 100; describe('Autoplay', () => { it('renders a animated avatar', () => { const component = renderer.create(<Avatar account={account} animate size={size} />); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); }); describe('Still', () => { it('renders a still avatar', () => { const component = renderer.create(<Avatar account={account} size={size} />); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); }); // TODO add autoplay test if possible });
files/cleditor/1.3.0/jquery.cleditor.js
oller/jsdelivr
/** @preserve CLEditor WYSIWYG HTML Editor v1.3.0 http://premiumsoftware.net/cleditor requires jQuery v1.4.2 or later Copyright 2010, Chris Landowski, Premium Software, LLC Dual licensed under the MIT or GPL Version 2 licenses. */ // ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS // @output_file_name jquery.cleditor.min.js // ==/ClosureCompiler== (function($) { //============== // jQuery Plugin //============== $.cleditor = { // Define the defaults used for all new cleditor instances defaultOptions: { width: 500, // width not including margins, borders or padding height: 250, // height not including margins, borders or padding controls: // controls to add to the toolbar "bold italic underline strikethrough subscript superscript | font size " + "style | color highlight removeformat | bullets numbering | outdent " + "indent | alignleft center alignright justify | undo redo | " + "rule image link unlink | cut copy paste pastetext | print source", colors: // colors in the color popup "FFF FCC FC9 FF9 FFC 9F9 9FF CFF CCF FCF " + "CCC F66 F96 FF6 FF3 6F9 3FF 6FF 99F F9F " + "BBB F00 F90 FC6 FF0 3F3 6CC 3CF 66C C6C " + "999 C00 F60 FC3 FC0 3C0 0CC 36F 63F C3C " + "666 900 C60 C93 990 090 399 33F 60C 939 " + "333 600 930 963 660 060 366 009 339 636 " + "000 300 630 633 330 030 033 006 309 303", fonts: // font names in the font popup "Arial,Arial Black,Comic Sans MS,Courier New,Narrow,Garamond," + "Georgia,Impact,Sans Serif,Serif,Tahoma,Trebuchet MS,Verdana", sizes: // sizes in the font size popup "1,2,3,4,5,6,7", styles: // styles in the style popup [["Paragraph", "<p>"], ["Header 1", "<h1>"], ["Header 2", "<h2>"], ["Header 3", "<h3>"], ["Header 4","<h4>"], ["Header 5","<h5>"], ["Header 6","<h6>"]], useCSS: false, // use CSS to style HTML when possible (not supported in ie) docType: // Document type contained within the editor '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">', docCSSFile: // CSS file used to style the document contained within the editor "", bodyStyle: // style to assign to document body contained within the editor "margin:4px; font:10pt Arial,Verdana; cursor:text" }, // Define all usable toolbar buttons - the init string property is // expanded during initialization back into the buttons object and // seperate object properties are created for each button. // e.g. buttons.size.title = "Font Size" buttons: { // name,title,command,popupName (""=use name) init: "bold,,|" + "italic,,|" + "underline,,|" + "strikethrough,,|" + "subscript,,|" + "superscript,,|" + "font,,fontname,|" + "size,Font Size,fontsize,|" + "style,,formatblock,|" + "color,Font Color,forecolor,|" + "highlight,Text Highlight Color,hilitecolor,color|" + "removeformat,Remove Formatting,|" + "bullets,,insertunorderedlist|" + "numbering,,insertorderedlist|" + "outdent,,|" + "indent,,|" + "alignleft,Align Text Left,justifyleft|" + "center,,justifycenter|" + "alignright,Align Text Right,justifyright|" + "justify,,justifyfull|" + "undo,,|" + "redo,,|" + "rule,Insert Horizontal Rule,inserthorizontalrule|" + "image,Insert Image,insertimage,url|" + "link,Insert Hyperlink,createlink,url|" + "unlink,Remove Hyperlink,|" + "cut,,|" + "copy,,|" + "paste,,|" + "pastetext,Paste as Text,inserthtml,|" + "print,,|" + "source,Show Source" }, // imagesPath - returns the path to the images folder imagesPath: function() { return imagesPath(); } }; // cleditor - creates a new editor for each of the matched textareas $.fn.cleditor = function(options) { // Create a new jQuery object to hold the results var $result = $([]); // Loop through all matching textareas and create the editors this.each(function(idx, elem) { if (elem.tagName == "TEXTAREA") { var data = $.data(elem, CLEDITOR); if (!data) data = new cleditor(elem, options); $result = $result.add(data); } }); // return the new jQuery object return $result; }; //================== // Private Variables //================== var // Misc constants BACKGROUND_COLOR = "backgroundColor", BUTTON = "button", BUTTON_NAME = "buttonName", CHANGE = "change", CLEDITOR = "cleditor", CLICK = "click", DISABLED = "disabled", DIV_TAG = "<div>", TRANSPARENT = "transparent", UNSELECTABLE = "unselectable", // Class name constants MAIN_CLASS = "cleditorMain", // main containing div TOOLBAR_CLASS = "cleditorToolbar", // toolbar div inside main div GROUP_CLASS = "cleditorGroup", // group divs inside the toolbar div BUTTON_CLASS = "cleditorButton", // button divs inside group div DISABLED_CLASS = "cleditorDisabled",// disabled button divs DIVIDER_CLASS = "cleditorDivider", // divider divs inside group div POPUP_CLASS = "cleditorPopup", // popup divs inside body LIST_CLASS = "cleditorList", // list popup divs inside body COLOR_CLASS = "cleditorColor", // color popup div inside body PROMPT_CLASS = "cleditorPrompt", // prompt popup divs inside body MSG_CLASS = "cleditorMsg", // message popup div inside body // Test for ie ie = $.browser.msie, ie6 = /msie\s6/i.test(navigator.userAgent), // Test for iPhone/iTouch/iPad iOS = /iphone|ipad|ipod/i.test(navigator.userAgent), // Popups are created once as needed and shared by all editor instances popups = {}, // Used to prevent the document click event from being bound more than once documentClickAssigned, // Local copy of the buttons object buttons = $.cleditor.buttons; //=============== // Initialization //=============== // Expand the buttons.init string back into the buttons object // and create seperate object properties for each button. // e.g. buttons.size.title = "Font Size" $.each(buttons.init.split("|"), function(idx, button) { var items = button.split(","), name = items[0]; buttons[name] = { stripIndex: idx, name: name, title: items[1] === "" ? name.charAt(0).toUpperCase() + name.substr(1) : items[1], command: items[2] === "" ? name : items[2], popupName: items[3] === "" ? name : items[3] }; }); delete buttons.init; //============ // Constructor //============ // cleditor - creates a new editor for the passed in textarea element cleditor = function(area, options) { var editor = this; // Get the defaults and override with options editor.options = options = $.extend({}, $.cleditor.defaultOptions, options); // Hide the textarea and associate it with this editor var $area = editor.$area = $(area) .hide() .data(CLEDITOR, editor) .blur(function() { // Update the iframe when the textarea loses focus updateFrame(editor, true); }); // Create the main container and append the textarea var $main = editor.$main = $(DIV_TAG) .addClass(MAIN_CLASS) .width(options.width) .height(options.height); // Create the toolbar var $toolbar = editor.$toolbar = $(DIV_TAG) .addClass(TOOLBAR_CLASS) .appendTo($main); // Add the first group to the toolbar var $group = $(DIV_TAG) .addClass(GROUP_CLASS) .appendTo($toolbar); // Add the buttons to the toolbar $.each(options.controls.split(" "), function(idx, buttonName) { if (buttonName === "") return true; // Divider if (buttonName == "|") { // Add a new divider to the group var $div = $(DIV_TAG) .addClass(DIVIDER_CLASS) .appendTo($group); // Create a new group $group = $(DIV_TAG) .addClass(GROUP_CLASS) .appendTo($toolbar); } // Button else { // Get the button definition var button = buttons[buttonName]; // Add a new button to the group var $buttonDiv = $(DIV_TAG) .data(BUTTON_NAME, button.name) .addClass(BUTTON_CLASS) .attr("title", button.title) .bind(CLICK, $.proxy(buttonClick, editor)) .appendTo($group) .hover(hoverEnter, hoverLeave); // Prepare the button image var map = {}; if (button.css) map = button.css; else if (button.image) map.backgroundImage = imageUrl(button.image); if (button.stripIndex) map.backgroundPosition = button.stripIndex * -24; $buttonDiv.css(map); // Add the unselectable attribute for ie if (ie) $buttonDiv.attr(UNSELECTABLE, "on"); // Create the popup if (button.popupName) createPopup(button.popupName, options, button.popupClass, button.popupContent, button.popupHover); } }); // Add the main div to the DOM and append the textarea $main.insertBefore($area) .append($area); // Bind the document click event handler if (!documentClickAssigned) { $(document).click(function(e) { // Dismiss all non-prompt popups var $target = $(e.target); if (!$target.add($target.parents()).is("." + PROMPT_CLASS)) hidePopups(); }); documentClickAssigned = true; } // Bind the window resize event when the width or height is auto or % if (/auto|%/.test("" + options.width + options.height)) $(window).resize(function() {refresh(editor);}); // Create the iframe and resize the controls refresh(editor); }; //=============== // Public Methods //=============== var fn = cleditor.prototype, // Expose the following private functions as methods on the cleditor object. // The closure compiler will rename the private functions. However, the // exposed method names on the cleditor object will remain fixed. methods = [ ["clear", clear], ["disable", disable], ["execCommand", execCommand], ["focus", focus], ["hidePopups", hidePopups], ["sourceMode", sourceMode, true], ["refresh", refresh], ["select", select], ["selectedHTML", selectedHTML, true], ["selectedText", selectedText, true], ["showMessage", showMessage], ["updateFrame", updateFrame], ["updateTextArea", updateTextArea] ]; $.each(methods, function(idx, method) { fn[method[0]] = function() { var editor = this, args = [editor]; // using each here would cast booleans into objects! for(var x = 0; x < arguments.length; x++) {args.push(arguments[x]);} var result = method[1].apply(editor, args); if (method[2]) return result; return editor; }; }); // change - shortcut for .bind("change", handler) or .trigger("change") fn.change = function(handler) { var $this = $(this); return handler ? $this.bind(CHANGE, handler) : $this.trigger(CHANGE); }; //=============== // Event Handlers //=============== // buttonClick - click event handler for toolbar buttons function buttonClick(e) { var editor = this, buttonDiv = e.target, buttonName = $.data(buttonDiv, BUTTON_NAME), button = buttons[buttonName], popupName = button.popupName, popup = popups[popupName]; // Check if disabled if (editor.disabled || $(buttonDiv).attr(DISABLED) == DISABLED) return; // Fire the buttonClick event var data = { editor: editor, button: buttonDiv, buttonName: buttonName, popup: popup, popupName: popupName, command: button.command, useCSS: editor.options.useCSS }; if (button.buttonClick && button.buttonClick(e, data) === false) return false; // Toggle source if (buttonName == "source") { // Show the iframe if (sourceMode(editor)) { delete editor.range; editor.$area.hide(); editor.$frame.show(); buttonDiv.title = button.title; } // Show the textarea else { editor.$frame.hide(); editor.$area.show(); buttonDiv.title = "Show Rich Text"; } // Enable or disable the toolbar buttons // IE requires the timeout setTimeout(function() {refreshButtons(editor);}, 100); } // Check for rich text mode else if (!sourceMode(editor)) { // Handle popups if (popupName) { var $popup = $(popup); // URL if (popupName == "url") { // Check for selection before showing the link url popup if (buttonName == "link" && selectedText(editor) === "") { showMessage(editor, "A selection is required when inserting a link.", buttonDiv); return false; } // Wire up the submit button click event handler $popup.children(":button") .unbind(CLICK) .bind(CLICK, function() { // Insert the image or link if a url was entered var $text = $popup.find(":text"), url = $.trim($text.val()); if (url !== "") execCommand(editor, data.command, url, null, data.button); // Reset the text, hide the popup and set focus $text.val("http://"); hidePopups(); focus(editor); }); } // Paste as Text else if (popupName == "pastetext") { // Wire up the submit button click event handler $popup.children(":button") .unbind(CLICK) .bind(CLICK, function() { // Insert the unformatted text replacing new lines with break tags var $textarea = $popup.find("textarea"), text = $textarea.val().replace(/\n/g, "<br />"); if (text !== "") execCommand(editor, data.command, text, null, data.button); // Reset the text, hide the popup and set focus $textarea.val(""); hidePopups(); focus(editor); }); } // Show the popup if not already showing for this button if (buttonDiv !== $.data(popup, BUTTON)) { showPopup(editor, popup, buttonDiv); return false; // stop propagination to document click } // propaginate to documnt click return; } // Print else if (buttonName == "print") editor.$frame[0].contentWindow.print(); // All other buttons else if (!execCommand(editor, data.command, data.value, data.useCSS, buttonDiv)) return false; } // Focus the editor focus(editor); } // hoverEnter - mouseenter event handler for buttons and popup items function hoverEnter(e) { var $div = $(e.target).closest("div"); $div.css(BACKGROUND_COLOR, $div.data(BUTTON_NAME) ? "#FFF" : "#FFC"); } // hoverLeave - mouseleave event handler for buttons and popup items function hoverLeave(e) { $(e.target).closest("div").css(BACKGROUND_COLOR, "transparent"); } // popupClick - click event handler for popup items function popupClick(e) { var editor = this, popup = e.data.popup, target = e.target; // Check for message and prompt popups if (popup === popups.msg || $(popup).hasClass(PROMPT_CLASS)) return; // Get the button info var buttonDiv = $.data(popup, BUTTON), buttonName = $.data(buttonDiv, BUTTON_NAME), button = buttons[buttonName], command = button.command, value, useCSS = editor.options.useCSS; // Get the command value if (buttonName == "font") // Opera returns the fontfamily wrapped in quotes value = target.style.fontFamily.replace(/"/g, ""); else if (buttonName == "size") { if (target.tagName == "DIV") target = target.children[0]; value = target.innerHTML; } else if (buttonName == "style") value = "<" + target.tagName + ">"; else if (buttonName == "color") value = hex(target.style.backgroundColor); else if (buttonName == "highlight") { value = hex(target.style.backgroundColor); if (ie) command = 'backcolor'; else useCSS = true; } // Fire the popupClick event var data = { editor: editor, button: buttonDiv, buttonName: buttonName, popup: popup, popupName: button.popupName, command: command, value: value, useCSS: useCSS }; if (button.popupClick && button.popupClick(e, data) === false) return; // Execute the command if (data.command && !execCommand(editor, data.command, data.value, data.useCSS, buttonDiv)) return false; // Hide the popup and focus the editor hidePopups(); focus(editor); } //================== // Private Functions //================== // checksum - returns a checksum using the Adler-32 method function checksum(text) { var a = 1, b = 0; for (var index = 0; index < text.length; ++index) { a = (a + text.charCodeAt(index)) % 65521; b = (b + a) % 65521; } return (b << 16) | a; } // clear - clears the contents of the editor function clear(editor) { editor.$area.val(""); updateFrame(editor); } // createPopup - creates a popup and adds it to the body function createPopup(popupName, options, popupTypeClass, popupContent, popupHover) { // Check if popup already exists if (popups[popupName]) return popups[popupName]; // Create the popup var $popup = $(DIV_TAG) .hide() .addClass(POPUP_CLASS) .appendTo("body"); // Add the content // Custom popup if (popupContent) $popup.html(popupContent); // Color else if (popupName == "color") { var colors = options.colors.split(" "); if (colors.length < 10) $popup.width("auto"); $.each(colors, function(idx, color) { $(DIV_TAG).appendTo($popup) .css(BACKGROUND_COLOR, "#" + color); }); popupTypeClass = COLOR_CLASS; } // Font else if (popupName == "font") $.each(options.fonts.split(","), function(idx, font) { $(DIV_TAG).appendTo($popup) .css("fontFamily", font) .html(font); }); // Size else if (popupName == "size") $.each(options.sizes.split(","), function(idx, size) { $(DIV_TAG).appendTo($popup) .html("<font size=" + size + ">" + size + "</font>"); }); // Style else if (popupName == "style") $.each(options.styles, function(idx, style) { $(DIV_TAG).appendTo($popup) .html(style[1] + style[0] + style[1].replace("<", "</")); }); // URL else if (popupName == "url") { $popup.html('Enter URL:<br><input type=text value="http://" size=35><br><input type=button value="Submit">'); popupTypeClass = PROMPT_CLASS; } // Paste as Text else if (popupName == "pastetext") { $popup.html('Paste your content here and click submit.<br /><textarea cols=40 rows=3></textarea><br /><input type=button value=Submit>'); popupTypeClass = PROMPT_CLASS; } // Add the popup type class name if (!popupTypeClass && !popupContent) popupTypeClass = LIST_CLASS; $popup.addClass(popupTypeClass); // Add the unselectable attribute to all items if (ie) { $popup.attr(UNSELECTABLE, "on") .find("div,font,p,h1,h2,h3,h4,h5,h6") .attr(UNSELECTABLE, "on"); } // Add the hover effect to all items if ($popup.hasClass(LIST_CLASS) || popupHover === true) $popup.children().hover(hoverEnter, hoverLeave); // Add the popup to the array and return it popups[popupName] = $popup[0]; return $popup[0]; } // disable - enables or disables the editor function disable(editor, disabled) { // Update the textarea and save the state if (disabled) { editor.$area.attr(DISABLED, DISABLED); editor.disabled = true; } else { editor.$area.removeAttr(DISABLED); delete editor.disabled; } // Switch the iframe into design mode. // ie6 does not support designMode. // ie7 & ie8 do not properly support designMode="off". try { if (ie) editor.doc.body.contentEditable = !disabled; else editor.doc.designMode = !disabled ? "on" : "off"; } // Firefox 1.5 throws an exception that can be ignored // when toggling designMode from off to on. catch (err) {} // Enable or disable the toolbar buttons refreshButtons(editor); } // execCommand - executes a designMode command function execCommand(editor, command, value, useCSS, button) { // Restore the current ie selection restoreRange(editor); // Set the styling method if (!ie) { if (useCSS === undefined || useCSS === null) useCSS = editor.options.useCSS; editor.doc.execCommand("styleWithCSS", 0, useCSS.toString()); } // Execute the command and check for error var success = true, description; if (ie && command.toLowerCase() == "inserthtml") getRange(editor).pasteHTML(value); else { try { success = editor.doc.execCommand(command, 0, value || null); } catch (err) { description = err.description; success = false; } if (!success) { if ("cutcopypaste".indexOf(command) > -1) showMessage(editor, "For security reasons, your browser does not support the " + command + " command. Try using the keyboard shortcut or context menu instead.", button); else showMessage(editor, (description ? description : "Error executing the " + command + " command."), button); } } // Enable the buttons refreshButtons(editor); return success; } // focus - sets focus to either the textarea or iframe function focus(editor) { setTimeout(function() { if (sourceMode(editor)) editor.$area.focus(); else editor.$frame[0].contentWindow.focus(); refreshButtons(editor); }, 0); } // getRange - gets the current text range object function getRange(editor) { if (ie) return getSelection(editor).createRange(); return getSelection(editor).getRangeAt(0); } // getSelection - gets the current text range object function getSelection(editor) { if (ie) return editor.doc.selection; return editor.$frame[0].contentWindow.getSelection(); } // Returns the hex value for the passed in string. // hex("rgb(255, 0, 0)"); // #FF0000 // hex("#FF0000"); // #FF0000 // hex("#F00"); // #FF0000 function hex(s) { var m = /rgba?\((\d+), (\d+), (\d+)/.exec(s), c = s.split(""); if (m) { s = ( m[1] << 16 | m[2] << 8 | m[3] ).toString(16); while (s.length < 6) s = "0" + s; } return "#" + (s.length == 6 ? s : c[1] + c[1] + c[2] + c[2] + c[3] + c[3]); } // hidePopups - hides all popups function hidePopups() { $.each(popups, function(idx, popup) { $(popup) .hide() .unbind(CLICK) .removeData(BUTTON); }); } // imagesPath - returns the path to the images folder function imagesPath() { var cssFile = "jquery.cleditor.css", href = $("link[href$='" + cssFile +"']").attr("href"); return href.substr(0, href.length - cssFile.length) + "images/"; } // imageUrl - Returns the css url string for a filemane function imageUrl(filename) { return "url(" + imagesPath() + filename + ")"; } // refresh - creates the iframe and resizes the controls function refresh(editor) { var $main = editor.$main, options = editor.options; // Remove the old iframe if (editor.$frame) editor.$frame.remove(); // Create a new iframe var $frame = editor.$frame = $('<iframe frameborder="0" src="javascript:true;">') .hide() .appendTo($main); // Load the iframe document content var contentWindow = $frame[0].contentWindow, doc = editor.doc = contentWindow.document, $doc = $(doc); doc.open(); doc.write( options.docType + '<html>' + ((options.docCSSFile === '') ? '' : '<head><link rel="stylesheet" type="text/css" href="' + options.docCSSFile + '" /></head>') + '<body style="' + options.bodyStyle + '"></body></html>' ); doc.close(); // Work around for bug in IE which causes the editor to lose // focus when clicking below the end of the document. if (ie) $doc.click(function() {focus(editor);}); // Load the content updateFrame(editor); // Bind the ie specific iframe event handlers if (ie) { // Save the current user selection. This code is needed since IE will // reset the selection just after the beforedeactivate event and just // before the beforeactivate event. $doc.bind("beforedeactivate beforeactivate selectionchange keypress", function(e) { // Flag the editor as inactive if (e.type == "beforedeactivate") editor.inactive = true; // Get rid of the bogus selection and flag the editor as active else if (e.type == "beforeactivate") { if (!editor.inactive && editor.range && editor.range.length > 1) editor.range.shift(); delete editor.inactive; } // Save the selection when the editor is active else if (!editor.inactive) { if (!editor.range) editor.range = []; editor.range.unshift(getRange(editor)); // We only need the last 2 selections while (editor.range.length > 2) editor.range.pop(); } }); // Restore the text range when the iframe gains focus $frame.focus(function() { restoreRange(editor); }); } // Update the textarea when the iframe loses focus ($.browser.mozilla ? $doc : $(contentWindow)).blur(function() { updateTextArea(editor, true); }); // Enable the toolbar buttons as the user types or clicks $doc.click(hidePopups) .bind("keyup mouseup", function() { refreshButtons(editor); }); // Show the textarea for iPhone/iTouch/iPad or // the iframe when design mode is supported. if (iOS) editor.$area.show(); else $frame.show(); // Wait for the layout to finish - shortcut for $(document).ready() $(function() { var $toolbar = editor.$toolbar, $group = $toolbar.children("div:last"), wid = $main.width(); // Resize the toolbar var hgt = $group.offset().top + $group.outerHeight() - $toolbar.offset().top + 1; $toolbar.height(hgt); // Resize the iframe hgt = (/%/.test("" + options.height) ? $main.height() : parseInt(options.height)) - hgt; $frame.width(wid).height(hgt); // Resize the textarea. IE6 textareas have a 1px top // & bottom margin that cannot be removed using css. editor.$area.width(wid).height(ie6 ? hgt - 2 : hgt); // Switch the iframe into design mode if enabled disable(editor, editor.disabled); // Enable or disable the toolbar buttons refreshButtons(editor); }); } // refreshButtons - enables or disables buttons based on availability function refreshButtons(editor) { // Webkit requires focus before queryCommandEnabled will return anything but false if (!iOS && $.browser.webkit && !editor.focused) { editor.$frame[0].contentWindow.focus(); window.focus(); editor.focused = true; } // Get the object used for checking queryCommandEnabled var queryObj = editor.doc; if (ie) queryObj = getRange(editor); // Loop through each button var inSourceMode = sourceMode(editor); $.each(editor.$toolbar.find("." + BUTTON_CLASS), function(idx, elem) { var $elem = $(elem), button = $.cleditor.buttons[$.data(elem, BUTTON_NAME)], command = button.command, enabled = true; // Determine the state if (editor.disabled) enabled = false; else if (button.getEnabled) { var data = { editor: editor, button: elem, buttonName: button.name, popup: popups[button.popupName], popupName: button.popupName, command: button.command, useCSS: editor.options.useCSS }; enabled = button.getEnabled(data); if (enabled === undefined) enabled = true; } else if (((inSourceMode || iOS) && button.name != "source") || (ie && (command == "undo" || command == "redo"))) enabled = false; else if (command && command != "print") { if (ie && command == "hilitecolor") command = "backcolor"; // IE does not support inserthtml, so it's always enabled if (!ie || command != "inserthtml") { try {enabled = queryObj.queryCommandEnabled(command);} catch (err) {enabled = false;} } } // Enable or disable the button if (enabled) { $elem.removeClass(DISABLED_CLASS); $elem.removeAttr(DISABLED); } else { $elem.addClass(DISABLED_CLASS); $elem.attr(DISABLED, DISABLED); } }); } // restoreRange - restores the current ie selection function restoreRange(editor) { if (ie && editor.range) editor.range[0].select(); } // select - selects all the text in either the textarea or iframe function select(editor) { setTimeout(function() { if (sourceMode(editor)) editor.$area.select(); else execCommand(editor, "selectall"); }, 0); } // selectedHTML - returns the current HTML selection or and empty string function selectedHTML(editor) { restoreRange(editor); var range = getRange(editor); if (ie) return range.htmlText; var layer = $("<layer>")[0]; layer.appendChild(range.cloneContents()); var html = layer.innerHTML; layer = null; return html; } // selectedText - returns the current text selection or and empty string function selectedText(editor) { restoreRange(editor); if (ie) return getRange(editor).text; return getSelection(editor).toString(); } // showMessage - alert replacement function showMessage(editor, message, button) { var popup = createPopup("msg", editor.options, MSG_CLASS); popup.innerHTML = message; showPopup(editor, popup, button); } // showPopup - shows a popup function showPopup(editor, popup, button) { var offset, left, top, $popup = $(popup); // Determine the popup location if (button) { var $button = $(button); offset = $button.offset(); left = --offset.left; top = offset.top + $button.height(); } else { var $toolbar = editor.$toolbar; offset = $toolbar.offset(); left = Math.floor(($toolbar.width() - $popup.width()) / 2) + offset.left; top = offset.top + $toolbar.height() - 2; } // Position and show the popup hidePopups(); $popup.css({left: left, top: top}) .show(); // Assign the popup button and click event handler if (button) { $.data(popup, BUTTON, button); $popup.bind(CLICK, {popup: popup}, $.proxy(popupClick, editor)); } // Focus the first input element if any setTimeout(function() { $popup.find(":text,textarea").eq(0).focus().select(); }, 100); } // sourceMode - returns true if the textarea is showing function sourceMode(editor) { return editor.$area.is(":visible"); } // updateFrame - updates the iframe with the textarea contents function updateFrame(editor, checkForChange) { var code = editor.$area.val(), options = editor.options, updateFrameCallback = options.updateFrame, $body = $(editor.doc.body); // Check for textarea change to avoid unnecessary firing // of potentially heavy updateFrame callbacks. if (updateFrameCallback) { var sum = checksum(code); if (checkForChange && editor.areaChecksum == sum) return; editor.areaChecksum = sum; } // Convert the textarea source code into iframe html var html = updateFrameCallback ? updateFrameCallback(code) : code; // Prevent script injection attacks by html encoding script tags html = html.replace(/<(?=\/?script)/ig, "&lt;"); // Update the iframe checksum if (options.updateTextArea) editor.frameChecksum = checksum(html); // Update the iframe and trigger the change event if (html != $body.html()) { $body.html(html); $(editor).triggerHandler(CHANGE); } } // updateTextArea - updates the textarea with the iframe contents function updateTextArea(editor, checkForChange) { var html = $(editor.doc.body).html(), options = editor.options, updateTextAreaCallback = options.updateTextArea, $area = editor.$area; // Check for iframe change to avoid unnecessary firing // of potentially heavy updateTextArea callbacks. if (updateTextAreaCallback) { var sum = checksum(html); if (checkForChange && editor.frameChecksum == sum) return; editor.frameChecksum = sum; } // Convert the iframe html into textarea source code var code = updateTextAreaCallback ? updateTextAreaCallback(html) : html; // Update the textarea checksum if (options.updateFrame) editor.areaChecksum = checksum(code); // Update the textarea and trigger the change event if (code != $area.val()) { $area.val(code); $(editor).triggerHandler(CHANGE); } } })(jQuery);
src/components/EmployeeList.js
goblinbr/manager-react-native-app
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { ListView, ScrollView } from 'react-native'; import { employeesFetch } from '../actions'; import { EmployeeListItem, CardSection } from '.'; import AddEmployeeButton from './AddEmployeeButton'; import LogoutButton from './LogoutButton'; class EmployeeList extends Component { static navigationOptions = { title: 'Employees', headerRight: <LogoutButton />, headerLeft: null }; componentWillMount() { this.props.employeesFetch(); this.createDataSource(this.props); } componentWillReceiveProps(nextProps) { this.createDataSource(nextProps); } createDataSource({ employees }) { const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }); this.dataSource = ds.cloneWithRows(employees); } renderRow(employee) { return <EmployeeListItem employee={employee} />; } render() { return ( <ScrollView> <CardSection> <AddEmployeeButton /> </CardSection> <ListView enableEmptySections dataSource={this.dataSource} renderRow={this.renderRow} /> </ScrollView> ); } } const mapStateToProps = (state) => { let employees = []; const stateEmployees = state.employees; if (stateEmployees) { employees = Object.keys(stateEmployees).map((uid) => { const val = stateEmployees[uid]; return { ...val, uid }; }); } return { employees }; }; const EmployeeListConnect = connect(mapStateToProps, { employeesFetch })(EmployeeList); export { EmployeeListConnect as EmployeeList };
app/index.js
yashprit/mongoment
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router, hashHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import routes from './routes'; import configureStore from './store/configureStore'; import './app.global.css'; import 'react-toolbox/lib/commons.scss'; const store = configureStore(); const history = syncHistoryWithStore(hashHistory, store); render( <Provider store={store}> <Router history={history} routes={routes} /> </Provider>, document.getElementById('root') );
src/components/contact_form.js
josh-mallett/NICU-Moms-of-Louisiana-Website
import React, { Component } from 'react'; import { Field, reduxForm, reset } from 'redux-form'; import { post } from 'axios'; class ContactForm extends Component { constructor(props) { super(props); // State holds the message that will display after the form is submitted. // (Success or Failure) this.state = { submit_message: '', submit_message_color: '' } } // Function that renders all input fields that are present in the form. renderInput(field) { // Returns an input with proper placeholders. // Input calls validation method once user enters and leaves the input, and // displays appropriate error message if something is wrong. // ...field.input is an object that contains predefined event handlers return ( <div> <input type="text" placeholder={field.placeholder} {...field.input} /> <span className={field.cssClass}>{field.meta.touched ? field.meta.error : ''}</span> </div> ) } // Function that renders all textarea fields that are present in the form. renderTextArea(field) { // Returns an textarea with proper placeholders. // Input calls validation method once user enters and leaves the input, and // displays appropriate error message if something is wrong. return ( <div> <textarea placeholder={field.placeholder} {...field.input} /> <span className={field.cssClass}>{field.meta.touched ? field.meta.error : ''}</span> </div> ) } // Function that takes in response sent from server and updates the page to let the user know // if their form was accepted and sent successfully. renderSubmitMessage(response) { if (response == 'Success!') { this.setState ({ submit_message: 'Form submitted successfully!', submit_message_color: 'rgb(10, 255, 104)' }); } else if (response == 'Failure!') { this.setState ({ submit_message: 'Something went wrong, please check your input and try again.', submit_message_color: 'red' }); } } // Function that handles sending the form data to the backend once the user submits // the form. onSubmit(values) { // Formdata object stores the values entered by the user in a better form to be sent // to the server. let formData = new FormData(); // Declare content type and url of PHP file. const config = { headers: { 'content-type': 'application/json' } } const url = 'https://josh-mallett.com/php/index.php'; // Weird requirement to work inside of the post function. var self = this; // Insert all form data into Formdata object. formData.append('first_name', values.first_name); formData.append('last_name', values.last_name); formData.append('email', values.email); formData.append('subject', values.subject); formData.append('message', values.message); // Axios post function: sends data to server and recieves response via AJAX. // POST to server. post(url, formData, config) // Then recieve response .then(function(response) { // Output success or failure message to console. console.log(response.data); // Calls renderSubmitMessage function using self as a reference to the // whole ContactForm Component itself, rather than just this post function. self.renderSubmitMessage(response.data.toString()); }) .catch(function(error) { // Catch any thrown error and console log it. console.log(error); }); } render() { const { handleSubmit } = this.props; var style = { color: this.state.submit_message_color, 'font-family': "Lato" } return ( <div className="contact_form"> <form onSubmit={handleSubmit(this.onSubmit.bind(this))}> <div className="form_content"> <li id="fn"> <Field name="first_name" component={this.renderInput} placeholder="First Name" cssClass="first_name" /> </li> <li id="ln"> <Field name="last_name" component={this.renderInput} placeholder="Last Name" cssClass="last_name" /> </li> <li> <Field name="email" component={this.renderInput} placeholder="someone@example.com" cssClass="email" /> </li> <li> <Field name="subject" component={this.renderInput} placeholder="Subject" cssClass="subject" /> </li> <li> <Field name="message" component={this.renderTextArea} placeholder="My message is..." cssClass="message" /> </li> <li> <input className="button_submit" type="submit" value="SUBMIT"> </input> <div className="submit_message" style={style}> {this.state.submit_message}</div> </li> </div> </form> </div> ); } } function validate(values) { const errors = {}; const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if (!values.first_name) { errors.first_name = "Please enter your first name."; } if (!values.last_name) { errors.last_name = "Please enter your last name."; } if (!values.email || !emailRegex.test(values.email)) { errors.email = "Please enter a valid email address."; } if (!values.subject) { errors.subject = "Please enter a message subject."; } if (!values.last_name) { errors.last_name = "Please enter your last name."; } if (!values.message) { errors.message = "Please enter a message."; } return errors; } const afterSubmit = (result, dispatch) => { dispatch(reset('contact')); } // Glue code export default reduxForm({ validate, form: 'contact', onSubmitSuccess: afterSubmit })(ContactForm);
src/media/js/addon/containers/dashboardDetail.js
mozilla/marketplace-submission
/* Dashboard page for a single add-on. */ import React from 'react'; import {connect} from 'react-redux'; import {ReverseLink} from 'react-router-reverse'; import {bindActionCreators} from 'redux'; import AddonVersionListingContainer from './versionListing'; import {changeSlug, fetch as fetchAddon} from '../actions/addon'; import {del as deleteAddon} from '../actions/dashboard'; import {messageChange, submitVersion} from '../actions/submitVersion'; import {Addon, AddonIcon, AddonForDashboardDetail} from '../components/addon'; import SlugChange from '../components/slugChange'; import AddonSubnav from '../components/subnav'; import AddonUpload from '../components/upload'; import ConfirmButton from '../../site/components/confirmButton'; import {Page, PageSection} from '../../site/components/page'; export class AddonDashboardDetail extends React.Component { static contextTypes = { store: React.PropTypes.object }; static propTypes = { addon: React.PropTypes.object, fetchAddon: React.PropTypes.func.isRequired, deleteAddon: React.PropTypes.func.isRequired, isSubmitting: React.PropTypes.bool, messageChange: React.PropTypes.func.isRequired, slug: React.PropTypes.string.isRequired, submit: React.PropTypes.func.isRequired, uploadLoaded: React.PropTypes.number, uploadTotal: React.PropTypes.number, user: React.PropTypes.object, validationError: React.PropTypes.string, }; constructor(props) { super(props); this.props.fetchAddon(this.props.slug); } handleDelete = () => { this.props.deleteAddon(this.props.addon.slug); } renderDeleted() { return ( <PageSection> <p> This add-on has been deleted. <ReverseLink to="addon-dashboard"> Return to My Add-ons</ReverseLink> </p> </PageSection> ); } renderCannotDelete() { return ( <p>This add-on has been blocked and thus cannot be deleted.</p> ); } renderDeleteMessage() { return ( <p> Deleting your add-on will permanently delete it from Marketplace. There is no going back. </p> ); } render() { if (!this.props.addon || !this.props.addon.slug) { return ( <Page subnav={<AddonSubnav user={this.props.user}/>} title="Loading Firefox OS Add-on..."/> ); } const title = ( <div className="addon-page-title"> <AddonIcon icons={this.props.addon.icons}/> {this.props.addon.name} </div> ); return ( <Page breadcrumbText="My Add-ons" breadcrumbTo="addon-dashboard" className="addon-dashboard-detail" subnav={<AddonSubnav user={this.props.user}/>} title={title}> {this.props.addon.deleted && this.renderDeleted()} {!this.props.addon.deleted && <div> <AddonForDashboardDetail className="addon-dashboard-detail--versions" showDeveloperActions={true} {...this.props.addon}/> <AddonVersionListingContainer className="addon-dashboard-detail--versions" showDeveloperActions={true}/> <PageSection title="Upload a New Version"> <AddonUpload {...this.props}/> </PageSection> <PageSection title="Available Actions" className="addon-dashboard-detail--actions"> <p>You can perform the following actions on this add-on:</p> <ul> <li> <SlugChange addonId={this.props.addon.id} changeSlug={this.props.changeSlug} error={this.props.addon.changeSlugError} isProcessing={this.props.addon.isChangingSlug} slug={this.props.addon.slug}/> </li> <li> <ConfirmButton className="button--delete" initialText="Delete add-on" isBlocked={this.props.addon.status === 'blocked'} onClick={this.handleDelete} processingText="Deleting add-on&hellip;"/> {this.props.addon.status === 'blocked' ? this.renderCannotDelete() : this.renderDeleteMessage()} </li> </ul> </PageSection> </div> } </Page> ); } }; export default connect( state => ({ ...state.addonSubmitVersion, addon: state.addon.addons[state.router.params.slug], slug: state.router.params.slug, }), dispatch => bindActionCreators({ changeSlug, fetchAddon, deleteAddon, messageChange, submit: submitVersion }, dispatch) )(AddonDashboardDetail);
src/svg-icons/editor/border-right.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBorderRight = (props) => ( <SvgIcon {...props}> <path d="M7 21h2v-2H7v2zM3 5h2V3H3v2zm4 0h2V3H7v2zm0 8h2v-2H7v2zm-4 8h2v-2H3v2zm8 0h2v-2h-2v2zm-8-8h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm8 8h2v-2h-2v2zm4-4h2v-2h-2v2zm4-10v18h2V3h-2zm-4 18h2v-2h-2v2zm0-16h2V3h-2v2zm-4 8h2v-2h-2v2zm0-8h2V3h-2v2zm0 4h2V7h-2v2z"/> </SvgIcon> ); EditorBorderRight = pure(EditorBorderRight); EditorBorderRight.displayName = 'EditorBorderRight'; EditorBorderRight.muiName = 'SvgIcon'; export default EditorBorderRight;
node_modules/bs-recipes/recipes/gulp.task.sequence/gulpfile.js
nep0muck/cavita-bremen
var gulp = require('gulp'); var browserSync = require('browser-sync'); var sass = require('gulp-sass'); var reload = browserSync.reload; var through = require("through2"); /** * A slow task */ gulp.task('slow1', function () { return gulp.src('./app/*.html') .pipe(slowStream()); }); /** * Another Slow task */ gulp.task('slow2', function () { return gulp.src('./app/*.html') .pipe(slowStream()); }); /** * Separate task for the reaction to a file change */ gulp.task('html-watch', ['slow1', 'slow2'], reload); /** * Sass task for live injecting into all browsers */ gulp.task('sass', function () { return gulp.src('./app/scss/*.scss') .pipe(sass()) .pipe(gulp.dest('./app/css')) .pipe(reload({stream: true})); }); /** * Serve and watch the html files for changes */ gulp.task('default', function () { browserSync({server: './app'}); gulp.watch('./app/scss/*.scss', ['sass']); gulp.watch('./app/*.html', ['html-watch']); }); /** * Simulate a slow task */ function slowStream () { return through.obj(function (file, enc, cb) { this.push(file); setTimeout(cb, 2000); }); }
public/src/containers/calendar/calendar.js
white87332/react-redux-sample
import React from 'react'; import update from 'immutability-helper'; import { connect } from 'react-redux'; import equal from 'deep-equal'; import './calendar.scss'; // has params state function mapStateToProps() { return {}; } // has params dispatch function mapDispatchToProps() { return {}; } class Calendar extends React.Component { constructor(props, context) { super(props, context); this.preYear = this.preYear.bind(this); this.nextYear = this.nextYear.bind(this); this.preMonth = this.preMonth.bind(this); this.nextMonth = this.nextMonth.bind(this); this.today = this.today.bind(this); const d = new Date(); this.state = { year: d.getFullYear(), month: d.getMonth() + 1 }; } shouldComponentUpdate(nextProps, nextState) { if (equal(this.state, nextState)) { return false; } else { return true; } } // isLeapYear(year) // { // if (0 === year % 400 || (0 === year % 4 && 0 !== year % 100)) // { // return true; // } // else // { // return false; // } // } // // maxDayOfDate(year, month) // { // if (1 === month || 3 === month || 5 === month || 7 === month || 8 === month || 10 === month || 12 === month) // { // return 31; // } // else if (4 === month || 6 === month || 9 === month || 11 === month) // { // return 30; // } // else // { // if (this.isLeapYear(year)) // { // return 29; // } // else // { // return 28; // } // } // } // getStartDate(d) // { // d.setDate(1); // return d; // } // // getEndDate(d) // { // let totalDays = maxDayOfDate(parseInt(d.getFullYear()), parseInt(d.getMonth() + 1)); // d.setDate(totalDays); // return d; // } preYear() { const { year } = this.state; this.setState(update(this.state, { year: { $set: year - 1 } })); } nextYear() { const { year } = this.state; this.setState(update(this.state, { year: { $set: year + 1 } })); } preMonth() { let { year, month } = this.state; month -= 1; if (month === 0) { year -= 1; month = 12; } this.setState(update(this.state, { year: { $set: year }, month: { $set: month } })); } nextMonth() { let { year, month } = this.state; month += 1; if (month === 13) { year += 1; month = 1; } this.setState(update(this.state, { year: { $set: year }, month: { $set: month } })); } today() { this.setState(update(this.state, { year: { $set: new Date().getFullYear() }, month: { $set: new Date().getMonth() + 1 } })); } renderTr() { const { year, month } = this.state; const dayFormat = new Date(year, month, 0).toString().split(' '); const whatDay = dayFormat[0]; const totalDays = parseInt(dayFormat[2], 10); for (let i = 1; i <= totalDays; i += 1) { // if (1 == i % 7 || 1 == i) // { // // } switch (whatDay) { case 'Tue': break; case 'Wed': break; case 'Thu': break; case 'Fri': break; case 'Sat': break; case 'Sun': break; default: } } } render() { const { year, month } = this.state; return ( <div className="calendar"> <div className="btns"> <div><input type="button" value="去年" onClick={() => this.preYear()} />{year}年</div> <div><input type="button" value="明年" onClick={() => this.nextYear()} /></div> <div><input type="button" value="上月" onClick={() => this.preMonth()} />&nbsp; {month}月&nbsp;</div> <div><input type="button" value="下月" onClick={() => this.nextMonth()} /></div> <div><input type="button" value="今天" onClick={() => this.today()} /></div> </div> <div className="day"> <div>星期一</div> <div>星期二</div> <div>星期三</div> <div>星期四</div> <div>星期五</div> <div>星期六</div> <div>星期日</div> </div> <div className="total"> {this.renderTr()} </div> </div> ); } } export default connect(mapStateToProps, mapDispatchToProps)(Calendar);
frontend/src/Settings/General/AnalyticSettings.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React from 'react'; import FieldSet from 'Components/FieldSet'; import FormGroup from 'Components/Form/FormGroup'; import FormInputGroup from 'Components/Form/FormInputGroup'; import FormLabel from 'Components/Form/FormLabel'; import { inputTypes, sizes } from 'Helpers/Props'; function AnalyticSettings(props) { const { settings, onInputChange } = props; const { analyticsEnabled } = settings; return ( <FieldSet legend="Analytics"> <FormGroup size={sizes.MEDIUM}> <FormLabel>Send Anonymous Usage Data</FormLabel> <FormInputGroup type={inputTypes.CHECK} name="analyticsEnabled" helpText="Send anonymous usage and error information to Lidarr's servers. This includes information on your browser, which Lidarr WebUI pages you use, error reporting as well as OS and runtime version. We will use this information to prioritize features and bug fixes." helpTextWarning="Requires restart to take effect" onChange={onInputChange} {...analyticsEnabled} /> </FormGroup> </FieldSet> ); } AnalyticSettings.propTypes = { settings: PropTypes.object.isRequired, onInputChange: PropTypes.func.isRequired }; export default AnalyticSettings;
app/components/malt/OG.js
MitchLillie/brewhome
import React from 'react' const OG = React.createClass({ render: function () { return ( <div className='calculated-og'> <h2>OG = {this.props.og}</h2> </div> ) } }) export default OG
test/specs/elements/Image/Image-test.js
shengnian/shengnian-ui-react
import _ from 'lodash' import React from 'react' import Image from 'src/elements/Image/Image' import ImageGroup from 'src/elements/Image/ImageGroup' import { SUI } from 'src/lib' import Dimmer from 'src/modules/Dimmer/Dimmer' import * as common from 'test/specs/commonTests' describe('Image', () => { common.isConformant(Image) common.hasSubComponents(Image, [ImageGroup]) common.hasUIClassName(Image) common.rendersChildren(Image) common.implementsCreateMethod(Image) common.implementsLabelProp(Image) common.implementsShorthandProp(Image, { propKey: 'dimmer', ShorthandComponent: Dimmer, mapValueToProps: val => ({ content: val }), }) common.implementsVerticalAlignProp(Image) common.propKeyAndValueToClassName(Image, 'floated', SUI.FLOATS) common.propKeyOnlyToClassName(Image, 'avatar') common.propKeyOnlyToClassName(Image, 'bordered') common.propKeyOnlyToClassName(Image, 'centered') common.propKeyOnlyToClassName(Image, 'circular') common.propKeyOnlyToClassName(Image, 'disabled') common.propKeyOnlyToClassName(Image, 'fluid') common.propKeyOnlyToClassName(Image, 'hidden') common.propKeyOnlyToClassName(Image, 'inline') common.propKeyOnlyToClassName(Image, 'rounded') common.propKeyOrValueAndKeyToClassName(Image, 'spaced', ['left', 'right']) common.propValueOnlyToClassName(Image, 'size', SUI.SIZES) it('renders an img tag', () => { shallow(<Image />) .type() .should.equal('img') }) describe('href', () => { it('renders an a tag', () => { shallow(<Image href='http://google.com' />) .type() .should.equal('a') }) }) describe('ui', () => { it('is true by default', () => { Image.defaultProps.should.have.any.keys('ui') Image.defaultProps.ui.should.equal(true) }) it('adds the "ui" className when true', () => { shallow(<Image ui />) .should.have.className('ui') }) it('removes the "ui" className when false', () => { shallow(<Image ui={false} />) .should.not.have.className('ui') }) }) describe('wrapped', () => { it('applies all img attribute props to the img tag', () => { const props = { src: 'http://g.co', alt: 'alt text', width: 10, height: '10' } const img = shallow(<Image {...props} wrapped />) .find('img') _.each(props, (val, key) => { img.should.have.prop(key, val) }) }) }) })
static/scripts/gis/gxp.js
julianprabhakar/eden_car
Ext.namespace("gxp"); gxp.util={_uniqueNames:{},getOGCExceptionText:function(a){var b;a&&a.exceptions?(b=[],Ext.each(a.exceptions,function(a){Ext.each(a.texts,function(a){b.push(a)})}),b=b.join("\n")):b="Unknown error (no exception report).";return b},dispatch:function(a,b,c){function d(){++g;g===f&&b.call(c,h)}function e(b){window.setTimeout(function(){a[b].apply(c,[d,h])})}b=b||Ext.emptyFn;c=c||this;for(var f=a.length,g=0,h={},k=0;k<f;++k)e(k)},uniqueName:function(a,b){b=b||" ";var c=new RegExp(b+"[0-9]*$"),d=a.replace(c, ""),c=c.exec(a),c=void 0!==this._uniqueNames[d]?this._uniqueNames[d]:c instanceof Array?Number(c[0]):void 0,e=d;void 0!==c&&(c++,e+=b+c);this._uniqueNames[d]=c||0;return e},getAbsoluteUrl:function(a){var b;Ext.isIE6||Ext.isIE7||Ext.isIE8?(b=document.createElement("<a href='"+a+"'/>"),b.style.display="none",document.body.appendChild(b),b.href=b.href,document.body.removeChild(b)):(b=document.createElement("a"),b.href=a);return b.href},throttle:function(){var a=function(a,c,d){var e,f,g,h,k=function(){a.apply(d|| this,g);e=(new Date).getTime()};return function(){f=(new Date).getTime()-e;g=arguments;clearTimeout(h);!e||f>=c?k():h=setTimeout(k,c-f)}};return function(b,c,d){return a(b,c,d)}}(),md5:function(){function a(a){return String.fromCharCode(a&255)+String.fromCharCode(a>>>8&255)+String.fromCharCode(a>>>16&255)+String.fromCharCode(a>>>24&255)}function b(a){for(;0>a;)a+=4294967296;for(;4294967295<a;)a-=4294967296;return a}var c=[0,3614090360,3905402710,606105819,3250441966,4118548399,1200080426,2821735955, 4249261313,1770035416,2336552879,4294925233,2304563134,1804603682,4254626195,2792965006,1236535329,4129170786,3225465664,643717713,3921069994,3593408605,38016083,3634488961,3889429448,568446438,3275163606,4107603335,1163531501,2850285829,4243563512,1735328473,2368359562,4294588738,2272392833,1839030562,4259657740,2763975236,1272893353,4139469664,3200236656,681279174,3936430074,3572445317,76029189,3654602809,3873151461,530742520,3299628645,4096336452,1126891415,2878612391,4237533241,1700485571,2399980690, 4293915773,2240044497,1873313359,4264355552,2734768916,1309151649,4149444226,3174756917,718787259,3951481745],d=[[function(a,b,c){return a&b|~a&c},[[0,7,1],[1,12,2],[2,17,3],[3,22,4],[4,7,5],[5,12,6],[6,17,7],[7,22,8],[8,7,9],[9,12,10],[10,17,11],[11,22,12],[12,7,13],[13,12,14],[14,17,15],[15,22,16]]],[function(a,b,c){return a&c|b&~c},[[1,5,17],[6,9,18],[11,14,19],[0,20,20],[5,5,21],[10,9,22],[15,14,23],[4,20,24],[9,5,25],[14,9,26],[3,14,27],[8,20,28],[13,5,29],[2,9,30],[7,14,31],[12,20,32]]],[function(a, b,c){return a^b^c},[[5,4,33],[8,11,34],[11,16,35],[14,23,36],[1,4,37],[4,11,38],[7,16,39],[10,23,40],[13,4,41],[0,11,42],[3,16,43],[6,23,44],[9,4,45],[12,11,46],[15,16,47],[2,23,48]]],[function(a,b,c){return b^(a|~c)},[[0,6,49],[7,10,50],[14,15,51],[5,21,52],[12,6,53],[3,10,54],[10,15,55],[1,21,56],[8,6,57],[15,10,58],[6,15,59],[13,21,60],[4,6,61],[11,10,62],[2,15,63],[9,21,64]]]];return function(e){var f,g,h,k,l,m,q,n,s,r,t;f=[1732584193,4023233417,2562383102,271733878];g=e.length;h=g&63;k=56>h? 56-h:120-h;if(0<k)for(e+="\u0080",h=0;h<k-1;h++)e+="\x00";e+=a(8*g);e+=a(0);g+=k+8;k=[0,1,2,3];l=[16];m=[4];for(r=0;r<g;r+=64){h=0;for(s=r;16>h;h++,s+=4)l[h]=e.charCodeAt(s)|e.charCodeAt(s+1)<<8|e.charCodeAt(s+2)<<16|e.charCodeAt(s+3)<<24;for(h=0;4>h;h++)m[h]=f[h];for(h=0;4>h;h++)for(q=d[h][0],n=d[h][1],s=0;16>s;s++){t=l;var v=m,w=n[s],y=void 0,z=void 0,x=void 0,B=void 0,u=void 0,A=void 0,C=void 0,x=u=void 0,y=k[0],z=k[1],x=k[2],B=k[3],u=w[0],A=w[1],C=w[2],x=q(v[z],v[x],v[B]),u=v[y]+x+t[u]+c[C],u= b(u),u=u<<A|u>>>32-A,u=u+v[z];v[y]=b(u);t=k[0];k[0]=k[3];k[3]=k[2];k[2]=k[1];k[1]=t}for(h=0;4>h;h++)f[h]+=m[h],f[h]=b(f[h])}h=a(f[0])+a(f[1])+a(f[2])+a(f[3]);f="";for(e=0;16>e;e++)g=h.charCodeAt(e),f+="0123456789abcdef".charAt(g>>4&15),f+="0123456789abcdef".charAt(g&15);return f}}()};Ext.ns("Ext.ux.form"); Ext.ux.form.FileUploadField=Ext.extend(Ext.form.TextField,{buttonText:"Browse...",buttonOnly:!1,buttonOffset:3,readOnly:!0,autoSize:Ext.emptyFn,initComponent:function(){Ext.ux.form.FileUploadField.superclass.initComponent.call(this);this.addEvents("fileselected")},onRender:function(a,b){Ext.ux.form.FileUploadField.superclass.onRender.call(this,a,b);this.wrap=this.el.wrap({cls:"x-form-field-wrap x-form-file-wrap"});this.el.addClass("x-form-file-text");this.el.dom.removeAttribute("name");this.createFileInput(); var c=Ext.applyIf(this.buttonCfg||{},{text:this.buttonText});this.button=new Ext.Button(Ext.apply(c,{renderTo:this.wrap,cls:"x-form-file-btn"+(c.iconCls?" x-btn-icon":"")}));this.buttonOnly&&(this.el.hide(),this.wrap.setWidth(this.button.getEl().getWidth()));this.bindListeners();this.resizeEl=this.positionEl=this.wrap},bindListeners:function(){this.fileInput.on({scope:this,mouseenter:function(){this.button.addClass(["x-btn-over","x-btn-focus"])},mouseleave:function(){this.button.removeClass(["x-btn-over", "x-btn-focus","x-btn-click"])},mousedown:function(){this.button.addClass("x-btn-click")},mouseup:function(){this.button.removeClass(["x-btn-over","x-btn-focus","x-btn-click"])},change:function(){var a=this.fileInput.dom.value;this.setValue(a);this.fireEvent("fileselected",this,a)}})},createFileInput:function(){this.fileInput=this.wrap.createChild({id:this.getFileInputId(),name:this.name||this.getId(),cls:"x-form-file",tag:"input",type:"file",size:1})},reset:function(){this.fileInput.remove();this.createFileInput(); this.bindListeners();Ext.ux.form.FileUploadField.superclass.reset.call(this)},getFileInputId:function(){return this.id+"-file"},onResize:function(a,b){Ext.ux.form.FileUploadField.superclass.onResize.call(this,a,b);this.wrap.setWidth(a);this.buttonOnly||(a=this.wrap.getWidth()-this.button.getEl().getWidth()-this.buttonOffset,this.el.setWidth(a))},onDestroy:function(){Ext.ux.form.FileUploadField.superclass.onDestroy.call(this);Ext.destroy(this.fileInput,this.button,this.wrap)},onDisable:function(){Ext.ux.form.FileUploadField.superclass.onDisable.call(this); this.doDisable(!0)},onEnable:function(){Ext.ux.form.FileUploadField.superclass.onEnable.call(this);this.doDisable(!1)},doDisable:function(a){this.fileInput.dom.disabled=a;this.button.setDisabled(a)},preFocus:Ext.emptyFn,alignErrorIcon:function(){this.errorIcon.alignTo(this.wrap,"tl-tr",[2,0])}});Ext.reg("fileuploadfield",Ext.ux.form.FileUploadField);Ext.form.FileUploadField=Ext.ux.form.FileUploadField;Ext.namespace("gxp.plugins"); gxp.plugins.LayerSource=Ext.extend(Ext.util.Observable,{store:null,lazy:!1,hidden:!1,title:"",constructor:function(a){this.initialConfig=a;Ext.apply(this,a);this.addEvents("ready","failure");gxp.plugins.LayerSource.superclass.constructor.apply(this,arguments)},init:function(a){this.target=a;this.createStore()},getMapProjection:function(){var a=this.target.mapPanel.map.projection;return this.target.mapPanel.map.getProjectionObject()||a&&new OpenLayers.Projection(a)||new OpenLayers.Projection("EPSG:4326")}, getProjection:function(a){a=a.getLayer();var b=this.getMapProjection();return(a.projection?a.projection instanceof OpenLayers.Projection?a.projection:new OpenLayers.Projection(a.projection):b).equals(b)?b:null},createStore:function(){this.fireEvent("ready",this)},createLayerRecord:function(a){},getConfigForRecord:function(a){var b=a.getLayer();return{source:a.get("source"),name:a.get("name"),title:a.get("title"),visibility:b.getVisibility(),opacity:b.opacity||void 0,group:a.get("group"),fixed:a.get("fixed"), selected:a.get("selected")}},getState:function(){return Ext.apply({},this.initialConfig)}});Ext.namespace("gxp.plugins"); gxp.plugins.Tool=Ext.extend(Ext.util.Observable,{ptype:"gxp_tool",autoActivate:!0,actionTarget:"map.tbar",showButtonText:!1,output:null,constructor:function(a){this.initialConfig=a||{};this.active=!1;Ext.apply(this,a);this.id||(this.id=Ext.id());this.output=[];this.addEvents("activate","deactivate");gxp.plugins.Tool.superclass.constructor.apply(this,arguments)},init:function(a){a.tools[this.id]=this;this.target=a;this.autoActivate&&this.activate();this.target.on("portalready",this.addActions,this)}, activate:function(){if(!1===this.active)return this.active=!0,this.fireEvent("activate",this),!0},deactivate:function(){if(!0===this.active)return this.active=!1,this.fireEvent("deactivate",this),!0},getContainer:function(a){var b,c;b=a.split(".");if(c=b[0])if("map"==c)a=this.target.mapPanel;else{if(a=Ext.getCmp(c)||this.target.portal[c],!a)throw Error("Can't find component with id: "+c);}else a=this.target.portal;if(b=1<b.length&&b[1])a=(c={tbar:"getTopToolbar",bbar:"getBottomToolbar",fbar:"getFooterToolbar"}[b])? a[c]():a[b];return a},addActions:function(a){if((a=a||this.actions)&&null!==this.actionTarget){var b=this.actionTarget instanceof Array?this.actionTarget:[this.actionTarget];a=a instanceof Array?a:[a];var c,d,e,f,g,h,k=null;for(e=b.length-1;0<=e;--e){if(c=b[e])c instanceof Object&&(k=c.index,c=c.target),h=this.getContainer(c);f=0;for(g=a.length;f<g;++f)if(a[f]instanceof Ext.Action||a[f]instanceof Ext.Component||((d=Ext.getCmp(a[f]))&&(a[f]=d),"string"!=typeof a[f]&&(f==this.defaultAction&&(a[f].pressed= !0),a[f]=new Ext.Action(a[f]))),c=a[f],f==this.defaultAction&&c instanceof GeoExt.Action&&(c.isDisabled()?c.activateOnEnable=!0:c.control.activate()),h){this.showButtonText&&c.setText(c.initialConfig.buttonText);h instanceof Ext.menu.Menu?c=Ext.apply(new Ext.menu.CheckItem(c),{text:c.initialConfig.menuText,group:c.initialConfig.toggleGroup,groupClass:null}):h instanceof Ext.Toolbar||(c=new Ext.Button(c));var l=null===k?h.add(c):h.insert(k,c);c=c instanceof Ext.Button?c:l;null!==k&&(k+=1);if(null!= this.outputAction&&f==this.outputAction)c.on("click",function(){d?this.outputTarget?d.show():d.ownerCt.ownerCt.show():d=this.addOutput()},this)}h&&(h.isVisible()?h.doLayout():h instanceof Ext.menu.Menu||h.show())}return this.actions=a}this.removeOutput();this.addOutput(this.outputConfig)},addOutput:function(a){if(a||this.outputConfig){a=a||{};var b=this.outputTarget;b?(b=this.getContainer(b),a instanceof Ext.Component||Ext.apply(a,this.outputConfig)):(b=this.outputConfig||{},b=(new Ext.Window(Ext.apply({hideBorders:!0, shadow:!1,closeAction:"hide",autoHeight:!b.height,layout:b.height?"fit":void 0,items:[{defaults:Ext.applyIf({autoHeight:!b.height&&!(b.defaults&&b.defaults.height)},b.defaults)}]},b))).show().items.get(0));if(b)return a=b.add(a),a.on("removed",function(a){this.output.remove(a)},this,{single:!0}),a instanceof Ext.Window?a.show():b.doLayout(),this.output.push(a),a;a=this.ptype;window.console&&console.error("Failed to create output for plugin with ptype: "+a)}},removeOutput:function(){for(var a,b=this.output.length- 1;0<=b;--b)if(a=this.output[b],this.outputTarget)if(a.ownerCt){if(a.ownerCt.remove(a),a.ownerCt instanceof Ext.Window)a.ownerCt[a.ownerCt.closeAction]()}else a.remove();else a.findParentBy(function(a){return a instanceof Ext.Window}).close();this.output=[]},getState:function(){return Ext.apply({},this.initialConfig)}});Ext.preg(gxp.plugins.Tool.prototype.ptype,gxp.plugins.Tool);Ext.namespace("gxp.plugins"); gxp.plugins.ZoomToExtent=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_zoomtoextent",menuText:"Zoom To Max Extent",tooltip:"Zoom To Max Extent",extent:null,closest:!0,iconCls:"gxp-icon-zoomtoextent",closest:!0,constructor:function(a){gxp.plugins.ZoomToExtent.superclass.constructor.apply(this,arguments);this.extent instanceof Array&&(this.extent=OpenLayers.Bounds.fromArray(this.extent))},addActions:function(){return gxp.plugins.ZoomToExtent.superclass.addActions.apply(this,[{text:this.buttonText,menuText:this.menuText, iconCls:this.iconCls,tooltip:this.tooltip,handler:function(){var a=this.target.mapPanel.map,b="function"==typeof this.extent?this.extent():this.extent;if(!b)for(var c,d=0,e=a.layers.length;d<e;++d)c=a.layers[d],c.getVisibility()&&(c=c.restrictedExtent||c.maxExtent,b?b.extend(c):c&&(b=c.clone()));b&&((d=a.restrictedExtent||a.maxExtent)&&(b=new OpenLayers.Bounds(Math.max(b.left,d.left),Math.max(b.bottom,d.bottom),Math.min(b.right,d.right),Math.min(b.top,d.top))),a.zoomToExtent(b,this.closest))},scope:this}])}}); Ext.preg(gxp.plugins.ZoomToExtent.prototype.ptype,gxp.plugins.ZoomToExtent);Ext.namespace("gxp.plugins"); gxp.plugins.ClickableFeatures=Ext.extend(gxp.plugins.Tool,{featureManager:null,autoLoadFeature:!1,autoLoadedFeature:null,toleranceParameters:["BUFFER","RADIUS"],constructor:function(a){a&&"autoLoadFeatures"in a&&(a.autoLoadFeature=a.autoLoadFeatures,delete a.autoLoadFeatures,window.console&&console.warn("Deprecated config option 'autoLoadFeatures' for ptype: '"+a.ptype+"'. Use 'autoLoadFeature' instead."));gxp.plugins.ClickableFeatures.superclass.constructor.apply(this,[a])},noFeatureClick:function(a){this.selectControl|| (this.selectControl=new OpenLayers.Control.SelectFeature(this.target.tools[this.featureManager].featureLayer,this.initialConfig.controlOptions));var b=this.target.mapPanel.map.getLonLatFromPixel(a.xy),c=this.target.tools[this.featureManager],d=c.page;if(!("all"==c.visible()&&c.paging&&d&&d.extent.containsLonLat(b))&&(b=c.layerRecord&&c.layerRecord.getLayer())){var e=this.target.mapPanel.map,d=e.getSize(),d=Ext.applyIf({REQUEST:"GetFeatureInfo",BBOX:e.getExtent().toBBOX(),WIDTH:d.w,HEIGHT:d.h,X:parseInt(a.xy.x), Y:parseInt(a.xy.y),QUERY_LAYERS:b.params.LAYERS,INFO_FORMAT:"application/vnd.ogc.gml",EXCEPTIONS:"application/vnd.ogc.se_xml",FEATURE_COUNT:1},b.params);if("number"===typeof this.tolerance)for(var f=0,g=this.toleranceParameters.length;f<g;++f)d[this.toleranceParameters[f]]=this.tolerance;e=e.getProjectionObject();(f=b.projection)&&f.equals(e)&&(e=f);1.3<=parseFloat(b.params.VERSION)?d.CRS=e.getCode():d.SRS=e.getCode();new GeoExt.data.FeatureStore({fields:{},proxy:new GeoExt.data.ProtocolProxy({protocol:new OpenLayers.Protocol.HTTP({url:"string"=== typeof b.url?b.url:b.url[0],params:d,format:new OpenLayers.Format.WMSGetFeatureInfo})}),autoLoad:!0,listeners:{load:function(b,d){if(0<d.length){var e=d[0].get("fid"),f=new OpenLayers.Filter.FeatureId({fids:[e]}),g=function(){c.loadFeatures(f,function(a){a.length&&(this.autoLoadedFeature=a[0],this.select(a[0]))},this)}.createDelegate(this),n=c.featureLayer.getFeatureByFid(e);n?this.select(n):c.paging&&c.pagingType===gxp.plugins.FeatureManager.QUADTREE_PAGING?(n=this.target.mapPanel.map.getLonLatFromPixel(a.xy), c.setPage({lonLat:n},function(){var a=c.featureLayer.getFeatureByFid(e);a?this.select(a):!0===this.autoLoadFeature&&g()},this)):g()}},scope:this}})}},select:function(a){this.selectControl.unselectAll();this.selectControl.select(a)}});Ext.namespace("gxp.plugins"); gxp.plugins.SelectedFeatureActions=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_selectedfeatureactions",addActions:function(){for(var a=this.target.tools[this.featureManager],b=this.actions.length,c=Array(b),d=this,e=0;e<b;++e)c[e]=Ext.apply({iconCls:"process",disabled:!0,handler:function(){var b=a.featureLayer.selectedFeatures[0],c=new Ext.Template(this.urlTemplate),e=Ext.applyIf(this.outputConfig||{},d.initialConfig.outputConfig);d.outputConfig=Ext.apply(e,{title:this.menuText,bodyCfg:{tag:"iframe", src:c.apply(Ext.applyIf({fid:b.fid.split(".").pop(),layer:a.layerRecord.get("name")},b.attributes)),style:{border:"0px none"}}});d.addOutput()}},this.actions[e]);a.featureLayer.events.on({featureselected:function(a){a=1!=a.feature.layer.selectedFeatures.length;for(var b=c.length-1;0<=b;--b)c[b].setDisabled(a)},featureunselected:function(a){if(0==a.feature.layer.selectedFeatures.length)for(a=c.length-1;0<=a;--a)c[a].disable()},scope:this});gxp.plugins.SelectedFeatureActions.superclass.addActions.apply(this, [c])}});Ext.preg(gxp.plugins.SelectedFeatureActions.prototype.ptype,gxp.plugins.SelectedFeatureActions);Ext.namespace("gxp.plugins"); gxp.plugins.MapQuestSource=Ext.extend(gxp.plugins.LayerSource,{ptype:"gxp_mapquestsource",title:"MapQuest Layers",osmAttribution:"Tiles Courtesy of <a href='http://open.mapquest.co.uk/' target='_blank'>MapQuest</a> <img src='http://developer.mapquest.com/content/osm/mq_logo.png' border='0'>",osmTitle:"MapQuest OpenStreetMap",naipAttribution:"Tiles Courtesy of <a href='http://open.mapquest.co.uk/' target='_blank'>MapQuest</a> <img src='http://developer.mapquest.com/content/osm/mq_logo.png' border='0'>",naipTitle:"MapQuest Imagery", createStore:function(){var a={projection:"EPSG:900913",maxExtent:new OpenLayers.Bounds(-2.00375083392E7,-2.00375083392E7,2.00375083392E7,2.00375083392E7),maxResolution:156543.03390625,numZoomLevels:19,units:"m",buffer:1,transitionEffect:"resize",tileOptions:{crossOriginKeyword:null}},a=[new OpenLayers.Layer.OSM(this.osmTitle,["http://otile1.mqcdn.com/tiles/1.0.0/map/${z}/${x}/${y}.png","http://otile2.mqcdn.com/tiles/1.0.0/map/${z}/${x}/${y}.png","http://otile3.mqcdn.com/tiles/1.0.0/map/${z}/${x}/${y}.png", "http://otile4.mqcdn.com/tiles/1.0.0/map/${z}/${x}/${y}.png"],OpenLayers.Util.applyDefaults({attribution:this.osmAttribution,type:"osm"},a)),new OpenLayers.Layer.OSM(this.naipTitle,["http://otile1.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.png","http://otile2.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.png","http://otile3.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.png","http://otile4.mqcdn.com/tiles/1.0.0/sat/${z}/${x}/${y}.png"],OpenLayers.Util.applyDefaults({attribution:this.naipAttribution,type:"naip"}, a))];this.store=new GeoExt.data.LayerStore({layers:a,fields:[{name:"source",type:"string"},{name:"name",type:"string",mapping:"type"},{name:"abstract",type:"string",mapping:"attribution"},{name:"group",type:"string",defaultValue:"background"},{name:"fixed",type:"boolean",defaultValue:!0},{name:"selected",type:"boolean"}]});this.store.each(function(a){a.set("group","background")});this.fireEvent("ready",this)},createLayerRecord:function(a){var b,c=this.store.findExact("name",a.name);-1<c&&(b=this.store.getAt(c).copy(Ext.data.Record.id({})), c=b.getLayer().clone(),a.title&&(c.setName(a.title),b.set("title",a.title)),"visibility"in a&&(c.visibility=a.visibility),b.set("selected",a.selected||!1),b.set("source",a.source),b.set("name",a.name),"group"in a&&b.set("group",a.group),b.data.layer=c,b.commit());return b}});Ext.preg(gxp.plugins.MapQuestSource.prototype.ptype,gxp.plugins.MapQuestSource);Ext.namespace("gxp"); gxp.FillSymbolizer=Ext.extend(Ext.FormPanel,{symbolizer:null,colorProperty:"fillColor",opacityProperty:"fillOpacity",colorManager:null,checkboxToggle:!0,defaultColor:null,border:!1,fillText:"Fill",colorText:"Color",opacityText:"Opacity",initComponent:function(){this.symbolizer||(this.symbolizer={});var a;this.colorManager&&(a=[new this.colorManager]);var b=100;this.opacityProperty in this.symbolizer?b=100*this.symbolizer[this.opacityProperty]:OpenLayers.Renderer.defaultSymbolizer[this.opacityProperty]&& (b=100*OpenLayers.Renderer.defaultSymbolizer[this.opacityProperty]);this.items=[{xtype:"fieldset",title:this.fillText,autoHeight:!0,checkboxToggle:this.checkboxToggle,collapsed:!0===this.checkboxToggle&&!1===this.symbolizer.fill,hideMode:"offsets",defaults:{width:100},items:[{xtype:"gxp_colorfield",fieldLabel:this.colorText,name:"color",emptyText:OpenLayers.Renderer.defaultSymbolizer[this.colorProperty],value:this.symbolizer[this.colorProperty],defaultBackground:this.defaultColor||OpenLayers.Renderer.defaultSymbolizer[this.colorProperty], plugins:a,listeners:{valid:function(a){a=a.getValue();var b=this.symbolizer[this.colorProperty]!=a;this.symbolizer[this.colorProperty]=a;b&&this.fireEvent("change",this.symbolizer)},scope:this}},{xtype:"slider",fieldLabel:this.opacityText,name:"opacity",values:[b],isFormField:!0,listeners:{changecomplete:function(a,b){this.symbolizer[this.opacityProperty]=b/100;this.fireEvent("change",this.symbolizer)},scope:this},plugins:[new GeoExt.SliderTip({getText:function(a){return a.value+"%"}})]}],listeners:{collapse:function(){!1!== this.symbolizer.fill&&(this.symbolizer.fill=!1,this.fireEvent("change",this.symbolizer))},expand:function(){this.symbolizer.fill=!0;this.fireEvent("change",this.symbolizer)},scope:this}}];this.addEvents("change");gxp.FillSymbolizer.superclass.initComponent.call(this)}});Ext.reg("gxp_fillsymbolizer",gxp.FillSymbolizer);Ext.namespace("gxp"); gxp.PointSymbolizer=Ext.extend(Ext.Panel,{symbolizer:null,graphicCircleText:"circle",graphicSquareText:"square",graphicTriangleText:"triangle",graphicStarText:"star",graphicCrossText:"cross",graphicXText:"x",graphicExternalText:"external",urlText:"URL",opacityText:"opacity",symbolText:"Symbol",sizeText:"Size",rotationText:"Rotation",pointGraphics:null,colorManager:null,external:null,layout:"form",initComponent:function(){this.symbolizer||(this.symbolizer={});this.pointGraphics||(this.pointGraphics= [{display:this.graphicCircleText,value:"circle",mark:!0},{display:this.graphicSquareText,value:"square",mark:!0},{display:this.graphicTriangleText,value:"triangle",mark:!0},{display:this.graphicStarText,value:"star",mark:!0},{display:this.graphicCrossText,value:"cross",mark:!0},{display:this.graphicXText,value:"x",mark:!0},{display:this.graphicExternalText}]);this.external=!!this.symbolizer.externalGraphic;this.markPanel=new Ext.Panel({border:!1,collapsed:this.external,layout:"form",items:[{xtype:"gxp_fillsymbolizer", symbolizer:this.symbolizer,labelWidth:this.labelWidth,labelAlign:this.labelAlign,colorManager:this.colorManager,listeners:{change:function(a){this.fireEvent("change",this.symbolizer)},scope:this}},{xtype:"gxp_strokesymbolizer",symbolizer:this.symbolizer,labelWidth:this.labelWidth,labelAlign:this.labelAlign,colorManager:this.colorManager,listeners:{change:function(a){this.fireEvent("change",this.symbolizer)},scope:this}}]});this.urlField=new Ext.form.TextField({name:"url",fieldLabel:this.urlText,value:this.symbolizer.externalGraphic, hidden:!this.external,listeners:{change:function(a,b){this.symbolizer.externalGraphic=b;this.fireEvent("change",this.symbolizer)},scope:this},width:100});this.graphicPanel=new Ext.Panel({border:!1,collapsed:!this.external,layout:"form",items:[this.urlField,{xtype:"slider",name:"opacity",fieldLabel:this.opacityText,value:[null==this.symbolizer.graphicOpacity?100:100*this.symbolizer.graphicOpacity],isFormField:!0,listeners:{changecomplete:function(a,b){this.symbolizer.graphicOpacity=b/100;this.fireEvent("change", this.symbolizer)},scope:this},plugins:[new GeoExt.SliderTip({getText:function(a){return a.value+"%"}})],width:100}]});this.items=[{xtype:"combo",name:"mark",fieldLabel:this.symbolText,store:new Ext.data.JsonStore({data:{root:this.pointGraphics},root:"root",fields:["value","display","preview",{name:"mark",type:"boolean"}]}),value:this.external?0:this.symbolizer.graphicName,displayField:"display",valueField:"value",tpl:new Ext.XTemplate('<tpl for="."><div class="x-combo-list-item gx-pointsymbolizer-mark-item"><tpl if="preview"><img src="{preview}" alt="{display}"/></tpl><span>{display}</span></div></tpl>'), mode:"local",allowBlank:!1,triggerAction:"all",editable:!1,listeners:{select:function(a,b){var c=b.get("mark"),d=b.get("value");c?(this.external&&(this.external=!1,delete this.symbolizer.externalGraphic,this.updateGraphicDisplay()),this.symbolizer.graphicName=d):(d?(this.urlField.hide(),this.symbolizer.externalGraphic=d):this.urlField.show(),this.external||(this.external=!0,c=this.urlField.getValue(),Ext.isEmpty(c)||(this.symbolizer.externalGraphic=c),delete this.symbolizer.graphicName,this.updateGraphicDisplay())); this.fireEvent("change",this.symbolizer)},scope:this},width:100},{xtype:"textfield",name:"size",fieldLabel:this.sizeText,value:this.symbolizer.pointRadius&&2*this.symbolizer.pointRadius,listeners:{change:function(a,b){this.symbolizer.pointRadius=b/2;this.fireEvent("change",this.symbolizer)},scope:this},width:100},{xtype:"textfield",name:"rotation",fieldLabel:this.rotationText,value:this.symbolizer.rotation,listeners:{change:function(a,b){this.symbolizer.rotation=b;this.fireEvent("change",this.symbolizer)}, scope:this},width:100},this.markPanel,this.graphicPanel];this.addEvents("change");gxp.PointSymbolizer.superclass.initComponent.call(this)},updateGraphicDisplay:function(){this.external?(this.markPanel.collapse(),this.graphicPanel.expand()):(this.graphicPanel.collapse(),this.markPanel.expand())}});Ext.reg("gxp_pointsymbolizer",gxp.PointSymbolizer);Ext.namespace("gxp.plugins"); gxp.plugins.Legend=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_legend",menuText:"Legend",tooltip:"Show Legend",actionTarget:null,constructor:function(a){gxp.plugins.Legend.superclass.constructor.apply(this,arguments);this.outputConfig||(this.outputConfig={width:300,height:400});Ext.applyIf(this.outputConfig,{title:this.menuText})},addActions:function(){return gxp.plugins.Legend.superclass.addActions.apply(this,[[{menuText:this.menuText,iconCls:"gxp-icon-legend",tooltip:this.tooltip,handler:function(){this.removeOutput(); this.addOutput(this.outputConfig)},scope:this}]])},getLegendPanel:function(){return this.output[0]},addOutput:function(a){return gxp.plugins.Legend.superclass.addOutput.call(this,Ext.apply({xtype:"gx_legendpanel",ascending:!1,border:!1,hideMode:"offsets",layerStore:this.target.mapPanel.layers,defaults:{cls:"gxp-legend-item"}},a))}});Ext.preg(gxp.plugins.Legend.prototype.ptype,gxp.plugins.Legend);Ext.namespace("gxp.plugins"); gxp.plugins.SchemaAnnotations={getAnnotationsFromSchema:function(a){var b=null;a=a.get("annotation");if(void 0!==a){var b={},c=GeoExt.Lang.locale.split("-").shift(),d,e;d=0;for(e=a.appinfo.length;d<e;++d){var f=Ext.decode(a.appinfo[d]);if(f.title&&f.title[c]){b.label=f.title[c];break}}d=0;for(e=a.documentation.length;d<e;++d)if(a.documentation[d].lang===c){b.helpText=a.documentation[d].textContent;break}}return b}};Ext.namespace("gxp.plugins"); gxp.plugins.FormFieldHelp=Ext.extend(Object,{ptype:"gxp_formfieldhelp",helpText:null,dismissDelay:5E3,constructor:function(a){Ext.apply(this,a)},init:function(a){this.target=a;a.on("render",this.showHelp,this)},showHelp:function(){var a;a=this.target.label?this.target.label:this.target.getEl();Ext.QuickTips.register({target:a,dismissDelay:this.dismissDelay,text:this.helpText})}});Ext.preg(gxp.plugins.FormFieldHelp.prototype.ptype,gxp.plugins.FormFieldHelp);Ext.namespace("gxp.plugins"); gxp.plugins.FeatureEditorForm=Ext.extend(Ext.FormPanel,{ptype:"gxp_editorform",xtype:"gxp_editorform",feature:null,schema:null,fieldConfig:null,fields:null,excludeFields:null,propertyNames:null,readOnly:null,monitorValid:!0,initComponent:function(){this.defaults=Ext.apply(this.defaults||{},{readOnly:!0});this.listeners={clientvalidation:function(a,b){b&&this.getForm().isDirty()&&(Ext.apply(this.feature.attributes,this.getForm().getFieldValues()),this.featureEditor.setFeatureState(this.featureEditor.getDirtyState()))}, scope:this};gxp.plugins.FeatureEditorForm.superclass.initComponent.call(this);this.excludeFields||(this.excludeFields=[]);var a=[],b,c;b=0;for(c=this.excludeFields.length;b<c;++b)a[b]=this.excludeFields[b].toLowerCase();this.excludeFields=a;var d=this.fields?this.fields.join(",").toUpperCase().split(","):[],e={};if(this.schema)this.schema.each(function(a){var b=a.get("name"),c=b.toLowerCase();this.fields&&-1==d.indexOf(b.toUpperCase())&&this.excludeFields.push(c);if(-1==this.excludeFields.indexOf(c)&& !a.get("type").match(/^[^:]*:?((Multi)?(Point|Line|Polygon|Curve|Surface|Geometry))/)){var f=GeoExt.form.recordToField(a);a=this.getAnnotationsFromSchema(a);null!==a&&(a.helpText&&(f.plugins||(f.plugins=[]),f.plugins.push({ptype:"gxp_formfieldhelp",helpText:a.helpText})),a.label&&(f.fieldLabel=a.label));f.fieldLabel=this.propertyNames?this.propertyNames[b]||f.fieldLabel:f.fieldLabel;this.fieldConfig&&this.fieldConfig[b]&&Ext.apply(f,this.fieldConfig[b]);void 0!==this.feature.attributes[b]&&(f.value= this.feature.attributes[b]);f.value&&"checkbox"==f.xtype&&(f.checked=Ext.isBoolean(f.value)?f.value:"true"===f.value);f.value&&"gxp_datefield"==f.xtype&&(f.value=new Date(1E3*f.value));f.value&&"datefield"==f.xtype&&(f.format="Y-m-d",f.value=Date.parseDate(f.value.replace(/Z$/,""),"Y-m-d"));"combo"===f.xtype&&Ext.applyIf(f,{store:new Ext.data.ArrayStore({fields:["id","value"],data:f.comboStoreData}),displayField:"value",valueField:"id",mode:"local",triggerAction:"all"});e[c]=f}},this);else{var e= {},f;for(f in this.feature.attributes)a=f.toLowerCase(),this.fields&&-1==d.indexOf(f.toUpperCase())&&this.excludeFields.push(a),-1===this.excludeFields.indexOf(a)&&(e[a]={xtype:"textfield",fieldLabel:this.propertyNames?this.propertyNames[f]||f:f,name:f,value:this.feature.attributes[f]})}this.add(this.reorderFields(e))},reorderFields:function(a){var b=[];if(this.fields)for(var c=0,d=this.fields.length;c<d;++c)a[this.fields[c].toLowerCase()]&&b.push(a[this.fields[c].toLowerCase()]);else for(c in a)b.push(a[c]); return b},init:function(a){this.featureEditor=a;this.featureEditor.on("startedit",this.onStartEdit,this);this.featureEditor.on("stopedit",this.onStopEdit,this);this.featureEditor.on("canceledit",this.onCancelEdit,this);this.featureEditor.add(this);this.featureEditor.doLayout()},destroy:function(){this.featureEditor.un("startedit",this.onStartEdit,this);this.featureEditor.un("stopedit",this.onStopEdit,this);this.featureEditor.un("canceledit",this.onCancelEdit,this);this.featureEditor=null;gxp.plugins.FeatureEditorForm.superclass.destroy.call(this)}, onStartEdit:function(){this.getForm().items.each(function(a){!0!==this.readOnly&&a.setReadOnly(!1)},this)},onStopEdit:function(){this.getForm().items.each(function(a){a.setReadOnly(!0)})},onCancelEdit:function(a,b){if(b){var c=this.getForm(),d;for(d in b.attributes){var e=c.findField(d);e&&e.setValue(b.attributes[d])}}}});Ext.override(gxp.plugins.FeatureEditorForm,gxp.plugins.SchemaAnnotations);Ext.preg(gxp.plugins.FeatureEditorForm.prototype.ptype,gxp.plugins.FeatureEditorForm); Ext.reg(gxp.plugins.FeatureEditorForm.prototype.xtype,gxp.plugins.FeatureEditorForm);Ext.namespace("gxp.data"); gxp.data.WFSProtocolProxy=Ext.extend(GeoExt.data.ProtocolProxy,{setFilter:function(a){this.protocol.filter=a;this.protocol.options.filter=a},constructor:function(a){Ext.applyIf(a,{version:"1.1.0"});this.protocol&&this.protocol instanceof OpenLayers.Protocol||(a.protocol=new OpenLayers.Protocol.WFS(Ext.apply({version:a.version,srsName:a.srsName,url:a.url,featureType:a.featureType,featureNS:a.featureNS,geometryName:a.geometryName,schema:a.schema,filter:a.filter,maxFeatures:a.maxFeatures,multi:a.multi}, a.protocol)));gxp.data.WFSProtocolProxy.superclass.constructor.apply(this,arguments)},doRequest:function(a,b,c,d,e,f,g){delete c.xaction;if(a===Ext.data.Api.actions.read)this.load(c,d,e,f,g);else{b instanceof Array||(b=[b]);var h=Array(b.length),k;Ext.each(b,function(a,b){h[b]=a.getFeature();k=h[b];k.modified=Ext.apply(k.modified||{},{attributes:Ext.apply(k.modified&&k.modified.attributes||{},a.modified)})},this);var l={action:a,records:b,callback:e,scope:f};a={callback:function(a){this.onProtocolCommit(a, l)},scope:this};Ext.applyIf(a,c);this.protocol.commit(h,a)}},onProtocolCommit:function(a,b){if(a.success()){var c=a.reqFeatures,d,e,f=[],g=a.insertIds||[],h,k,l=0;h=0;for(k=c.length;h<k;++h)if(e=c[h],d=e.state)d==OpenLayers.State.DELETE?f.push(e):d==OpenLayers.State.INSERT?(e.fid=g[l],++l):e.modified&&(e.modified={}),e.state=null;h=0;for(k=f.length;h<k;++h)e=f[h],e.layer&&e.layer.destroyFeatures([e]);k=c.length;d=Array(k);for(h=0;h<k;++h){e=c[h];d[h]={id:e.id,feature:e,state:null};var f=b.records[h].fields, m;for(m in e.attributes)f.containsKey(m)&&(d[h][m]=e.attributes[m])}b.callback.call(b.scope,d,a.priv,!0)}else c=a.priv,200<=c.status&&300>c.status?this.fireEvent("exception",this,"remote",b.action,b,a.error,b.records):this.fireEvent("exception",this,"response",b.action,b,c),b.callback.call(b.scope,[],c,!1)}});Ext.namespace("gxp.data"); gxp.data.WFSFeatureStore=Ext.extend(GeoExt.data.FeatureStore,{setOgcFilter:function(a){this.proxy.setFilter(a)},constructor:function(a){a.proxy&&a.proxy instanceof GeoExt.data.ProtocolProxy||(a.proxy=new gxp.data.WFSProtocolProxy(Ext.apply({srsName:a.srsName,url:a.url,featureType:a.featureType,featureNS:a.featureNS,geometryName:a.geometryName,schema:a.schema,filter:a.ogcFilter,maxFeatures:a.maxFeatures,multi:a.multi},a.proxy)));a.writer||(a.writer=new Ext.data.DataWriter({write:Ext.emptyFn}));gxp.data.WFSFeatureStore.superclass.constructor.apply(this, arguments);this.reader.extractValues=function(a,c,d){return this.readRecords([a.feature]).records[0].data}.createDelegate(this.reader);this.reader.meta.idProperty="id";this.reader.getId=function(a){return a.id}}});Ext.namespace("gxp"); gxp.GoogleStreetViewPanel=Ext.extend(Ext.Panel,{panorama:null,heading:0,pitch:0,zoom:0,location:null,initComponent:function(){Ext.applyIf(this,{plain:!0,border:!1});return gxp.GoogleStreetViewPanel.superclass.initComponent.call(this)},afterRender:function(){var a=this.ownerCt;a&&(a=a.getSize(),Ext.applyIf(this,a),this.location||GeoExt.Popup&&this.bubble(function(a){if(a instanceof GeoExt.Popup)return this.location=a.location.clone().transform(a.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326")), !1},this));gxp.GoogleStreetViewPanel.superclass.afterRender.call(this);a={position:new google.maps.LatLng(this.location.lat,this.location.lon),pov:{heading:this.heading,pitch:this.pitch,zoom:this.zoom}};this.panorama=new google.maps.StreetViewPanorama(this.body.dom,a)},beforeDestroy:function(){delete this.panorama;gxp.GoogleStreetViewPanel.superclass.beforeDestroy.apply(this,arguments)},onResize:function(a,b){gxp.GoogleStreetViewPanel.superclass.onResize.apply(this,arguments);this.panorama&&"object"== typeof this.panorama&&google.maps.event.trigger(this.panorama,"resize")},setSize:function(a,b,c){gxp.GoogleStreetViewPanel.superclass.setSize.apply(this,arguments);this.panorama&&"object"==typeof this.panorama&&google.maps.event.trigger(this.panorama,"resize")}});Ext.reg("gxp_googlestreetviewpanel",gxp.GoogleStreetViewPanel);Ext.ns("gxp.data"); gxp.data.GroupStyleReader=Ext.extend(GeoExt.data.StyleReader,{onMetaChange:function(){gxp.data.GroupStyleReader.superclass.onMetaChange.apply(this,arguments);var a=this.recordType,b=!1;a.prototype.set=Ext.createInterceptor(this.recordType.prototype.set,function(c,d){if(!b&&"filter"===c){b=!0;var e=this.store,f=this.get("filter");BETWEEN=OpenLayers.Filter.Comparison.BETWEEN;f instanceof OpenLayers.Filter&&"string"===typeof d&&(d=OpenLayers.Format.CQL.prototype.read(d));var g,h=e.indexOf(this);if(h< e.getCount()-1&&(g=d.type===BETWEEN?"upperBoundary":"value",d[g]!==f[g])){var k=e.getAt(h+1),l=k.get("filter").clone();l[l.type===BETWEEN?"lowerBoundary":"value"]=d[g];k.set("filter",l)}0<h&&(g=d.type===BETWEEN?"lowerBoundary":"value",d[g]!==f[g]&&(e=e.getAt(h-1),f=e.get("filter").clone(),f[f.type===BETWEEN?"upperBoundary":"value"]=d[g],e.set("filter",f)));a.prototype.set.apply(this,[c,d]);return b=!1}})}});Ext.namespace("gxp.grid"); gxp.grid.FeatureGrid=Ext.extend(Ext.grid.GridPanel,{map:null,ignoreFields:null,includeFields:null,layer:null,columnsSortable:!0,columnMenuDisabled:!1,initComponent:function(){this.ignoreFields=["feature","state","fid"].concat(this.ignoreFields);this.store?(this.cm=this.createColumnModel(this.store),this.map&&(this.layer=new OpenLayers.Layer.Vector(this.id+"_layer"),this.map.addLayer(this.layer))):(this.store=new Ext.data.Store,this.cm=new Ext.grid.ColumnModel({columns:[]}));this.layer&&(this.sm=this.sm|| new GeoExt.grid.FeatureSelectionModel({layerFromStore:!1,layer:this.layer}),this.store instanceof GeoExt.data.FeatureStore&&this.store.bind(this.layer));this.dateFormat||(this.dateFormat=Ext.form.DateField.prototype.format);this.timeFormat||(this.timeFormat=Ext.form.TimeField.prototype.format);gxp.grid.FeatureGrid.superclass.initComponent.call(this)},onDestroy:function(){this.initialConfig&&this.initialConfig.map&&!this.initialConfig.layer&&(this.layer.destroy(),delete this.layer);gxp.grid.FeatureGrid.superclass.onDestroy.apply(this, arguments)},setStore:function(a,b){b&&(this.schema=b);a?(this.store instanceof GeoExt.data.FeatureStore&&this.store.unbind(),this.layer&&(this.layer.destroyFeatures(),a.bind(this.layer)),this.reconfigure(a,this.createColumnModel(a))):this.reconfigure(new Ext.data.Store,new Ext.grid.ColumnModel({columns:[]}))},getColumns:function(a){function b(a){return function(b){var c=b;"string"==typeof b&&(c=Date.parseDate(b.replace(/Z$/,""),"c"));return c?c.format(a):b}}var c=[],d=this.customEditors||{},e=this.customRenderers|| {},f,g,h,k,l;(this.schema||a.fields).each(function(a){if(this.schema)switch(f=a.get("name"),g=a.get("type").split(":").pop(),k=null,g){case "date":k=this.dateFormat;break;case "datetime":k=k?k:this.dateFormat+" "+this.timeFormat;h=void 0;l=b(k);break;case "boolean":h="booleancolumn";break;case "string":h="gridcolumn";break;default:h="numbercolumn"}else f=a.name;-1===this.ignoreFields.indexOf(f)&&(null===this.includeFields||0<=this.includeFields.indexOf(f))&&c.push(Ext.apply({dataIndex:f,hidden:this.fieldVisibility? !this.fieldVisibility[f]:!1,header:this.propertyNames?this.propertyNames[f]||f:f,sortable:this.columnsSortable,menuDisabled:this.columnMenuDisabled,xtype:h,editor:d[f]||{xtype:"textfield"},format:k,renderer:e[f]||(h?void 0:l)},this.columnConfig?this.columnConfig[f]:null))},this);return c},createColumnModel:function(a){a=this.getColumns(a);return new Ext.grid.ColumnModel(a)}});Ext.reg("gxp_featuregrid",gxp.grid.FeatureGrid); (function(){function a(a){var c=this.meta.format;if("string"===typeof a||a.nodeType){a=c.read(a);var d=c.read;c.read=function(){c.read=d;return a}}this.raw=a}Ext.intercept(GeoExt.data.WMSCapabilitiesReader.prototype,"readRecords",a);GeoExt.data.AttributeReader&&Ext.intercept(GeoExt.data.AttributeReader.prototype,"readRecords",a)})();Ext.namespace("gxp.plugins"); gxp.plugins.WMSSource=Ext.extend(gxp.plugins.LayerSource,{ptype:"gxp_wmssource",baseParams:null,format:null,describeLayerStore:null,describedLayers:null,schemaCache:null,ready:!1,requiredProperties:["title","bbox"],constructor:function(a){a&&!0===a.forceLazy&&(a.requiredProperties=[],delete a.forceLazy,window.console&&console.warn("Deprecated config option 'forceLazy: true' for layer source '"+a.id+"'. Use 'requiredProperties: []' instead."));gxp.plugins.WMSSource.superclass.constructor.apply(this, arguments);this.format||(this.format=new OpenLayers.Format.WMSCapabilities({keepData:!0}))},init:function(a){gxp.plugins.WMSSource.superclass.init.apply(this,arguments);this.target.on("authorizationchange",this.onAuthorizationChange,this)},onAuthorizationChange:function(){if(!0!==this.disabled&&this.store&&"/"===this.url.charAt(0)){var a=this.store.lastOptions||{params:{}};Ext.apply(a.params,{_dc:Math.random()});this.store.reload(a)}},destroy:function(){this.target.un("authorizationchange",this.onAuthorizationChange, this);gxp.plugins.WMSSource.superclass.destroy.apply(this,arguments)},isLazy:function(){var a=!0,b=this.target.initialConfig.map;if(b&&b.layers)for(var c,d=0,e=b.layers.length;d<e&&(c=b.layers[d],c.source!==this.id||(a=this.layerConfigComplete(c),!1!==a));++d);return a},layerConfigComplete:function(a){var b=!0;if(!Ext.isObject(a.capability))for(var c=this.requiredProperties,d=c.length-1;0<=d&&(b=!!a[c[d]],!1!==b);--d);return b},createStore:function(){var a=this.baseParams||{SERVICE:"WMS",REQUEST:"GetCapabilities"}; this.version&&(a.VERSION=this.version);var b=this.isLazy();this.store=new GeoExt.data.WMSCapabilitiesStore({url:this.trimUrl(this.url,a),baseParams:a,format:this.format,autoLoad:!b,layerParams:{exceptions:null},listeners:{load:function(){this.store.reader.raw&&this.store.reader.raw.service?(this.title||(this.title=this.store.reader.raw.service.title),this.ready?this.lazy=!1:(this.ready=!0,this.fireEvent("ready",this))):this.fireEvent("failure",this,"Invalid capabilities document.");delete this.format.data}, exception:function(a,b,e,f,g,h){delete this.store;a="";"response"===b?"string"==typeof h?b=h:(b="Invalid response from server.",(a=this.format&&this.format.data)&&a.parseError&&(b+=" "+a.parseError.reason+" - line: "+a.parseError.line),g=g.status,a=200<=g&&300>g?gxp.util.getOGCExceptionText(h&&h.arg&&h.arg.exceptionReport):"Status: "+g):(b="Trouble creating layer store from response.",a="Unable to handle response.");this.fireEvent("failure",this,b,a);delete this.format.data},scope:this}});b&&(this.lazy= b,this.ready=!0,this.fireEvent("ready",this))},trimUrl:function(a,b,c){c=OpenLayers.Util.getParameters(a);b=OpenLayers.Util.upperCaseObject(b);var d=0,e;for(e in c)++d,e.toUpperCase()in b&&(--d,delete c[e]);return a.split("?").shift()+(d?"?"+OpenLayers.Util.getParameterString(c):"")},createLazyLayerRecord:function(a){a=Ext.apply({},a);var b=a.srs||this.target.map.projection;a.srs={};a.srs[b]=!0;var c=a.bbox||this.target.map.maxExtent||OpenLayers.Projection.defaults[b].maxExtent;a.bbox={};a.bbox[b]= {bbox:c};c=this.store&&this.store instanceof GeoExt.data.WMSCapabilitiesStore?new this.store.recordType(a):new GeoExt.data.LayerRecord(a);c.setLayer(new OpenLayers.Layer.WMS(a.title||a.name,a.url||this.url,{layers:a.name,transparent:"transparent"in a?a.transparent:!0,cql_filter:a.cql_filter,format:a.format},{projection:b,eventListeners:{tileloaded:this.countAlive,tileerror:this.countAlive,scope:this}}));c.json=a;return c},countAlive:function(a){"_alive"in a.object.metadata||(a.object.metadata._alive= 0,a.object.events.register("loadend",this,this.removeDeadLayer));a.object.metadata._alive+="tileerror"==a.type?-1:1},removeDeadLayer:function(a){a.object.events.un({tileloaded:this.countAlive,tileerror:this.countAlive,loadend:this.removeDeadLayer,scope:this});0===a.object.metadata._alive&&(this.target.mapPanel.map.removeLayer(a.object),window.console&&console.debug("Unavailable layer "+a.object.name+" removed."));delete a.object.metadata._alive},createLayerRecord:function(a){var b,c,d=this.store.findExact("name", a.name);-1<d?c=this.store.getAt(d):Ext.isObject(a.capability)?c=this.store.reader.readRecords({capability:{request:{getmap:{href:this.trimUrl(this.url,this.baseParams)}},layers:[a.capability]}}).records[0]:this.layerConfigComplete(a)&&(c=this.createLazyLayerRecord(a));if(c){b=c.getLayer().clone();var d=this.getMapProjection(),e=this.getProjection(c);e&&b.addOptions({projection:e});var e=(e||d).getCode(),f=c.get("bbox"),g;if(f&&f[e])g=OpenLayers.Bounds.fromArray(f[e].bbox,b.reverseAxisOrder());else if(e= c.get("llbbox"))e[0]=Math.max(e[0],-180),e[1]=Math.max(e[1],-90),e[2]=Math.min(e[2],180),e[3]=Math.min(e[3],90),g=OpenLayers.Bounds.fromArray(e).transform("EPSG:4326",d);b.mergeNewParams({STYLES:a.styles,FORMAT:a.format,TRANSPARENT:a.transparent,CQL_FILTER:a.cql_filter});d=!1;"tiled"in a?d=!a.tiled:c.data.dimensions&&c.data.dimensions.time&&(d=!0);b.setName(a.title||b.name);b.addOptions({attribution:b.attribution||a.attribution,maxExtent:g,restrictedExtent:g,singleTile:d,ratio:a.ratio||1,visibility:"visibility"in a?a.visibility:!0,opacity:"opacity"in a?a.opacity:1,buffer:"buffer"in a?a.buffer:1,dimensions:c.data.dimensions,transitionEffect:d?"resize":null,minScale:a.minscale,maxScale:a.maxscale});g=Ext.applyIf({title:b.name,group:a.group,infoFormat:a.infoFormat,getFeatureInfo:a.getFeatureInfo,source:a.source,properties:"gxp_wmslayerpanel",fixed:a.fixed,selected:"selected"in a?a.selected:!1,restUrl:this.restUrl,layer:b},c.data);var h=[{name:"source",type:"string"},{name:"group",type:"string"},{name:"properties", type:"string"},{name:"fixed",type:"boolean"},{name:"selected",type:"boolean"},{name:"restUrl",type:"string"},{name:"infoFormat",type:"string"},{name:"getFeatureInfo"}];c.fields.each(function(a){h.push(a)});b=new (GeoExt.data.LayerRecord.create(h))(g,b.id);b.json=a}else window.console&&0<this.store.getCount()&&void 0!==a.name&&console.warn("Could not create layer record for layer '"+a.name+"'. Check if the layer is found in the WMS GetCapabilities response.");return b},getProjection:function(a){var b= this.getMapProjection(),c=b;a=a.get("srs");if(!a[b.getCode()]){var c=null,d;for(d in a)if((a=new OpenLayers.Projection(d)).equals(b)){c=a;break}}return c},initDescribeLayerStore:function(){var a=this.store.reader.raw;this.lazy&&(a={capability:{request:{describelayer:{href:this.url}}},version:this.version||"1.1.1"});var b=a.capability.request.describelayer;b&&(a=a.version,1.1<parseFloat(a)&&(a="1.1.1"),a={SERVICE:"WMS",VERSION:a,REQUEST:"DescribeLayer"},this.describeLayerStore=new GeoExt.data.WMSDescribeLayerStore({url:this.trimUrl(b.href, a),baseParams:a}))},describeLayer:function(a,b,c){function d(a){window.setTimeout(function(){b.call(c,a)},0)}this.describeLayerStore||this.initDescribeLayerStore();if(this.describeLayerStore){this.describedLayers||(this.describedLayers={});var e=a.getLayer().params.LAYERS;a=function(){for(var a=Ext.isArray(arguments[1])?arguments[1]:arguments[0],d,g,m=a.length-1;0<=m;m--){d=a[m];g=d.get("layerName");if(g==e){this.describeLayerStore.un("load",arguments.callee,this);this.describedLayers[g]=!0;b.call(c, d);return}"function"==typeof this.describedLayers[g]&&(d=this.describedLayers[g],this.describeLayerStore.un("load",d,this),d.apply(this,arguments))}delete f[e];b.call(c,!1)};var f=this.describedLayers,g;if(f[e])if(-1==(g=this.describeLayerStore.findExact("layerName",e)))this.describeLayerStore.on("load",a,this);else d(this.describeLayerStore.getAt(g));else f[e]=a,this.describeLayerStore.load({params:{LAYERS:e},add:!0,callback:a,scope:this})}else d(!1)},fetchSchema:function(a,b,c,d){var e=this.schemaCache[b]; if(e)if(0==e.getCount())e.on("load",function(){c.call(d,e)},this,{single:!0});else c.call(d,e);else e=new GeoExt.data.AttributeStore({url:a,baseParams:{SERVICE:"WFS",VERSION:"1.1.0",REQUEST:"DescribeFeatureType",TYPENAME:b},autoLoad:!0,listeners:{load:function(){c.call(d,e)},scope:this}}),this.schemaCache[b]=e},getSchema:function(a,b,c){this.schemaCache||(this.schemaCache={});this.describeLayer(a,function(d){if(d&&"WFS"==d.get("owsType")){var e=d.get("typeName");d=d.get("owsURL");this.fetchSchema(d, e,b,c)}else d?b.call(c,!1):this.fetchSchema(this.url,a.get("name"),b,c)},this)},getWFSProtocol:function(a,b,c){this.getSchema(a,function(d){var e=!1;if(d){var f,g=/gml:((Multi)?(Point|Line|Polygon|Curve|Surface|Geometry)).*/;d.each(function(a){g.exec(a.get("type"))&&(f=a.get("name"))},this);e=new OpenLayers.Protocol.WFS({version:"1.1.0",srsName:a.getLayer().projection.getCode(),url:d.url,featureType:d.reader.raw.featureTypes[0].typeName,featureNS:d.reader.raw.targetNamespace,geometryName:f})}b.call(c, e,d,a)},this)},getConfigForRecord:function(a){var b=Ext.applyIf(gxp.plugins.WMSSource.superclass.getConfigForRecord.apply(this,arguments),a.json),c=a.getLayer(),d=c.params,e=c.options,f=b.name,g=this.store.reader.raw;if(g)for(var g=g.capability.layers,h=g.length-1;0<=h;--h)if(g[h].name===f){b.capability=Ext.apply({},g[h]);f={};f[c.projection.getCode()]=!0;b.capability.srs=f;break}b.capability||(c.maxExtent&&(b.bbox=c.maxExtent.toArray()),b.srs=c.projection.getCode());return Ext.apply(b,{format:d.FORMAT, styles:d.STYLES,tiled:!e.singleTile,transparent:d.TRANSPARENT,cql_filter:d.CQL_FILTER,minscale:e.minScale,maxscale:e.maxScale,infoFormat:a.get("infoFormat"),attribution:c.attribution})},disable:function(){this.disabled=!0},getState:function(){var a=gxp.plugins.WMSSource.superclass.getState.apply(this,arguments);return Ext.applyIf(a,{title:this.title})}});Ext.preg(gxp.plugins.WMSSource.prototype.ptype,gxp.plugins.WMSSource);Ext.namespace("gxp.plugins"); gxp.plugins.ArcRestSource=Ext.extend(gxp.plugins.LayerSource,{ptype:"gxp_arcrestsource",requiredProperties:["name"],constructor:function(a){this.config=a;gxp.plugins.ArcRestSource.superclass.constructor.apply(this,arguments)},createStore:function(){var a=this.url.split("?")[0],b=this,c=function(c){var f=Ext.decode(c.responseText),g=b.getArcProjection(f.spatialReference.wkid),h=[];if(null!=g)for(c=0;c<f.layers.length;c++){var k=f.layers[c];h.push(new OpenLayers.Layer.ArcGIS93Rest(k.name,a+"/export", {layers:"show:"+k.id,TRANSPARENT:!0},{isBaseLayer:!1,ratio:1,displayInLayerSwitcher:!0,visibility:!0,projection:g,queryable:f.capabilities&&f.capabilities.Identify}))}else d(c);b.title=f.documentInfo.Title;b.store=new GeoExt.data.LayerStore({layers:h,fields:[{name:"source",type:"string"},{name:"name",type:"string",mapping:"name"},{name:"layerid",type:"string"},{name:"group",type:"string",defaultValue:this.title},{name:"fixed",type:"boolean",defaultValue:!0},{name:"tiled",type:"boolean",defaultValue:!0}, {name:"queryable",type:"boolean",defaultValue:!0},{name:"selected",type:"boolean"}]});b.fireEvent("ready",b)},d=function(a){Ext.Msg.alert("No ArcGIS Layers","Could not find any compatible layers at "+b.config.url);b.fireEvent("failure",b)};(this.lazy=this.isLazy())?this.fireEvent("ready"):Ext.Ajax.request({url:a,params:{f:"json",pretty:"false",keepPostParams:"true"},method:"POST",success:c,failure:d})},isLazy:function(){var a=!0,b=!1,c=this.target.initialConfig.map;if(c&&c.layers)for(var d,e=0,f= c.layers.length;e<f&&(d=c.layers[e],d.source!==this.id||(b=!0,a=this.layerConfigComplete(d),!1!==a));++e);return a&&b},layerConfigComplete:function(a){for(var b=!0,c=this.requiredProperties,d=c.length-1;0<=d&&(b=!!a[c[d]],!1!==b);--d);return b},createLayerRecord:function(a){var b,c;c=function(b){return b.get("name")===a.name};var d=this.lazy||this.store&&-1<this.store.findBy(c);-1==this.target.mapPanel.layers.findBy(c)&&d&&(b=!this.lazy&&-1<this.store.findBy(c)?this.store.getAt(this.store.findBy(c)).clone(): this.createLazyLayerRecord(a),c=b.getLayer(),a.title&&(c.setName(a.title),b.set("title",a.title)),"visibility"in a&&(c.visibility=a.visibility),"opacity"in a&&(c.opacity=a.opacity),"format"in a&&(c.params.FORMAT=a.format,b.set("format",a.format)),c=!1,"tiled"in a&&(c=!a.tiled),b.set("tiled",!c),b.set("selected",a.selected||!1),b.set("queryable",a.queryable||!0),b.set("source",a.source),b.set("name",a.name),b.set("layerid",a.layerid),b.set("properties","gxp_wmslayerpanel"),"group"in a&&b.set("group", a.group),b.commit());return b},getArcProjection:function(a){var b=this.getMapProjection(),c=b;a="EPSG:"+a+"";a!==b.getCode()&&(c=null,(p=new OpenLayers.Projection(a)).equals(b)&&(c=p));return c},createLazyLayerRecord:function(a){var b=a.srs||this.target.map.projection;a.srs={};a.srs[b]=!0;var c=a.bbox||this.target.map.maxExtent||OpenLayers.Projection.defaults[b].maxExtent;a.bbox={};a.bbox[b]={bbox:c};c=new GeoExt.data.LayerRecord(a);c.set("name",a.name);c.set("layerid",a.layerid||"show:0");c.set("format", a.format||"png");c.set("tiled","tiled"in a?a.tiled:!0);c.setLayer(new OpenLayers.Layer.ArcGIS93Rest(a.name,this.url.split("?")[0]+"/export",{layers:a.layerid,TRANSPARENT:!0,FORMAT:"format"in a?a.format:"png"},{isBaseLayer:!1,displayInLayerSwitcher:!0,projection:b,singleTile:"tiled"in a?!a.tiled:!1,queryable:"queryable"in a?a.queryable:!1}));return c},getConfigForRecord:function(a){var b=a.getLayer();return{source:a.get("source"),name:a.get("name"),title:a.get("title"),tiled:a.get("tiled"),visibility:b.getVisibility(), layerid:b.params.LAYERS,format:b.params.FORMAT,opacity:b.opacity||void 0,group:a.get("group"),fixed:a.get("fixed"),selected:a.get("selected")}}});Ext.preg(gxp.plugins.ArcRestSource.prototype.ptype,gxp.plugins.ArcRestSource);Ext.namespace("gxp.plugins"); gxp.plugins.NavigationHistory=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_navigationhistory",previousMenuText:"Zoom To Previous Extent",nextMenuText:"Zoom To Next Extent",previousTooltip:"Zoom To Previous Extent",nextTooltip:"Zoom To Next Extent",constructor:function(a){gxp.plugins.NavigationHistory.superclass.constructor.apply(this,arguments)},addActions:function(){var a=new OpenLayers.Control.NavigationHistory;this.target.mapPanel.map.addControl(a);a=[new GeoExt.Action({menuText:this.previousMenuText, iconCls:"gxp-icon-zoom-previous",tooltip:this.previousTooltip,disabled:!0,control:a.previous}),new GeoExt.Action({menuText:this.nextMenuText,iconCls:"gxp-icon-zoom-next",tooltip:this.nextTooltip,disabled:!0,control:a.next})];return gxp.plugins.NavigationHistory.superclass.addActions.apply(this,[a])}});Ext.preg(gxp.plugins.NavigationHistory.prototype.ptype,gxp.plugins.NavigationHistory);Ext.namespace("gxp.form"); gxp.form.ComparisonComboBox=Ext.extend(Ext.form.ComboBox,{allowedTypes:[[OpenLayers.Filter.Comparison.EQUAL_TO,"="],[OpenLayers.Filter.Comparison.NOT_EQUAL_TO,"<>"],[OpenLayers.Filter.Comparison.LESS_THAN,"<"],[OpenLayers.Filter.Comparison.GREATER_THAN,">"],[OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO,"<="],[OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO,">="],[OpenLayers.Filter.Comparison.LIKE,"like"],[OpenLayers.Filter.Comparison.BETWEEN,"between"]],allowBlank:!1,mode:"local",typeAhead:!0, forceSelection:!0,triggerAction:"all",width:50,editable:!0,initComponent:function(){var a={displayField:"name",valueField:"value",store:new Ext.data.SimpleStore({data:this.allowedTypes,fields:["value","name"]}),value:void 0===this.value?this.allowedTypes[0][0]:this.value,listeners:{blur:function(){var a=this.store.findExact("value",this.getValue());-1!=a?this.fireEvent("select",this,this.store.getAt(a)):null!=this.startValue&&this.setValue(this.startValue)}}};Ext.applyIf(this,a);gxp.form.ComparisonComboBox.superclass.initComponent.call(this)}}); Ext.reg("gxp_comparisoncombo",gxp.form.ComparisonComboBox);Ext.namespace("gxp.plugins"); gxp.plugins.FeedGetFeatureInfo=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_getfeedfeatureinfo",init:function(a){gxp.plugins.FeedGetFeatureInfo.superclass.init.apply(this,arguments);this.target.mapPanel.layers.on({add:this.addLayer,remove:this.removeLayer,scope:this})},addLayer:function(a,b,c){a=0;for(c=b.length;a<c;++a){var d=b[a],e=this.target.getSource(d),d=d.getLayer();e instanceof gxp.plugins.FeedSource&&(null==this.target.selectControl?(this.target.selectControl=new OpenLayers.Control.SelectFeature(d, {clickout:!0,listeners:{clickoutFeature:function(){}},scope:this}),this.target.mapPanel.map.addControl(this.target.selectControl)):(e=this.target.selectControl.layers?this.target.selectControl.layers:this.target.selectControl.layer?[this.target.selectControl.layer]:[],e.push(d),this.target.selectControl.setLayer(e)))}this.target.selectControl&&this.target.selectControl.activate()},removeLayer:function(a,b,c){b.length||(b=[b]);a=0;for(c=b.length;a<c;++a){var d=b[a].getLayer(),e=this.target.selectControl; if(null!=e)if(e.layers)for(var f=0;f<e.layers.length;f++){var g=e.layers;e.layers[f].id===d.id&&(g.splice(f,1),e.setLayer(g))}else null!=e.layer&&d.id===e.layer.id&&e.setLayer([])}}});Ext.preg(gxp.plugins.FeedGetFeatureInfo.prototype.ptype,gxp.plugins.FeedGetFeatureInfo);Ext.namespace("gxp.plugins"); gxp.plugins.FeedSource=Ext.extend(gxp.plugins.LayerSource,{ptype:"gxp_feedsource",title:"Feed Source",format:"OpenLayers.Format.GeoRSS",popupTemplate:'<a target="_blank" href="{link}">{description}</a>',fixed:!0,createLayerRecord:function(a){var b=new OpenLayers.Layer.Vector(a.name,{projection:"projection"in a?a.projection:"EPSG:4326",visibility:"visibility"in a?a.visibility:!0,strategies:[this.fixed?new OpenLayers.Strategy.Fixed:new OpenLayers.Strategy.BBOX({resFactor:1,ratio:1})],protocol:new OpenLayers.Protocol.HTTP({url:this.url, params:a.params,format:this.getFormat(a)}),styleMap:this.getStyleMap(a)});this.configureInfoPopup(b);var c=GeoExt.data.LayerRecord.create([{name:"name",type:"string"},{name:"source",type:"string"},{name:"group",type:"string"},{name:"fixed",type:"boolean"},{name:"selected",type:"boolean"},{name:"visibility",type:"boolean"},{name:"format",type:"string"},{name:"defaultStyle"},{name:"selectStyle"},{name:"params"}]),d="format"in a?a.format:this.format;return new c({layer:b,name:a.name,source:a.source, group:a.group,fixed:"fixed"in a?a.fixed:!1,selected:"selected"in a?a.selected:!1,params:"params"in a?a.params:{},visibility:"visibility"in a?a.visibility:!1,format:d instanceof String?d:null,defaultStyle:"defaultStyle"in a?a.defaultStyle:{},selectStyle:"selectStyle"in a?a.selectStyle:{}},b.id)},getConfigForRecord:function(a){var b=gxp.plugins.FeedSource.superclass.getConfigForRecord.apply(this,arguments);return Ext.apply(b,{name:a.get("name"),group:a.get("group"),fixed:a.get("fixed"),selected:a.get("selected"), params:a.get("params"),visibility:a.getLayer().getVisibility(),format:a.get("format"),defaultStyle:a.getLayer().styleMap.styles["default"].defaultStyle,selectStyle:a.getLayer().styleMap.styles.select.defaultStyle})},getFormat:function(a){var b=window;a="format"in a?a.format:this.format;if("string"==typeof a||a instanceof String){a=a.split(".");for(var c=0,d=a.length;c<d&&(b=b[a[c]],b);++c);if(b&&b.prototype&&b.prototype.initialize)return a=function(){b.prototype.initialize.apply(this)},a.prototype= b.prototype,new a}else return a},configureInfoPopup:function(a){var b=new Ext.XTemplate(this.popupTemplate);a.events.on({featureselected:function(a){a=a.feature;this.target.selectControl&&(this.target.selectControl.popup&&this.target.selectControl.popup.close(),this.target.selectControl.popup=new GeoExt.Popup({title:a.attributes.title,closeAction:"destroy",location:a,html:b.apply(a.attributes)}),this.target.selectControl.popup.show())},featureunselected:function(){this.target.selectControl&&this.target.selectControl.popup&& this.target.selectControl.popup.close()},scope:this})},getStyleMap:function(a){return new OpenLayers.StyleMap({"default":new OpenLayers.Style("defaultStyle"in a?a.defaultStyle:{graphicName:"circle",pointRadius:5,fillOpacity:.7,fillColor:"Red"},{title:a.name}),select:new OpenLayers.Style("selectStyle"in a?a.selectStyle:{graphicName:"circle",pointRadius:10,fillOpacity:1,fillColor:"Yellow"})})}});Ext.preg(gxp.plugins.FeedSource.prototype.ptype,gxp.plugins.FeedSource);Ext.namespace("gxp.plugins"); gxp.plugins.PicasaFeedSource=Ext.extend(gxp.plugins.FeedSource,{ptype:"gxp_picasasource",url:"http://picasaweb.google.com/data/feed/base/all?thumbsize=160c&",format:"OpenLayers.Format.Picasa",title:"Picasa Photos",pointRadius:14,popupTemplate:'<tpl for="."><a target="_blank" href="{link}"><img title="{title}" src="{thumbnail}"/></a></tpl>',fixed:!1,createLayerRecord:function(a){Ext.isEmpty(a.params["max-results"])&&(a.params["max-results"]=50);a.url=this.url;this.format=new OpenLayers.Format.GeoRSS({createFeatureFromItem:function(a){var b= OpenLayers.Format.GeoRSS.prototype.createFeatureFromItem.apply(this,arguments);b.attributes.thumbnail=this.getElementsByTagNameNS(a,"http://search.yahoo.com/mrss/","thumbnail")[0].getAttribute("url");b.attributes.content=OpenLayers.Util.getXmlNodeValue(this.getElementsByTagNameNS(a,"*","summary")[0]);return b}});var b=gxp.plugins.PicasaFeedSource.superclass.createLayerRecord.apply(this,arguments);b.getLayer().protocol.filterToParams=function(a,b){if(a.type===OpenLayers.Filter.Spatial.BBOX){var e= a.value.toArray();b.bbox=[Math.max(-180,e[0]),Math.max(-90,e[1]),Math.min(180,e[2]),Math.min(90,e[3])]}return b};return b},configureInfoPopup:function(a){var b=new Ext.XTemplate(this.popupTemplate);a.events.on({featureselected:function(a){a=a.feature;null!=this.target.selectControl.popup&&this.target.selectControl.popup.close();var d=document.createElement("div");d.innerHTML=a.attributes.content;d={link:d.getElementsByTagName("a")[0].getAttribute("href"),title:a.attributes.title,thumbnail:a.attributes.thumbnail}; this.target.selectControl.popup=new GeoExt.Popup({title:a.attributes.title,closeAction:"destroy",location:a,width:175,height:200,html:b.apply(d)});this.target.selectControl.popup.show()},featureunselected:function(a){this.target.selectControl&&this.target.selectControl.popup&&this.target.selectControl.popup.close()},scope:this})},getStyleMap:function(a){return new OpenLayers.StyleMap({"default":new OpenLayers.Style({externalGraphic:"${thumbnail}",pointRadius:this.pointRadius},{title:this.title}), select:new OpenLayers.Style({pointRadius:this.pointRadius+5})})}});Ext.preg(gxp.plugins.PicasaFeedSource.prototype.ptype,gxp.plugins.PicasaFeedSource);Ext.namespace("gxp.form"); gxp.form.ColorField=Ext.extend(Ext.form.TextField,{cssColors:{aqua:"#00FFFF",black:"#000000",blue:"#0000FF",fuchsia:"#FF00FF",gray:"#808080",green:"#008000",lime:"#00FF00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#FF0000",silver:"#C0C0C0",teal:"#008080",white:"#FFFFFF",yellow:"#FFFF00"},defaultBackground:"#ffffff",initComponent:function(){this.value&&(this.value=this.hexToColor(this.value));gxp.form.ColorField.superclass.initComponent.call(this);this.on({render:this.colorField, valid:this.colorField,scope:this})},isDark:function(a){var b=!1;if(a){var b=parseInt(a.substring(1,3),16)/255,c=parseInt(a.substring(3,5),16)/255;a=parseInt(a.substring(5,7),16)/255;b=.5>.299*b+.587*c+.144*a}return b},colorField:function(){var a=this.colorToHex(this.getValue())||this.defaultBackground;this.getEl().setStyle({background:a,color:this.isDark(a)?"#ffffff":"#000000"})},getHexValue:function(){return this.colorToHex(gxp.form.ColorField.superclass.getValue.apply(this,arguments))},getValue:function(){var a= this.getHexValue(),b=this.initialConfig.value;a===this.hexToColor(b)&&(a=b);return a},setValue:function(a){gxp.form.ColorField.superclass.setValue.apply(this,[this.hexToColor(a)])},colorToHex:function(a){return a?a.match(/^#[0-9a-f]{6}$/i)?a:this.cssColors[a.toLowerCase()]||null:a},hexToColor:function(a){if(!a)return a;for(var b in this.cssColors)if(this.cssColors[b]==a.toUpperCase()){a=b;break}return a}});Ext.reg("gxp_colorfield",gxp.form.ColorField);Ext.namespace("gxp.plugins"); gxp.plugins.GoogleEarth=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_googleearth",timeout:7E3,menuText:"3D Viewer",tooltip:"Switch to 3D Viewer",tooltipMap:"Switch back to normal map view",constructor:function(a){gxp.plugins.GoogleEarth.superclass.constructor.apply(this,arguments)},addActions:function(){return gxp.plugins.GoogleEarth.superclass.addActions.apply(this,[[{menuText:this.menuText,enableToggle:!0,iconCls:"gxp-icon-googleearth",tooltip:this.tooltip,toggleHandler:function(a,b){this.actions[0].each(function(a){a.toggle&& a.toggle(!1,!0)});this.togglePanelDisplay(b)},scope:this}]])},togglePanelDisplay:function(a){var b=this.target.mapPanel.ownerCt,c=b&&b.getLayout();if(c&&c instanceof Ext.layout.CardLayout)if(!0===a)gxp.plugins.GoogleEarth.loader.onLoad({callback:function(){c.setActiveItem(1);this.actions[0].enable();this.actions[0].items[0].setTooltip(this.tooltipMap);this.actions[0].each(function(a){a.toggle&&a.toggle(!0,!0)})},scope:this});else c.setActiveItem(0),this.actions[0].items[0].setTooltip(this.tooltip)}, getHost:function(){return window.location.host.split(":").shift()+":"+(window.location.port||"80")}}); gxp.plugins.GoogleEarth.loader=new (Ext.extend(Ext.util.Observable,{ready:!(!window.google||!window.google.earth),loading:!1,constructor:function(){this.addEvents("ready","failure");return Ext.util.Observable.prototype.constructor.apply(this,arguments)},onScriptLoad:function(){var a=gxp.plugins.GoogleEarth.loader;a.ready||(a.ready=!0,a.loading=!1,a.fireEvent("ready"))},onLoad:function(a){if(this.ready)window.setTimeout(function(){a.callback.call(a.scope)},0);else if(this.loading)this.on({ready:a.callback, failure:a.errback||Ext.emptyFn,scope:a.scope});else this.loadScript(a)},loadScript:function(a){function b(){document.getElementsByTagName("head")[0].appendChild(d)}window.google&&delete google.loader;var c={autoload:Ext.encode({modules:[{name:"earth",version:"1",callback:"gxp.plugins.GoogleEarth.loader.onScriptLoad"}]})},d=document.createElement("script");d.src="//www.google.com/jsapi?"+Ext.urlEncode(c);c=a.timeout||gxp.plugins.GoogleSource.prototype.timeout;window.setTimeout(function(){gxp.plugins.GoogleEarth.loader.ready|| (this.fireEvent("failure"),this.unload())}.createDelegate(this),c);this.on({ready:a.callback,failure:a.errback||Ext.emptyFn,scope:a.scope});this.loading=!0;if(document.body)b();else Ext.onReady(b);this.script=d},unload:function(){this.purgeListeners();this.script&&(document.getElementsByTagName("head")[0].removeChild(this.script),delete this.script);this.ready=this.loading=!1;delete google.loader;delete google.earth}}));Ext.preg(gxp.plugins.GoogleEarth.prototype.ptype,gxp.plugins.GoogleEarth);Ext.namespace("gxp.plugins"); gxp.plugins.OSMSource=Ext.extend(gxp.plugins.LayerSource,{ptype:"gxp_osmsource",title:"OpenStreetMap Layers",mapnikAttribution:"&copy; <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> contributors",osmarenderAttribution:"Data CC-By-SA by <a href='http://openstreetmap.org/' target='_blank'>OpenStreetMap</a>",createStore:function(){var a={projection:"EPSG:900913",maxExtent:new OpenLayers.Bounds(-2.00375083392E7,-2.00375083392E7,2.00375083392E7,2.00375083392E7),maxResolution:156543.03390625, numZoomLevels:19,units:"m",buffer:1,transitionEffect:"resize"},a=[new OpenLayers.Layer.OSM("OpenStreetMap",["//a.tile.openstreetmap.org/${z}/${x}/${y}.png","//b.tile.openstreetmap.org/${z}/${x}/${y}.png","//c.tile.openstreetmap.org/${z}/${x}/${y}.png"],OpenLayers.Util.applyDefaults({attribution:this.mapnikAttribution,type:"mapnik"},a))];this.store=new GeoExt.data.LayerStore({layers:a,fields:[{name:"source",type:"string"},{name:"name",type:"string",mapping:"type"},{name:"abstract",type:"string",mapping:"attribution"}, {name:"group",type:"string",defaultValue:"background"},{name:"fixed",type:"boolean",defaultValue:!0},{name:"selected",type:"boolean"}]});this.store.each(function(a){a.set("group","background")});this.fireEvent("ready",this)},createLayerRecord:function(a){var b,c=this.store.findExact("name",a.name);-1<c&&(b=this.store.getAt(c).copy(Ext.data.Record.id({})),c=b.getLayer().clone(),a.title&&(c.setName(a.title),b.set("title",a.title)),"visibility"in a&&(c.visibility=a.visibility),b.set("selected",a.selected|| !1),b.set("source",a.source),b.set("name",a.name),"group"in a&&b.set("group",a.group),b.data.layer=c,b.commit());return b}});Ext.preg(gxp.plugins.OSMSource.prototype.ptype,gxp.plugins.OSMSource);Ext.namespace("gxp"); gxp.StrokeSymbolizer=Ext.extend(Ext.FormPanel,{solidStrokeName:"solid",dashStrokeName:"dash",dotStrokeName:"dot",titleText:"Stroke",styleText:"Style",colorText:"Color",widthText:"Width",opacityText:"Opacity",symbolizer:null,colorManager:null,checkboxToggle:!0,defaultColor:null,dashStyles:null,border:!1,initComponent:function(){this.dashStyles=this.dashStyles||[["solid",this.solidStrokeName],["4 4",this.dashStrokeName],["2 4",this.dotStrokeName]];this.symbolizer||(this.symbolizer={});var a;this.colorManager&& (a=[new this.colorManager]);this.items=[{xtype:"fieldset",title:this.titleText,autoHeight:!0,checkboxToggle:this.checkboxToggle,collapsed:!0===this.checkboxToggle&&!1===this.symbolizer.stroke,hideMode:"offsets",defaults:{width:100},items:[{xtype:"combo",name:"style",fieldLabel:this.styleText,store:new Ext.data.SimpleStore({data:this.dashStyles,fields:["value","display"]}),displayField:"display",valueField:"value",value:this.getDashArray(this.symbolizer.strokeDashstyle)||OpenLayers.Renderer.defaultSymbolizer.strokeDashstyle, mode:"local",allowBlank:!0,triggerAction:"all",editable:!1,listeners:{select:function(a,c){this.symbolizer.strokeDashstyle=c.get("value");this.fireEvent("change",this.symbolizer)},scope:this}},{xtype:"gxp_colorfield",name:"color",fieldLabel:this.colorText,emptyText:OpenLayers.Renderer.defaultSymbolizer.strokeColor,value:this.symbolizer.strokeColor,defaultBackground:this.defaultColor||OpenLayers.Renderer.defaultSymbolizer.strokeColor,plugins:a,listeners:{valid:function(a){a=a.getValue();var c=this.symbolizer.strokeColor!= a;this.symbolizer.strokeColor=a;c&&this.fireEvent("change",this.symbolizer)},scope:this}},{xtype:"numberfield",name:"width",fieldLabel:this.widthText,allowNegative:!1,emptyText:OpenLayers.Renderer.defaultSymbolizer.strokeWidth,value:this.symbolizer.strokeWidth,listeners:{change:function(a,c){c=parseFloat(c);isNaN(c)?delete this.symbolizer.strokeWidth:this.symbolizer.strokeWidth=c;this.fireEvent("change",this.symbolizer)},scope:this}},{xtype:"slider",name:"opacity",fieldLabel:this.opacityText,values:[100* ("strokeOpacity"in this.symbolizer?this.symbolizer.strokeOpacity:OpenLayers.Renderer.defaultSymbolizer.strokeOpacity)],isFormField:!0,listeners:{changecomplete:function(a,c){this.symbolizer.strokeOpacity=c/100;this.fireEvent("change",this.symbolizer)},scope:this},plugins:[new GeoExt.SliderTip({getText:function(a){return a.value+"%"}})]}],listeners:{collapse:function(){!1!==this.symbolizer.stroke&&(this.symbolizer.stroke=!1,this.fireEvent("change",this.symbolizer))},expand:function(){this.symbolizer.stroke= !0;this.fireEvent("change",this.symbolizer)},scope:this}}];this.addEvents("change");gxp.StrokeSymbolizer.superclass.initComponent.call(this)},getDashArray:function(a){var b;a&&(a=a.split(/\s+/),a=a[0]/a[1],isNaN(a)||(b=1<=a?"4 4":"2 4"));return b}});Ext.reg("gxp_strokesymbolizer",gxp.StrokeSymbolizer);Ext.ns("gxp.slider"); gxp.slider.TimeSlider=Ext.extend(Ext.slider.MultiSlider,{ref:"slider",cls:"gx_timeslider",indexMap:null,width:200,animate:!1,timeFormat:"l, F d, Y g:i:s A",timeManager:null,playbackMode:"track",autoPlay:!1,aggressive:!1,changeBuffer:10,map:null,initComponent:function(){this.timeManager||(this.timeManager=new OpenLayers.Control.DimensionManager,this.map.addControl(this.timeManager));this.model||(this.model=this.timeManager.model);this.timeManager.agents&&(this.timeManager.timeUnits||this.timeManager.snapToList|| (this.model.values&&!this.model.resolution&&!1!==this.timeManager.snapToList&&(this.timeManager.snapToList=!0),this.model.resolution&&!this.model.values&&this.model.timeUnits&&(this.timeManager.timeUnits=this.model.timeUnits,this.timeManager.timeStep=this.model.timeStep)),this.playbackMode&&"track"!=this.playbackMode&&this.timeManager.timeUnits&&this.timeManager.incrementTimeValue(this.timeManager.rangeInterval));var a=this.buildSliderValues();if(a){this.timeManager.snapToList||this.timeManager.timeUnits|| this.timeManager.guessPlaybackRate();var b={maxValue:a.maxValue,minValue:a.minValue,increment:a.interval,keyIncrement:a.interval,indexMap:a.map,values:a.values};if(!this.initialConfig.timeFormat)if(a.interval)this.setTimeFormat(gxp.PlaybackToolbar.guessTimeFormat(a.interval*OpenLayers.TimeStep[this.timeManager.timeUnits]));else if(this.model.values){for(var a="Seconds Minutes Hours Days Months Years".split(" "),c={},d=1,e=this.model.values.length;d<e;++d)diff=this.model.values[d]-this.model.values[d- 1],info=gxp.PlaybackToolbar.smartIntervalFormat(diff),c[info.units]=!0;for(var f=null,d=0,e=a.length;d<e;++d)if(!0===c[a[d]]){f=a[d];break}null!==f&&(a=gxp.PlaybackToolbar.timeFormats[f])&&this.setTimeFormat(a)}Ext.applyIf(this.initialConfig,b);Ext.apply(this,this.initialConfig)}this.timeManager.events.on({rangemodified:this.onRangeModified,tick:this.onTimeTick,scope:this});this.plugins=(this.plugins||[]).concat([new Ext.slider.Tip({cls:"gxp-timeslider-tip",getText:this.getThumbText})]);this.listeners= Ext.applyIf(this.listeners||{},{dragstart:function(){this.timeManager.timer&&(this.timeManager.stop(),this._restartPlayback=!0)},beforechange:function(a,b,c,d){b=!0;this.timeManager.timeUnits||this.timeManager.snapToList?"cumulative"==this.playbackMode&&"tail"==a.indexMap[d.index]&&(b=!1):b=!1;return b},afterrender:function(a){this.sliderTip=a.plugins[0];this.timeManager.units&&1<a.thumbs.length&&a.setThumbStyles();this.autoPlay&&this.timeManager.play()},scope:this});!0===this.aggressive?this.listeners.change= {fn:this.onSliderChangeComplete,buffer:this.changeBuffer}:this.listeners.changecomplete=this.onSliderChangeComplete;gxp.slider.TimeSlider.superclass.initComponent.call(this);this.addEvents("sliderclick")},onClickChange:function(a){this.fireEvent("sliderclick",this);gxp.slider.TimeSlider.superclass.onClickChange.apply(this,arguments)},beforeDestroy:function(){this.map=null;gxp.slider.TimeSlider.superclass.beforeDestroy.call(this)},setPlaybackMode:function(a){this.playbackMode=a;a=this.buildSliderValues(); this.reconfigureSlider(a);"track"!=this.playbackMode&&this.timeManager.rangeInterval&&(this.timeManager.incrementTimeValue(this.timeManager.rangeInterval),this.setValue(0,this.timeManager.currentValue));this.setThumbStyles()},setTimeFormat:function(a){a&&(this.timeFormat=a)},onRangeModified:function(a){a=this.timeManager;if(a.agents&&a.agents.length){var b={start:a.animationRange[0],end:a.animationRange[1],resolution:{units:a.units,step:a.step}};a.guessPlaybackRate();if(a.animationRange[0]!=b.start|| a.animationRange[1]!=b.end||a.units!=b.units||a.step!=b.step)this.reconfigureSlider(this.buildSliderValues()),this.setThumbStyles(),this.fireEvent("rangemodified",this,a.animationRange)}else a.map.removeControl(this.ctl),a.destroy()},onTimeTick:function(a){if(a=a.currentValue){var b=this.refOwner,c=this.indexMap?this.indexMap.indexOf("tail"):-1,d=-1<c?a-this.thumbs[0].value:0;this.setValue(0,a);-1<c&&this.setValue(c,this.thumbs[c].value+d);this.updateTimeDisplay();b.fireEvent("timechange",b,a)}}, updateTimeDisplay:function(){this.sliderTip.onSlide(this,null,this.thumbs[0]);this.sliderTip.el.alignTo(this.el,"b-t?",this.offsets)},buildSliderValues:function(){var a=this.timeManager;if(a.step||a.snapToList){var b=["primary"],c=[a.currentValue],d=a.animationRange[0],e=a.animationRange[1],f=!1;if(this.dynamicRange){var g=.1*(d-e);c.push(d-=g,e+=g);b[1]="minTime";b[2]="maxTime"}"track"!=this.playbackMode&&(c.push(d),b[b.length]="tail");a.snapToList||(f=a.step);return{values:c,map:b,maxValue:e,minValue:d, interval:f}}return!1},reconfigureSlider:function(a){this.setMaxValue(a.maxValue);this.setMinValue(a.minValue);Ext.apply(this,{increment:a.interval,keyIncrement:a.interval,indexMap:a.map});for(var b=0;b<a.values.length;b++)this.thumbs[b]?this.setValue(b,a.values[b]):this.addThumb(a.values[b]);!a.interval&&this.timeManager.modelCache.values&&(a.interval=Math.round((a.maxValue-a.minValue)/this.timeManager.modelCache.values.length));this.setTimeFormat(gxp.PlaybackToolbar.guessTimeFormat(a.interval))}, setThumbStyles:function(){var a=this.indexMap.indexOf("tail");"min"==this.indexMap[1]&&(this.thumbs[1].el.addClass("x-slider-min-thumb"),this.thumbs[2].el.addClass("x-slider-max-thumb"));if(-1<a){var a=this.thumbs[a],b=this.thumbs[0];a.el.addClass("x-slider-tail-thumb");a.constrain=!1;b.constrain=!1}},getThumbText:function(a){if("tail"!=a.slider.indexMap[a.index]){var b=new Date(a.value);b.setTime(b.getTime()+6E4*b.getTimezoneOffset());return b.format(a.slider.timeFormat)}a=gxp.PlaybackToolbar.smartIntervalFormat.call(a, a.slider.thumbs[0].value-a.value);return a.value+" "+a.units},onSliderChangeComplete:function(a,b,c,d){var e=a.timeManager;if(b!==e.currentValue){switch(a.indexMap[c.index]){case "primary":d=a.indexMap.indexOf("tail");if(-1<d)a.onSliderChangeComplete(a,a.thumbs[d].value,a.thumbs[d],!0);!e.snapToList&&e.timeUnits?(a=Math[b>e.currentValue?"ceil":"floor"]((b-e.currentValue)/OpenLayers.TimeStep[e.timeUnits]),e.setCurrentValue(e.incrementTimeValue(a))):e.setCurrentValue(b);break;case "min":e.setAnimationStart(b); break;case "max":e.seAnimantionEnd(b);break;case "tail":c=0;for(var f=e.agents.length;c<f;c++)"range"==e.agents[c].tickMode&&(e.agents[c].rangeInterval=a.thumbs[0].value-b);d||e.setCurrentValue(a.thumbs[0].value)}this._restartPlayback&&(delete this._restartPlayback,e.play())}},onRender:function(){this.autoEl={cls:"x-slider "+(this.vertical?"x-slider-vert":"x-slider-horz"),cn:[{cls:"x-slider-end",cn:{cls:"x-slider-inner",cn:[{tag:"a",cls:"x-slider-focus",href:"#",tabIndex:"-1",hidefocus:"on"}]}},{cls:"x-slider-progress"}]}; Ext.slider.MultiSlider.superclass.onRender.apply(this,arguments);this.endEl=this.el.first();this.progressEl=this.el.child(".x-slider-progress");this.innerEl=this.endEl.first();this.focusEl=this.innerEl.child(".x-slider-focus");for(var a=0;a<this.thumbs.length;a++)this.thumbs[a].render();a=this.innerEl.child(".x-slider-thumb");this.halfThumb=(this.vertical?a.getHeight():a.getWidth())/2;this.initEvents()}});Ext.reg("gxp_timeslider",gxp.slider.TimeSlider);Ext.namespace("gxp"); gxp.PlaybackToolbar=Ext.extend(Ext.Toolbar,{control:null,dimModel:null,mapPanel:null,initialTime:null,timeFormat:"l, F d, Y g:i:s A",toolbarCls:"x-toolbar gx-overlay-playback",ctCls:"gx-playback-wrap",slider:!0,dynamicRange:!1,playbackMode:"track",showIntervals:!1,labelButtons:!1,settingsButton:!0,rateAdjuster:!1,looped:!1,autoPlay:!1,aggressive:null,prebuffer:null,maxframes:null,optionsWindow:null,playing:!1,playLabel:"Play",playTooltip:"Play",stopLabel:"Stop",stopTooltip:"Stop",fastforwardLabel:"FFWD", fastforwardTooltip:"Double Speed Playback",nextLabel:"Next",nextTooltip:"Advance One Frame",resetLabel:"Reset",resetTooltip:"Reset to the start",loopLabel:"Loop",loopTooltip:"Continously loop the animation",normalTooltip:"Return to normal playback",pauseLabel:"Pause",pauseTooltip:"Pause",initComponent:function(){this.playbackActions||(this.playbackActions="settings slider reset play fastforward next loop".split(" "));this.control||(this.controlConfig=Ext.applyIf(this.controlConfig||{},{dimension:"time", prebuffer:this.prebuffer,maxframes:this.maxframes,autoSync:!0}),this.control=this.buildTimeManager());this.control.events.on({play:function(a){this.playing=!0},stop:function(a){this.playing=!1},scope:this});this.dimModel||(this.dimModel=new OpenLayers.Dimension.Model({dimension:"time",map:this.mapPanel.map}));this.mapPanel.map.events.on({zoomend:function(){!0===this._prebuffer&&this.mapPanel.map.zoom!==this.previousZoom&&(this._stopPrebuffer=!0,this.slider.progressEl.hide(),this.mapPanel.map.events.un({zoomend:arguments.callee, scope:this}));this.previousZoom=this.mapPanel.map.zoom},scope:this});this.control.events.on({prebuffer:function(a){this._prebuffer=!0;!0===this._stopPrebuffer&&this.slider.progressEl.hide();this.slider.progressEl.setWidth(100*a.progress+"%");return!0!==this._stopPrebuffer},scope:this});this.availableTools=Ext.applyIf(this.availableTools||{},this.getAvailableTools());Ext.applyIf(this,{defaults:{xtype:"button",flex:1,scale:"small"},items:this.buildPlaybackItems(),border:!1,frame:!1,unstyled:!0,shadow:!1, timeDisplayConfig:{xtype:"tip",format:this.timeFormat,height:"auto",closeable:!1,title:!1,width:210}});this.addEvents("timechange","rangemodified");gxp.PlaybackToolbar.superclass.initComponent.call(this)},destroy:function(){this.control&&!this.initialConfig.control&&(this.control.map&&this.control.map.removeControl(this.control),this.control.destroy(),this.control=null);this.mapPanel=null;gxp.PlaybackToolbar.superclass.destroy.call(this)},setTime:function(a){a=a.getTime();if(a<this.slider.minValue|| a>this.slider.maxValue)return!1;this.control.setCurrentValue(a);return!0},setTimeFormat:function(a){a&&(this.timeFormat=a,this.slider.setTimeFormat(a))},setPlaybackMode:function(a){a&&(this.playbackMode=a,this.slider&&this.slider.setPlaybackMode(a))},buildPlaybackItems:function(){for(var a=this.playbackActions,b=[],c=0,d=a.length;c<d;c++){var e=a[c],f=this.availableTools[e];f?b.push(f):-1<["|"," ","->"].indexOf(e)&&b.push(e)}return b},getAvailableTools:function(){return{slider:{xtype:"gxp_timeslider", ref:"slider",listeners:{sliderclick:{fn:function(){this._stopPrebuffer=!0},scope:this},dragstart:{fn:function(){this._stopPrebuffer=!0},scope:this}},map:this.mapPanel.map,timeManager:this.control,model:this.dimModel,playbackMode:this.playbackMode,aggressive:this.aggressive},reset:{iconCls:"gxp-icon-reset",ref:"btnReset",handler:this.control.reset,scope:this.control,tooltip:this.resetTooltip,menuText:this.resetLabel,text:this.labelButtons?this.resetLabel:!1},pause:{iconCls:"gxp-icon-pause",ref:"btnPause", handler:this.control.stop,scope:this.control,tooltip:this.stopTooltip,menuText:this.stopLabel,text:this.labelButtons?this.stopLabel:!1,toggleGroup:"timecontrol",enableToggle:!0,allowDepress:!1},play:{iconCls:"gxp-icon-play",ref:"btnPlay",toggleHandler:this.toggleAnimation,scope:this,toggleGroup:"timecontrol",enableToggle:!0,allowDepress:!0,tooltip:this.playTooltip,menuText:this.playLabel,text:this.labelButtons?this.playLabel:!1},next:{iconCls:"gxp-icon-next",ref:"btnNext",handler:function(){this.stop(); this.tick()},scope:this.control,tooltip:this.nextTooltip,menuText:this.nextLabel,text:this.labelButtons?this.nextLabel:!1},end:{iconCls:"gxp-icon-last",ref:"btnEnd",handler:this.forwardToEnd,scope:this,tooltip:this.endTooltip,menuText:this.endLabel,text:this.labelButtons?this.endLabel:!1},loop:{iconCls:"gxp-icon-loop",ref:"btnLoop",tooltip:this.loopTooltip,enableToggle:!0,allowDepress:!0,pressed:this.looped,toggleHandler:this.toggleLoopMode,scope:this,menuText:this.loopLabel,text:this.labelButtons? this.loopLabel:!1},fastforward:{iconCls:"gxp-icon-ffwd",ref:"btnFastforward",tooltip:this.fastforwardTooltip,enableToggle:!0,toggleGroup:"fastforward",toggleHandler:this.toggleDoubleSpeed,scope:this,disabled:!0,menuText:this.fastforwardLabel,text:this.labelButtons?this.fastforwardLabel:!1},settings:{iconCls:"gxp-icon-settings",ref:"btnSettings",scope:this,handler:this.toggleOptionsWindow,enableToggle:!1,tooltip:this.settingsTooltip,menuText:this.settingsLabel,text:this.labelButtons?this.settingsLabel: !1}}},buildTimeManager:function(){this.controlConfig||(this.controlConfig={});this.controlConfig.timeAgents&&(this.controlConfig.agents=this.controlConfig.timeAgents,delete this.controlConfig.timeAgents);if(this.controlConfig.agents)for(var a=0;a<this.controlConfig.agents.length;a++){var b=this.controlConfig.agents[a],c=b.type,d=[];Ext.each(b.layers,function(a){var b=this.mapPanel.layers.findBy(function(b){return b.json&&b.json.source==a.source&&b.json.title==a.title&&b.json.name==a.name&&(b.json.styles== a.styles||0==!!b.json.styles&&0==!!a.styles)});-1<b&&d.push(this.mapPanel.layers.getAt(b).getLayer())},this);b.layers=d;b.rangeMode&&(b.tickMode=b.rangeMode,delete b.rangeMode);delete b.type;b.dimension||(b.dimension="time");b=c&&OpenLayers.Dimension.Agent[c]?new OpenLayers.Dimension.Agent[c](b):new OpenLayers.Dimension.Agent(b);this.controlConfig.agents[a]=b}else"ranged"==this.playbackMode?Ext.apply(this.controlConfig,{agentOptions:{WMS:{tickMode:"range",rangeInterval:this.controlConfig.rangeInterval|| void 0},Vector:{tickMode:"range",rangeInterval:this.controlConfig.rangeInterval||void 0}}}):"cumulative"==this.playbackMode&&Ext.apply(this.controlConfig,{agentOptions:{WMS:{tickMode:"cumulative"},Vector:{tickMode:"cumulative"}}});this.controlConfig.dimension||(this.controlConfig.dimension="time");a=this.control=new OpenLayers.Control.DimensionManager(this.controlConfig);a.loop=this.looped;this.mapPanel.map.addControl(a);a.layers&&this.fireEvent("rangemodified",this,a.range);return a},forwardToEnd:function(a){a= this.control;a.setCurrentValue(a.animationRange[0>a.step?0:1])},toggleAnimation:function(a,b){!a.bound&&b&&(this.control.events.on({stop:function(b){a.toggle(!1);b.rangeExceeded&&(this._resetOnPlay=!0)},play:function(b){a.toggle(!0);this._resetOnPlay&&(this.reset(),delete this._resetOnPlay)}}),a.bound=!0);b?(this.playing||this.control.play(),a.btnEl.removeClass("gxp-icon-play"),a.btnEl.addClass("gxp-icon-pause"),a.setTooltip(this.pauseTooltip)):(this.playing&&this.control.stop(),a.btnEl.addClass("gxp-icon-play"), a.btnEl.removeClass("gxp-icon-pause"),a.setTooltip(this.playTooltip));a.el.removeClass("x-btn-pressed");a.refOwner.btnFastforward.setDisabled(!b);this.labelButtons&&a.text&&a.setText(b?this.pauseLabel:this.playLabel)},toggleLoopMode:function(a,b){this.control.loop=b;a.setTooltip(b?this.normalTooltip:this.loopTooltip);this.labelButtons&&a.text&&a.setText(b?this.normalLabel:this.loopLabel)},toggleDoubleSpeed:function(a,b){this.control.setFrameRate(this.control.frameRate*(b?2:.5));a.setTooltip(b?this.normalTooltip: this.fastforwardTooltip)},toggleOptionsWindow:function(a,b){b&&this.optionsWindow.hidden?(this.optionsWindow.optionsPanel.timeManager||(this.optionsWindow.optionsPanel.timeManager=this.control,this.optionsWindow.optionsPanel.playbackToolbar=this),this.optionsWindow.show()):b||this.optionsWindow.hidden||this.optionsWindow.hide()}});gxp.PlaybackToolbar.timeFormats={Minutes:"l, F d, Y g:i A",Hours:"l, F d, Y g A",Days:"l, F d, Y",Months:"F, Y",Years:"Y"}; gxp.PlaybackToolbar.guessTimeFormat=function(a){if(a){a=gxp.PlaybackToolbar.smartIntervalFormat(a).units;var b=this.timeFormat;gxp.PlaybackToolbar.timeFormats[a]&&(b=gxp.PlaybackToolbar.timeFormats[a]);return b}}; gxp.PlaybackToolbar.smartIntervalFormat=function(a){var b;b=Math.abs(a);5E3>b?(b="Seconds",a=Math.round(a/100)/10):35E5>b?(b="Minutes",a=Math.round(a/600)/10):828E5>b?(b="Hours",a=Math.round(a/36E4)/10):25E8>b?(b="Days",a=Math.round(a/864E4)/10):311E8>b?(b="Months",a=Math.round(a/2628E5)/10):(b="Years",a=Math.round(a/31536E5)/10);return{units:b,value:a}};Ext.reg("gxp_playbacktoolbar",gxp.PlaybackToolbar);Ext.namespace("gxp.plugins"); gxp.plugins.FeatureManager=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_featuremanager",maxFeatures:100,paging:!0,pagingType:null,autoZoomPage:!1,autoSetLayer:!0,autoLoadFeatures:!1,layerRecord:null,featureStore:null,hitCountProtocol:null,featureLayer:null,schema:null,geometryType:null,toolsShowingLayer:null,selectStyle:null,style:null,pages:null,page:null,numberOfFeatures:null,numPages:null,pageIndex:null,constructor:function(a){this.addEvents("beforequery","query","beforelayerchange","layerchange","beforesetpage", "setpage","beforeclearfeatures","clearfeatures","beforesave","exception");a&&!a.pagingType&&(this.pagingType=gxp.plugins.FeatureManager.QUADTREE_PAGING);a&&a.layer&&(this.autoSetLayer=!1);gxp.plugins.FeatureManager.superclass.constructor.apply(this,arguments)},init:function(a){gxp.plugins.FeatureManager.superclass.init.apply(this,arguments);this.toolsShowingLayer={};this.style={all:new OpenLayers.Style(null,{rules:[new OpenLayers.Rule({symbolizer:this.initialConfig.symbolizer||{Point:{pointRadius:4, graphicName:"square",fillColor:"white",fillOpacity:1,strokeWidth:1,strokeOpacity:1,strokeColor:"#333333"},Line:{strokeWidth:4,strokeOpacity:1,strokeColor:"#ff9933"},Polygon:{strokeWidth:2,strokeOpacity:1,strokeColor:"#ff6633",fillColor:"white",fillOpacity:.3}}})]}),selected:new OpenLayers.Style(null,{rules:[new OpenLayers.Rule({symbolizer:{display:"none"}})]})};this.featureLayer=new OpenLayers.Layer.Vector(this.id,{displayInLayerSwitcher:!1,visibility:!1,styleMap:new OpenLayers.StyleMap({select:Ext.applyIf(Ext.apply({display:""}, this.selectStyle),OpenLayers.Feature.Vector.style.select),vertex:this.style.all},{extendDefault:!1})});this.target.on({ready:function(){this.target.mapPanel.map.addLayer(this.featureLayer)},scope:this});this.on({beforedestroy:function(){this.target.mapPanel.map.removeLayer(this.featureLayer)},scope:this})},activate:function(){if(gxp.plugins.FeatureManager.superclass.activate.apply(this,arguments)){if(this.autoSetLayer)this.target.on("beforelayerselectionchange",this.setLayer,this);if(this.layer){var a= Ext.apply({},this.layer);this.target.createLayerRecord(a,this.setLayer,this)}this.on("layerchange",this.setSchema,this);return!0}},deactivate:function(){if(gxp.plugins.FeatureManager.superclass.deactivate.apply(this,arguments))return this.autoSetLayer&&this.target.un("beforelayerselectionchange",this.setLayer,this),this.un("layerchange",this.setSchema,this),this.setLayer(),!0},getPageExtent:function(){return this.pagingType===gxp.plugins.FeatureManager.QUADTREE_PAGING?this.page.extent:this.featureStore.layer.getDataExtent()}, setLayer:function(a){var b=this.fireEvent("beforelayerchange",this,a);!1!==b&&(a&&(this.featureLayer.projection=a.getLayer().projection),a!==this.layerRecord&&(this.clearFeatureStore(),(this.layerRecord=a)?!0===this.autoLoadFeatures?this.loadFeatures():this.setFeatureStore():this.fireEvent("layerchange",this,null)));return b},setSchema:function(a,b,c){this.schema=c},showLayer:function(a,b){this.toolsShowingLayer[a]=b||"all";this.setLayerDisplay()},hideLayer:function(a){delete this.toolsShowingLayer[a]; this.setLayerDisplay()},setLayerDisplay:function(){var a=this.visible(),b=this.target.mapPanel.map;a?(a=this.style[a],a!==this.featureLayer.styleMap.styles["default"]&&(this.featureLayer.styleMap.styles["default"]=a,this.featureLayer.redraw()),this.featureLayer.setVisibility(!0),b.events.on({addlayer:this.raiseLayer,scope:this})):this.featureLayer.map&&(this.featureLayer.setVisibility(!1),b.events.un({addlayer:this.raiseLayer,scope:this}))},visible:function(){var a=!1,b;for(b in this.toolsShowingLayer)"all"!= a&&(a=this.toolsShowingLayer[b]);return a},raiseLayer:function(){var a=this.featureLayer&&this.featureLayer.map;a&&a.setLayerIndex(this.featureLayer,a.layers.length)},loadFeatures:function(a,b,c){if(!1!==this.fireEvent("beforequery",this,a,b,c)){this.filter=a;this.pages=null;if(b){var d=this;d._activeQuery&&d.un("query",d._activeQuery);this.on("query",d._activeQuery=function(a,f){delete d._activeQuery;this.un("query",arguments.callee,this);f.getCount();0==f.getCount()?b.call(c,[]):this.featureLayer.events.register("featuresadded", this,function(a){this.featureLayer.events.unregister("featuresadded",this,arguments.callee);b.call(c,a.features)})},this,{single:!0})}this.featureStore?(this.featureStore.setOgcFilter(a),this.paging?this.setPage():this.featureStore.load()):(this.paging&&this.on("layerchange",function(a,b,c){c&&(this.un("layerchange",arguments.callee,this),this.setPage())},this),this.setFeatureStore(a,!this.paging))}},clearFeatures:function(){var a=this.featureStore;a&&!1!==this.fireEvent("beforeclearfeatures",this)&& (a.removeAll(),this.fireEvent("clearfeatures",this),a=a.proxy,a.abortRequest(),a.protocol.response&&a.protocol.response.abort())},getProjection:function(a){var b=this.target.mapPanel.map.getProjectionObject();(a=a.getLayer().projection)&&a.equals(b)&&(b=a);return b},setFeatureStore:function(a,b){var c=this.layerRecord,d=this.target.getSource(c);d&&d instanceof gxp.plugins.WMSSource?d.getSchema(c,function(d){if(!1===d)this.clearFeatureStore();else{var f=[],g,h=/gml:((Multi)?(Point|Line|Polygon|Curve|Surface|Geometry)).*/, k={"xsd:boolean":"boolean","xsd:int":"int","xsd:integer":"int","xsd:short":"int","xsd:long":"int","xsd:date":"date","xsd:string":"string","xsd:float":"float","xsd:double":"float"};d.each(function(a){var b=h.exec(a.get("type"));b?(g=a.get("name"),this.geometryType=b[1]):(b=k[a.get("type")],a={name:a.get("name"),type:k[b]},"date"==b&&(a.dateFormat="Y-m-d\\Z"),f.push(a))},this);var l={srsName:this.getProjection(c).getCode(),url:d.url,featureType:d.reader.raw.featureTypes[0].typeName,featureNS:d.reader.raw.targetNamespace, geometryName:g};this.hitCountProtocol=new OpenLayers.Protocol.WFS(Ext.apply({version:"1.1.0",readOptions:{output:"object"},resultType:"hits",filter:a},l));this.featureStore=new gxp.data.WFSFeatureStore(Ext.apply({fields:f,proxy:{protocol:{outputFormat:this.format,multi:this.multi}},maxFeatures:this.maxFeatures,layer:this.featureLayer,ogcFilter:a,autoLoad:b,autoSave:!1,listeners:{beforewrite:function(a,b,c,d){this.fireEvent("beforesave",this,a,d.params)},write:function(a,b,d,e,f){this.redrawMatchingLayers(c)}, load:function(a,b,c){this.fireEvent("query",this,a,this.filter)},scope:this}},l))}this.fireEvent("layerchange",this,c,d)},this):(this.clearFeatureStore(),this.fireEvent("layerchange",this,c,!1))},redrawMatchingLayers:function(a){var b=a.get("name"),c=a.get("source");this.target.mapPanel.layers.each(function(a){a.get("source")===c&&a.get("name")===b&&a.getLayer().redraw(!0)})},clearFeatureStore:function(){this.featureStore&&(this.featureStore.removeAll(),this.featureStore.unbind(),this.featureStore.destroy(), this.geometryType=this.featureStore=this.numberOfFeatures=null)},processPage:function(a,b,c,d){b=b||{};var e=b.lonLat?null:b.index,f=b.next,g=this.pages,h=this.pages.indexOf(a);this.setPageFilter(a);var k=f?h==(g.indexOf(f)||g.length)-1:!0,l=b.lonLat?a.extent.containsLonLat(b.lonLat):!0;l&&a.numFeatures&&a.numFeatures<=this.maxFeatures?c.call(this,a):l&&(h==e||k)&&this.hitCountProtocol.read({callback:function(h){var k=e,l=b.lonLat;f&&(k=(g.indexOf(f)||g.length)-1);!k&&l&&a.extent.containsLonLat(l)&& (k=g.indexOf(a));a.numFeatures=h.numberOfFeatures;this.page||(a.numFeatures>this.maxFeatures?this.createLeaf(a,Ext.applyIf({index:k,next:f},b),c,d):0==a.numFeatures&&1<g.length?(g.remove(a),!1===b.allowEmpty&&this.setPage({index:e%this.pages.length,allowEmpty:!1})):this.pages.indexOf(a)==k&&c.call(this,a))},scope:this})},createLeaf:function(a,b,c,d){b=b||{};this.layerRecord.getLayer();var e=this.pages.indexOf(a);this.pages.remove(a);var f=a.extent,g=f.getCenterLonLat();a=[f.left,g.lon,f.left,g.lon]; for(var h=[g.lat,g.lat,f.bottom,f.bottom],k=[g.lon,f.right,g.lon,f.right],f=[f.top,f.top,g.lat,g.lat],l,g=3;0<=g;--g)l={extent:new OpenLayers.Bounds(a[g],h[g],k[g],f[g])},this.pages.splice(e,0,l),this.processPage(l,b,c,d)},getPagingExtent:function(a){var b=this.layerRecord.getLayer(),c=this.getSpatialFilter();(a=c?c.value:this.target.mapPanel.map[a]())&&b.maxExtent&&a.containsBounds(b.maxExtent)&&(a=b.maxExtent);return a},getSpatialFilter:function(){var a;if(this.filter instanceof OpenLayers.Filter.Spatial&& this.filter.type===OpenLayers.Filter.Spatial.BBOX)a=this.filter;else if(this.filter instanceof OpenLayers.Filter.Logical&&this.filter.type===OpenLayers.Filter.Logical.AND)for(var b,c=this.filter.filters.length-1;0<=c;--c)if(b=this.filter.filters[c],b instanceof OpenLayers.Filter.Spatial&&b.type===OpenLayers.Filter.Spatial.BBOX){a=b;break}return a},setPageFilter:function(a){a.extent?(a=new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.BBOX,property:this.featureStore.geometryName,value:a.extent}), a=this.filter?new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.AND,filters:[this.filter,a]}):a):a=this.filter;this.featureStore.setOgcFilter(a);this.hitCountProtocol.filter=a;return this.hitCountProtocol.options.filter=a},nextPage:function(a,b){var c;this.pagingType===gxp.plugins.FeatureManager.QUADTREE_PAGING?(c=this.page,this.page=null,c=(this.pages.indexOf(c)+1)%this.pages.length):c=this.pageIndex+1%this.numPages;this.setPage({index:c,allowEmpty:!1},a,b)},previousPage:function(a,b){var c; this.pagingType===gxp.plugins.FeatureManager.QUADTREE_PAGING?(c=this.pages.indexOf(this.page)-1,0>c&&(c=this.pages.length-1)):(c=this.pageIndex-1,0>c&&(c=this.numPages-1));this.setPage({index:c,allowEmpty:!1,next:this.page},a)},setPage:function(a,b,c){if(this.pagingType===gxp.plugins.FeatureManager.QUADTREE_PAGING)if(this.filter instanceof OpenLayers.Filter.FeatureId)this.featureStore.load({callback:function(){b&&b.call(c)}});else{if(!1!==this.fireEvent("beforesetpage",this,a,b,c)){if(!a){var d=this.getPagingExtent("getExtent"), d=new OpenLayers.LonLat(d.left,d.top),e=this.target.mapPanel.map.getMaxExtent();e.containsLonLat(d,!0)||(d=new OpenLayers.LonLat(e.left,e.top));a={lonLat:d,allowEmpty:!1}}a.index=a.index||0;"last"==a.index&&(a.index=this.pages.length-1,a.next=this.pages[0]);this.page=null;if(!this.pages)this.layerRecord.getLayer(),this.pages=[{extent:this.getPagingExtent("getMaxExtent")}],a.index=0;else if(a.lonLat)for(d=this.pages.length-1;0<=d;--d)if(this.pages[d].extent.containsLonLat(a.lonLat)){a.index=d;break}this.processPage(this.pages[a.index], a,function(d){var e=this.target.mapPanel.map;this.page=d;this.setPageFilter(d);this.autoZoomPage&&!e.getExtent().containsLonLat(d.extent.getCenterLonLat())&&e.zoomToExtent(d.extent);e=this.pages.indexOf(this.page);this.fireEvent("setpage",this,a,b,c,e,this.pages.length);this.featureStore.load({callback:function(){b&&b.call(c,d)}})},this)}}else!1!==this.fireEvent("beforesetpage",this,a,b,c)&&(a?null!=a.index&&(this.pageIndex="last"===a.index?this.numPages-1:"first"===a.index?0:a.index,d=this.pageIndex* this.maxFeatures,this.fireEvent("setpage",this,a,b,c,this.pageIndex,this.numPages),this.featureStore.load({startIndex:d,callback:function(){b&&b.call(c)}})):this.hitCountProtocol.read({filter:this.filter,callback:function(d){this.numberOfFeatures=d.numberOfFeatures;this.numPages=Math.ceil(this.numberOfFeatures/this.maxFeatures);this.pageIndex=0;this.fireEvent("setpage",this,a,b,c,this.pageIndex,this.numPages);this.featureStore.load({output:"object",callback:function(){b&&b.call(c)}})},scope:this}))}}); gxp.plugins.FeatureManager.QUADTREE_PAGING=0;gxp.plugins.FeatureManager.WFS_PAGING=1;Ext.preg(gxp.plugins.FeatureManager.prototype.ptype,gxp.plugins.FeatureManager);Ext.namespace("gxp.plugins"); gxp.plugins.ZoomToSelectedFeatures=Ext.extend(gxp.plugins.ZoomToExtent,{ptype:"gxp_zoomtoselectedfeatures",menuText:"Zoom to selected features",tooltip:"Zoom to selected features",closest:!1,layer:null,iconCls:"gxp-icon-zoom-to",extent:function(){for(var a,b,c=this.target.tools[this.featureManager].featureLayer.selectedFeatures,d=c.length-1;0<=d;--d)if(b=c[d].geometry)b=b.getBounds(),a?a.extend(b):a=b.clone();return a},addActions:function(){function a(){this.layer&&this.layer.events.un(c);if(this.layer= d.featureLayer)this.layer.events.on(c)}var b=gxp.plugins.ZoomToSelectedFeatures.superclass.addActions.apply(this,arguments);b[0].disable();var c={featureselected:function(a){b[0].isDisabled()&&null!==a.feature.geometry&&b[0].enable()},featureunselected:function(){0===this.layer.selectedFeatures.length&&b[0].disable()},scope:this},d=this.target.tools[this.featureManager];this.target.on("layerselectionchange",a);d.on("query",function(){b[0].disable()});a.call(this);return b}}); Ext.preg(gxp.plugins.ZoomToSelectedFeatures.prototype.ptype,gxp.plugins.ZoomToSelectedFeatures);Ext.namespace("gxp.plugins"); gxp.plugins.FeatureGrid=Ext.extend(gxp.plugins.ClickableFeatures,{ptype:"gxp_featuregrid",schema:null,showTotalResults:!1,alwaysDisplayOnMap:!1,displayMode:"all",autoExpand:!1,autoCollapse:!1,selectOnMap:!1,displayFeatureText:"Display on map",firstPageTip:"First page",previousPageTip:"Previous page",zoomPageExtentTip:"Zoom to page extent",nextPageTip:"Next page",lastPageTip:"Last page",totalMsg:"Features {1} to {2} of {0}",displayTotalResults:function(){var a=this.target.tools[this.featureManager]; !0===this.showTotalResults&&this.displayItem.setText(null!==a.numberOfFeatures?String.format(this.totalMsg,a.numberOfFeatures,a.pageIndex*a.maxFeatures+Math.min(a.numberOfFeatures,1),Math.min((a.pageIndex+1)*a.maxFeatures,a.numberOfFeatures)):"")},addOutput:function(a){function b(){var a=c.schema,b=["feature","state","fid"];a&&a.each(function(a){0==a.get("type").indexOf("gml:")&&b.push(a.get("name"))});f.ignoreFields=b;f.setStore(c.featureStore,a);c.featureStore||(c.paging&&(f.lastPageButton.disable(), f.nextPageButton.disable(),f.firstPageButton.disable(),f.prevPageButton.disable(),f.zoomToPageButton.disable()),this.displayTotalResults())}var c=this.target.tools[this.featureManager],d=this.target.mapPanel.map,e;this.selectControl=new OpenLayers.Control.SelectFeature(c.featureLayer,this.initialConfig.controlOptions);if(this.selectOnMap){if(this.autoLoadFeature||c.paging&&c.pagingType===gxp.plugins.FeatureManager.QUADTREE_PAGING)this.selectControl.events.on({activate:function(){d.events.register("click", this,this.noFeatureClick)},deactivate:function(){d.events.unregister("click",this,this.noFeatureClick)},scope:this});d.addControl(this.selectControl);e={selectControl:this.selectControl}}else e={selectControl:this.selectControl,singleSelect:!1,autoActivateControl:!1,listeners:{beforerowselect:function(){if(window.event&&"contextmenu"==window.event.type||this.selectControl.active||c.featureStore.getModifiedRecords().length)return!1},scope:this}};this.displayItem=new Ext.Toolbar.TextItem({});a=Ext.apply({xtype:"gxp_featuregrid", border:!1,sm:new GeoExt.grid.FeatureSelectionModel(e),autoScroll:!0,columnMenuDisabled:!!c.paging,bbar:(c.paging?[{iconCls:"x-tbar-page-first",ref:"../firstPageButton",tooltip:this.firstPageTip,disabled:!0,handler:function(){c.setPage({index:0})}},{iconCls:"x-tbar-page-prev",ref:"../prevPageButton",tooltip:this.previousPageTip,disabled:!0,handler:function(){c.previousPage()}},{iconCls:"gxp-icon-zoom-to",ref:"../zoomToPageButton",tooltip:this.zoomPageExtentTip,disabled:!0,hidden:c.pagingType!==gxp.plugins.FeatureManager.QUADTREE_PAGING|| c.autoZoomPage,handler:function(){var a=c.getPageExtent();null!==a&&d.zoomToExtent(a)}},{iconCls:"x-tbar-page-next",ref:"../nextPageButton",tooltip:this.nextPageTip,disabled:!0,handler:function(){c.nextPage()}},{iconCls:"x-tbar-page-last",ref:"../lastPageButton",tooltip:this.lastPageTip,disabled:!0,handler:function(){c.setPage({index:"last"})}},{xtype:"tbspacer",width:10},this.displayItem]:[]).concat(["->"].concat(this.alwaysDisplayOnMap?[]:[{text:this.displayFeatureText,enableToggle:!0,toggleHandler:function(a, b){this.selectOnMap&&this.selectControl[b?"activate":"deactivate"]();c[b?"showLayer":"hideLayer"](this.id,this.displayMode)},scope:this}])),contextMenu:new Ext.menu.Menu({items:[]})},a||{});var f=gxp.plugins.FeatureGrid.superclass.addOutput.call(this,a);f.on({added:function(a,b){function d(){this.displayTotalResults();this.selectOnMap&&this.selectControl.deactivate();this.autoCollapse&&"function"==typeof b.collapse&&b.collapse()}c.on({query:function(a,c){c&&c.getCount()?(this.displayTotalResults(), this.selectOnMap&&this.selectControl.activate(),this.autoExpand&&"function"==typeof b.expand&&b.expand()):d.call(this)},layerchange:d,clearfeatures:d,scope:this})},contextmenu:function(a){if(0<f.contextMenu.items.getCount()){var b=f.getView().findRowIndex(a.getTarget());!1!==b&&(f.getSelectionModel().selectRow(b),f.contextMenu.showAt(a.getXY()),a.stopEvent())}},scope:this});(this.alwaysDisplayOnMap||!0===this.selectOnMap&&"selected"===this.displayMode)&&c.showLayer(this.id,this.displayMode);c.paging&& c.on({beforesetpage:function(){f.zoomToPageButton.disable()},setpage:function(a,b,c,d,e,q){a=0<q;f.zoomToPageButton.setDisabled(!a);b=a&&0!==e;f.firstPageButton.setDisabled(!b);f.prevPageButton.setDisabled(!b);e=a&&e!==q-1;f.lastPageButton.setDisabled(!e);f.nextPageButton.setDisabled(!e)},scope:this});c.featureStore&&b.call(this);c.on("layerchange",b,this);return f}});Ext.preg(gxp.plugins.FeatureGrid.prototype.ptype,gxp.plugins.FeatureGrid);Ext.namespace("gxp"); gxp.EmbedMapDialog=Ext.extend(Ext.Container,{url:null,url:null,publishMessage:"Your map is ready to be published to the web! Simply copy the following HTML to embed the map in your website:",heightLabel:"Height",widthLabel:"Width",mapSizeLabel:"Map Size",miniSizeLabel:"Mini",smallSizeLabel:"Small",premiumSizeLabel:"Premium",largeSizeLabel:"Large",snippetArea:null,heightField:null,widthField:null,initComponent:function(){Ext.apply(this,this.getConfig());gxp.EmbedMapDialog.superclass.initComponent.call(this)}, getIframeHTML:function(){return this.snippetArea.getValue()},updateSnippet:function(){this.snippetArea.setValue('<iframe style="border: none;" height="'+this.heightField.getValue()+'" width="'+this.widthField.getValue()+'" src="'+gxp.util.getAbsoluteUrl(this.url)+'"></iframe>');!0===this.snippetArea.isVisible()&&this.snippetArea.focus(!0,100)},getConfig:function(){this.snippetArea=new Ext.form.TextArea({height:70,selectOnFocus:!0,readOnly:!0});var a={change:this.updateSnippet,specialkey:function(a, c){c.getKey()==c.ENTER&&this.updateSnippet()},scope:this};this.heightField=new Ext.form.NumberField({width:50,value:400,listeners:a});this.widthField=new Ext.form.NumberField({width:50,value:600,listeners:a});return{border:!1,defaults:{border:!1,cls:"gxp-export-section",xtype:"container",layout:"fit"},items:[{items:[new Ext.Container({layout:"column",defaults:{border:!1,xtype:"box"},items:[{autoEl:{cls:"gxp-field-label",html:this.mapSizeLabel}},new Ext.form.ComboBox({editable:!1,width:75,store:new Ext.data.SimpleStore({fields:["name", "height","width"],data:[[this.miniSizeLabel,100,100],[this.smallSizeLabel,200,300],[this.largeSizeLabel,400,600],[this.premiumSizeLabel,600,800]]}),triggerAction:"all",displayField:"name",value:this.largeSizeLabel,mode:"local",listeners:{select:function(a,c,d){this.widthField.setValue(c.get("width"));this.heightField.setValue(c.get("height"));this.updateSnippet()},scope:this}}),{autoEl:{cls:"gxp-field-label",html:this.heightLabel}},this.heightField,{autoEl:{cls:"gxp-field-label",html:this.widthLabel}}, this.widthField]})]},{xtype:"box",autoEl:{tag:"p",html:this.publishMessage}},{items:[this.snippetArea]}],listeners:{afterrender:this.updateSnippet,scope:this}}}});Ext.reg("gxp_embedmapdialog",gxp.EmbedMapDialog);Ext.namespace("gxp.plugins"); gxp.plugins.LayerTree=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_layertree",shortTitle:"Layers",rootNodeText:"Layers",overlayNodeText:"Overlays",baseNodeText:"Base Layers",groups:null,defaultGroup:"default",treeNodeUI:null,constructor:function(a){gxp.plugins.LayerTree.superclass.constructor.apply(this,arguments);this.groups||(this.groups={"default":this.overlayNodeText,background:{title:this.baseNodeText,exclusive:!0}});this.treeNodeUI||(this.treeNodeUI=Ext.extend(GeoExt.tree.LayerNodeUI,new GeoExt.tree.TreeNodeUIEventMixin))}, addOutput:function(a){a=Ext.apply(this.createOutputConfig(),a||{});a=gxp.plugins.LayerTree.superclass.addOutput.call(this,a);a.on({contextmenu:this.handleTreeContextMenu,beforemovenode:this.handleBeforeMoveNode,scope:this});return a},createOutputConfig:function(){var a=new Ext.tree.TreeNode({text:this.rootNodeText,expanded:!0,isTarget:!1,allowDrop:!1}),b;this.initialConfig.loader&&this.initialConfig.loader.baseAttrs&&(b=this.initialConfig.loader.baseAttrs);var c=this.defaultGroup,d=this,e,f,g;for(g in this.groups)e= "string"==typeof this.groups[g]?{title:this.groups[g]}:this.groups[g],f=e.exclusive,a.appendChild(new GeoExt.tree.LayerContainer(Ext.apply({text:e.title,iconCls:"gxp-folder",expanded:!0,group:g==this.defaultGroup?void 0:g,loader:new GeoExt.tree.LayerLoader({baseAttrs:f?Ext.apply({checkedGroup:Ext.isString(f)?f:g},b):b,store:this.target.mapPanel.layers,filter:function(a){return function(b){return(b.get("group")||c)==a&&1==b.getLayer().displayInLayerSwitcher}}(g),createNode:function(a){d.configureLayerNode(this, a);return GeoExt.tree.LayerLoader.prototype.createNode.apply(this,arguments)}}),singleClickExpand:!0,allowDrag:!1,listeners:{append:function(a,b){b.expand()}}},e)));return{xtype:"treepanel",root:a,rootVisible:!1,shortTitle:this.shortTitle,border:!1,enableDD:!0,selModel:new Ext.tree.DefaultSelectionModel({listeners:{beforeselect:this.handleBeforeSelect,scope:this}}),contextMenu:new Ext.menu.Menu({items:[]})}},configureLayerNode:function(a,b){b.uiProvider=this.treeNodeUI;var c=b.layer,d=b.layerStore; if(c&&d){var e=d.getAt(d.findBy(function(a){return a.getLayer()===c}));e&&(b.qtip=e.get("abstract"),e.get("queryable")||b.iconCls||(b.iconCls="gxp-tree-rasterlayer-icon"),e.get("fixed")&&(b.allowDrag=!1),b.listeners={rendernode:function(a){e===this.target.selectedLayer&&a.select();this.target.on("layerselectionchange",function(b){this.selectionChanging||b!==e||a.select()},this)},scope:this})}},handleBeforeSelect:function(a,b){var c=!0,d=b&&b.layer,e;d&&(c=b.layerStore,e=c.getAt(c.findBy(function(a){return a.getLayer()=== d})));this.selectionChanging=!0;c=this.target.selectLayer(e);this.selectionChanging=!1;return c},handleTreeContextMenu:function(a,b){if(a&&a.layer){a.select();var c=a.getOwnerTree();c.getSelectionModel().getSelectedNode()===a&&(c=c.contextMenu,c.contextNode=a,0<c.items.getCount()&&c.showAt(b.getXY()))}},handleBeforeMoveNode:function(a,b,c,d,e){c!==d&&(a=d.loader.store,c=a.findBy(function(a){return a.getLayer()===b.layer}),a.getAt(c).set("group",d.attributes.group))}}); Ext.preg(gxp.plugins.LayerTree.prototype.ptype,gxp.plugins.LayerTree);Ext.namespace("gxp.plugins"); gxp.plugins.LayerManager=Ext.extend(gxp.plugins.LayerTree,{ptype:"gxp_layermanager",baseNodeText:"Base Maps",createOutputConfig:function(){var a=gxp.plugins.LayerManager.superclass.createOutputConfig.apply(this,arguments);Ext.applyIf(a,Ext.apply({cls:"gxp-layermanager-tree",lines:!1,useArrows:!0,plugins:[{ptype:"gx_treenodecomponent"}]},this.treeConfig));return a},configureLayerNode:function(a,b){gxp.plugins.LayerManager.superclass.configureLayerNode.apply(this,arguments);var c;OpenLayers.Layer.WMS&& b.layer instanceof OpenLayers.Layer.WMS?c="gx_wmslegend":OpenLayers.Layer.Vector&&b.layer instanceof OpenLayers.Layer.Vector&&(c="gx_vectorlegend");if(c){var d;a&&a.baseAttrs&&a.baseAttrs.baseParams&&(d=a.baseAttrs.baseParams);Ext.apply(b,{component:{xtype:c,hidden:!b.layer.getVisibility(),baseParams:Ext.apply({transparent:!0,format:"image/png",legend_options:"fontAntiAliasing:true;fontSize:11;fontName:Arial"},d),layerRecord:this.target.mapPanel.layers.getByLayer(b.layer),showTitle:!1,cls:"legend"}})}}}); Ext.preg(gxp.plugins.LayerManager.prototype.ptype,gxp.plugins.LayerManager);Ext.namespace("gxp.plugins"); gxp.plugins.Zoom=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_zoom",zoomMenuText:"Zoom Box",zoomInMenuText:"Zoom In",zoomOutMenuText:"Zoom Out",zoomTooltip:"Zoom by dragging a box",zoomInTooltip:"Zoom in",zoomOutTooltip:"Zoom out",constructor:function(a){gxp.plugins.Zoom.superclass.constructor.apply(this,arguments)},addActions:function(){var a=[{menuText:this.zoomInMenuText,iconCls:"gxp-icon-zoom-in",tooltip:this.zoomInTooltip,handler:function(){this.target.mapPanel.map.zoomIn()},scope:this},{menuText:this.zoomOutMenuText, iconCls:"gxp-icon-zoom-out",tooltip:this.zoomOutTooltip,handler:function(){this.target.mapPanel.map.zoomOut()},scope:this}];this.showZoomBoxAction&&a.unshift(new GeoExt.Action({menuText:this.zoomText,iconCls:"gxp-icon-zoom",tooltip:this.zoomTooltip,control:new OpenLayers.Control.ZoomBox(this.controlOptions),map:this.target.mapPanel.map,enableToggle:!0,allowDepress:!1,toggleGroup:this.toggleGroup}));return gxp.plugins.Zoom.superclass.addActions.apply(this,[a])}}); Ext.preg(gxp.plugins.Zoom.prototype.ptype,gxp.plugins.Zoom);Ext.namespace("gxp.form"); gxp.form.FontComboBox=Ext.extend(Ext.form.ComboBox,{fonts:"Serif;SansSerif;Arial;Courier New;Tahoma;Times New Roman;Verdana".split(";"),defaultFont:"Serif",allowBlank:!1,mode:"local",triggerAction:"all",editable:!1,initComponent:function(){var a=this.fonts||gxp.form.FontComboBox.prototype.fonts,b=this.defaultFont;-1===a.indexOf(this.defaultFont)&&(b=a[0]);a={displayField:"field1",valueField:"field1",store:a,value:b,tpl:new Ext.XTemplate('<tpl for="."><div class="x-combo-list-item"><span style="font-family: {field1};">{field1}</span></div></tpl>')}; Ext.applyIf(this,a);gxp.form.FontComboBox.superclass.initComponent.call(this)}});Ext.reg("gxp_fontcombo",gxp.form.FontComboBox);Ext.namespace("gxp"); gxp.WMSLayerPanel=Ext.extend(Ext.TabPanel,{layerRecord:null,source:null,styling:!0,sameOriginStyling:!0,rasterStyling:!1,transparent:null,editableStyles:!1,activeTab:0,border:!1,imageFormats:/png|gif|jpe?g/i,aboutText:"About",titleText:"Title",attributionText:"Attribution",nameText:"Name",descriptionText:"Description",displayText:"Display",opacityText:"Opacity",formatText:"Tile format",infoFormatText:"Info format",infoFormatEmptyText:"Select a format",transparentText:"Transparent",cacheText:"Caching", cacheFieldText:"Use cached tiles",stylesText:"Available Styles",displayOptionsText:"Display options",queryText:"Limit with filters",scaleText:"Limit by scale",minScaleText:"Min scale",maxScaleText:"Max scale",switchToFilterBuilderText:"Switch back to filter builder",cqlPrefixText:"or ",cqlText:"use CQL filter instead",singleTileText:"Single tile",singleTileFieldText:"Use a single tile",initComponent:function(){this.cqlFormat=new OpenLayers.Format.CQL;this.source&&this.source.getSchema(this.layerRecord, function(a){if(!1!==a){var c=this.layerRecord.getLayer().params.CQL_FILTER;this.filterBuilder=new gxp.FilterBuilder({filter:c&&this.cqlFormat.read(c),allowGroups:!1,listeners:{afterrender:function(){this.filterBuilder.cascade(function(a){"toolbar"===a.getXType()&&(a.addText(this.cqlPrefixText),a.addButton({text:this.cqlText,handler:this.switchToCQL,scope:this}))},this)},change:function(a){a=a.getFilter();var b=null;!1!==a&&(b=this.cqlFormat.write(a));this.layerRecord.getLayer().mergeNewParams({CQL_FILTER:b})}, scope:this},attributes:a});this.filterFieldset.add(this.filterBuilder);this.filterFieldset.doLayout()}},this);this.addEvents("change");this.items=[this.createAboutPanel(),this.createDisplayPanel()];if(this.styling&&gxp.WMSStylesDialog&&this.layerRecord.get("styles")){var a=this.layerRecord.get("restUrl");a||(a=(this.source||this.layerRecord.get("layer")).url.split("?").shift().replace(/\/(wms|ows)\/?$/,"/rest"));this.editableStyles=this.sameOriginStyling?"/"===a.charAt(0):!0;this.items.push(this.createStylesPanel(a))}gxp.WMSLayerPanel.superclass.initComponent.call(this)}, switchToCQL:function(){var a=this.filterBuilder.getFilter(),b="";!1!==a&&(b=this.cqlFormat.write(a));this.filterBuilder.hide();this.cqlField.setValue(b);this.cqlField.show();this.cqlToolbar.show()},switchToFilterBuilder:function(){var a=null;try{a=this.cqlFormat.read(this.cqlField.getValue())}catch(b){}this.cqlField.hide();this.cqlToolbar.hide();this.filterBuilder.show();null!==a&&this.filterBuilder.setFilter(a)},createStylesPanel:function(a){a=gxp.WMSStylesDialog.createGeoServerStylerConfig(this.layerRecord, a);!0===this.rasterStyling&&a.plugins.push({ptype:"gxp_wmsrasterstylesdialog"});var b=this.ownerCt;b.ownerCt instanceof Ext.Window||(a.dialogCls=Ext.Panel,a.showDlg=function(a){a.layout="fit";a.autoHeight=!1;b.add(a)});return Ext.apply(a,{title:this.stylesText,style:"padding: 10px",editable:!1})},createAboutPanel:function(){return{title:this.aboutText,bodyStyle:{padding:"10px"},defaults:{border:!1},items:[{layout:"form",labelWidth:70,items:[{xtype:"textfield",fieldLabel:this.titleText,anchor:"99%", value:this.layerRecord.get("title"),listeners:{change:function(a){this.layerRecord.set("title",a.getValue());this.layerRecord.commit();this.fireEvent("change")},scope:this}},{xtype:"textfield",fieldLabel:this.nameText,anchor:"99%",value:this.layerRecord.get("name"),readOnly:!0},{xtype:"textfield",fieldLabel:this.attributionText,anchor:"99%",listeners:{change:function(a){var b=this.layerRecord.getLayer();b.attribution=a.getValue();b.map.events.triggerEvent("changelayer",{layer:b,property:"attribution"}); this.fireEvent("change")},scope:this},value:this.layerRecord.getLayer().attribution}]},{layout:"form",labelAlign:"top",items:[{xtype:"textarea",fieldLabel:this.descriptionText,grow:!0,growMax:150,anchor:"99%",value:this.layerRecord.get("abstract"),readOnly:!0}]}]}},onFormatChange:function(a){var b=this.layerRecord.getLayer();a=a.getValue();b.mergeNewParams({format:a});b=this.transparentCb;"image/jpeg"==a?(this.transparent=b.getValue(),b.setValue(!1)):null!==this.transparent&&(b.setValue(this.transparent), this.transparent=null);b.setDisabled("image/jpeg"==a);this.fireEvent("change")},addScaleOptions:function(a,b){a.alwaysInRange=null;a.addOptions(b);a.display();a.redraw()},createDisplayPanel:function(){var a=this.layerRecord,b=a.getLayer(),c=b.opacity;null==c&&(c=1);var d=[],c=b.params.FORMAT.toLowerCase();Ext.each(a.get("formats"),function(a){this.imageFormats.test(a)&&d.push(a.toLowerCase())},this);-1===d.indexOf(c)&&d.push(c);var e=b.params.TRANSPARENT;return{title:this.displayText,layout:"form", bodyStyle:{padding:"10px"},defaults:{labelWidth:70},items:[{xtype:"fieldset",title:this.displayOptionsText,items:[{xtype:"gx_opacityslider",name:"opacity",anchor:"99%",isFormField:!0,fieldLabel:this.opacityText,listeners:{change:function(){this.fireEvent("change")},scope:this},layer:this.layerRecord},{xtype:"compositefield",fieldLabel:this.formatText,anchor:"99%",items:[{xtype:"combo",width:90,listWidth:150,store:d,value:c,mode:"local",triggerAction:"all",editable:!1,listeners:{select:this.onFormatChange, scope:this}},{xtype:"checkbox",ref:"../../../transparentCb",checked:"true"===e||!0===e,listeners:{check:function(a,c){b.mergeNewParams({transparent:c?"true":"false"});this.fireEvent("change")},scope:this}},{xtype:"label",cls:"gxp-layerproperties-label",text:this.transparentText}]},{xtype:"compositefield",fieldLabel:this.singleTileText,anchor:"99%",items:[{xtype:"checkbox",checked:this.layerRecord.get("layer").singleTile,listeners:{check:function(a,c){b.addOptions({singleTile:c});this.fireEvent("change")}, scope:this}},{xtype:"label",cls:"gxp-layerproperties-label",text:this.singleTileFieldText}]},{xtype:"compositefield",anchor:"99%",hidden:null==this.layerRecord.get("layer").params.TILED,fieldLabel:this.cacheText,items:[{xtype:"checkbox",checked:!0===this.layerRecord.get("layer").params.TILED,listeners:{check:function(a,b){this.layerRecord.get("layer").mergeNewParams({TILED:b});this.fireEvent("change")},scope:this}},{xtype:"label",cls:"gxp-layerproperties-label",text:this.cacheFieldText}]},{xtype:"combo", fieldLabel:this.infoFormatText,emptyText:this.infoFormatEmptyText,store:a.get("infoFormats"),value:a.get("infoFormat"),hidden:void 0===a.get("infoFormats"),mode:"local",listWidth:150,triggerAction:"all",editable:!1,anchor:"99%",listeners:{select:function(b){b=b.getValue();a.set("infoFormat",b);this.fireEvent("change")}},scope:this}]},{xtype:"fieldset",title:this.queryText,hideLabels:!0,ref:"../filterFieldset",listeners:{expand:function(){this.layerRecord.getLayer().mergeNewParams({CQL_FILTER:this.cqlFilter})}, collapse:function(){this.cqlFilter=this.layerRecord.getLayer().params.CQL_FILTER;this.layerRecord.getLayer().mergeNewParams({CQL_FILTER:null})},scope:this},hidden:null===this.source,checkboxToggle:!0,collapsed:!this.layerRecord.getLayer().params.CQL_FILTER,items:[{xtype:"textarea",value:this.layerRecord.getLayer().params.CQL_FILTER,grow:!0,anchor:"99%",width:"100%",growMax:100,ref:"../../cqlField",hidden:!0}],buttons:[{ref:"../../../cqlToolbar",hidden:!0,text:this.switchToFilterBuilderText,handler:this.switchToFilterBuilder, scope:this}]},{xtype:"fieldset",title:this.scaleText,listeners:{expand:function(){var a=this.layerRecord.getLayer();void 0===this.minScale&&void 0===this.maxScale||this.addScaleOptions(a,{minScale:this.maxScale,maxScale:this.minScale})},collapse:function(){var a=this.layerRecord.getLayer();this.minScale=a.options.maxScale;this.maxScale=a.options.minScale;this.addScaleOptions(a,{minScale:null,maxScale:null})},scope:this},checkboxToggle:!0,collapsed:null==this.layerRecord.getLayer().options.maxScale&& null==this.layerRecord.getLayer().options.minScale,items:[{xtype:"compositefield",fieldLabel:this.minScaleText,items:[{xtype:"label",text:"1:",cls:"gxp-layerproperties-label"},{xtype:"numberfield",anchor:"99%",width:"85%",listeners:{change:function(a){a={maxScale:parseInt(a.getValue())};var b=this.layerRecord.getLayer();this.addScaleOptions(b,a)},scope:this},value:this.layerRecord.getLayer().options.maxScale}]},{xtype:"compositefield",fieldLabel:this.maxScaleText,items:[{xtype:"label",text:"1:",cls:"gxp-layerproperties-label"}, {xtype:"numberfield",anchor:"99%",width:"85%",listeners:{change:function(a){a={minScale:parseInt(a.getValue())};var b=this.layerRecord.getLayer();this.addScaleOptions(b,a)},scope:this},value:this.layerRecord.getLayer().options.minScale}]}]}]}}});Ext.reg("gxp_wmslayerpanel",gxp.WMSLayerPanel);Ext.namespace("gxp"); gxp.ScaleLimitPanel=Ext.extend(Ext.Panel,{maxScaleDenominatorLimit:1.577757414193268E9*OpenLayers.DOTS_PER_INCH/256,limitMaxScaleDenominator:!0,maxScaleDenominator:void 0,minScaleDenominatorLimit:1.577757414193268E9*Math.pow(.5,19)*OpenLayers.DOTS_PER_INCH/256,limitMinScaleDenominator:!0,minScaleDenominator:void 0,scaleLevels:20,scaleSliderTemplate:"{scaleType} Scale 1:{scale}",modifyScaleTipContext:Ext.emptyFn,scaleFactor:null,changing:!1,border:!1,maxScaleLimitText:"Max scale limit",minScaleLimitText:"Min scale limit", initComponent:function(){this.layout="column";this.defaults={border:!1,bodyStyle:"margin: 0 5px;"};this.bodyStyle={padding:"5px"};this.scaleSliderTemplate=new Ext.Template(this.scaleSliderTemplate);Ext.applyIf(this,{minScaleDenominator:this.minScaleDenominatorLimit,maxScaleDenominator:this.maxScaleDenominatorLimit});this.scaleFactor=Math.pow(this.maxScaleDenominatorLimit/this.minScaleDenominatorLimit,1/(this.scaleLevels-1));this.scaleSlider=new Ext.Slider({vertical:!0,height:100,values:[0,100],listeners:{changecomplete:function(a, b){this.updateScaleValues(a)},render:function(a){a.thumbs[0].el.setVisible(this.limitMaxScaleDenominator);a.thumbs[1].el.setVisible(this.limitMinScaleDenominator);a.setDisabled(!this.limitMinScaleDenominator&&!this.limitMaxScaleDenominator)},scope:this},plugins:[new gxp.slider.Tip({getText:function(a){var b=a.slider.thumbs.indexOf(a),c=this.sliderValuesToScale([a.value]);a={scale:String(c[0]),zoom:(this.scaleLevels/100*a.value).toFixed(1),type:0===b?"Max":"Min",scaleType:0===b?"Min":"Max"};this.modifyScaleTipContext(this, a);return this.scaleSliderTemplate.apply(a)}.createDelegate(this)})]});this.maxScaleDenominatorInput=new Ext.form.NumberField({allowNegative:!1,width:100,fieldLabel:"1",value:Math.round(this.maxScaleDenominator),disabled:!this.limitMaxScaleDenominator,validator:function(a){return!this.limitMinScaleDenominator||a>this.minScaleDenominator}.createDelegate(this),listeners:{valid:function(a){a=Number(a.getValue());var b=Math.round(this.maxScaleDenominatorLimit);a<b&&a>this.minScaleDenominator&&(this.maxScaleDenominator= a,this.updateSliderValues())},change:function(a){var b=Number(a.getValue()),c=Math.round(this.maxScaleDenominatorLimit);b>c?a.setValue(c):b<this.minScaleDenominator?a.setValue(this.minScaleDenominator):(this.maxScaleDenominator=b,this.updateSliderValues())},scope:this}});this.minScaleDenominatorInput=new Ext.form.NumberField({allowNegative:!1,width:100,fieldLabel:"1",value:Math.round(this.minScaleDenominator),disabled:!this.limitMinScaleDenominator,validator:function(a){return!this.limitMaxScaleDenominator|| a<this.maxScaleDenominator}.createDelegate(this),listeners:{valid:function(a){a=Number(a.getValue());var b=Math.round(this.minScaleDenominatorLimit);a>b&&a<this.maxScaleDenominator&&(this.minScaleDenominator=a,this.updateSliderValues())},change:function(a){var b=Number(a.getValue()),c=Math.round(this.minScaleDenominatorLimit);b<c?a.setValue(c):b>this.maxScaleDenominator?a.setValue(this.maxScaleDenominator):(this.minScaleDenominator=b,this.updateSliderValues())},scope:this}});this.items=[this.scaleSlider, {xtype:"panel",layout:"form",defaults:{border:!1},items:[{labelWidth:90,layout:"form",width:150,items:[{xtype:"checkbox",checked:!!this.limitMinScaleDenominator,fieldLabel:this.maxScaleLimitText,listeners:{check:function(a,b){this.limitMinScaleDenominator=b;var c=this.scaleSlider;c.setValue(1,100);c.thumbs[1].el.setVisible(b);this.minScaleDenominatorInput.setDisabled(!b);this.updateScaleValues(c);c.setDisabled(!this.limitMinScaleDenominator&&!this.limitMaxScaleDenominator)},scope:this}}]},{labelWidth:10, layout:"form",items:[this.minScaleDenominatorInput]},{labelWidth:90,layout:"form",items:[{xtype:"checkbox",checked:!!this.limitMaxScaleDenominator,fieldLabel:this.minScaleLimitText,listeners:{check:function(a,b){this.limitMaxScaleDenominator=b;var c=this.scaleSlider;c.setValue(0,0);c.thumbs[0].el.setVisible(b);this.maxScaleDenominatorInput.setDisabled(!b);this.updateScaleValues(c);c.setDisabled(!this.limitMinScaleDenominator&&!this.limitMaxScaleDenominator)},scope:this}}]},{labelWidth:10,layout:"form", items:[this.maxScaleDenominatorInput]}]}];this.addEvents("change");gxp.ScaleLimitPanel.superclass.initComponent.call(this)},updateScaleValues:function(a){if(!this.changing){var b=a.getValues(),c=!1;!this.limitMaxScaleDenominator&&0<b[0]&&(b[0]=0,c=!0);!this.limitMinScaleDenominator&&100>b[1]&&(b[1]=100,c=!0);c?(a.setValue(0,b[0]),a.setValue(1,b[1])):(b=this.sliderValuesToScale(b),a=b[0],b=b[1],this.changing=!0,this.minScaleDenominatorInput.setValue(b),this.maxScaleDenominatorInput.setValue(a),this.changing= !1,this.fireEvent("change",this,this.limitMinScaleDenominator?b:void 0,this.limitMaxScaleDenominator?a:void 0))}},updateSliderValues:function(){if(!this.changing){var a=this.minScaleDenominator,b=this.maxScaleDenominator,c=this.scaleToSliderValues([b,a]);this.changing=!0;this.scaleSlider.setValue(0,c[0]);this.scaleSlider.setValue(1,c[1]);this.changing=!1;this.fireEvent("change",this,this.limitMinScaleDenominator?a:void 0,this.limitMaxScaleDenominator?b:void 0)}},sliderValuesToScale:function(a){var b= 100/(this.scaleLevels-1);return[Math.round(Math.pow(this.scaleFactor,(100-a[0])/b)*this.minScaleDenominatorLimit),Math.round(Math.pow(this.scaleFactor,(100-a[1])/b)*this.minScaleDenominatorLimit)]},scaleToSliderValues:function(a){var b=100/(this.scaleLevels-1);return[100-b*Math.log(a[0]/this.minScaleDenominatorLimit)/Math.log(this.scaleFactor),100-b*Math.log(a[1]/this.minScaleDenominatorLimit)/Math.log(this.scaleFactor)]}});Ext.reg("gxp_scalelimitpanel",gxp.ScaleLimitPanel);Ext.namespace("gxp.form"); gxp.form.GoogleGeocoderComboBox=Ext.extend(Ext.form.ComboBox,{xtype:"gxp_googlegeocodercombo",queryDelay:100,valueField:"viewport",displayField:"address",initComponent:function(){this.disabled=!0;if(window.google&&google.maps)window.setTimeout(function(){this.prepGeocoder()}.createDelegate(this),0);else{if(!gxp.plugins||!gxp.plugins.GoogleSource)throw Error("The gxp.form.GoogleGeocoderComboBox requires the gxp.plugins.GoogleSource or the Google Maps V3 API to be loaded.");gxp.plugins.GoogleSource.loader.onLoad({otherParams:gxp.plugins.GoogleSource.prototype.otherParams, callback:this.prepGeocoder,errback:function(){throw Error("The Google Maps script failed to load within the given timeout.");},scope:this})}this.store=new Ext.data.JsonStore({root:"results",fields:[{name:"address",type:"string"},{name:"location"},{name:"viewport"}],autoLoad:!1});this.on({focus:function(){this.clearValue()},scope:this});return gxp.form.GoogleGeocoderComboBox.superclass.initComponent.apply(this,arguments)},prepGeocoder:function(){var a=new google.maps.Geocoder,b={};b[Ext.data.Api.actions.read]= !0;var b=new Ext.data.DataProxy({api:b}),c=this,d=function(){var a=this.bounds;a&&(a instanceof OpenLayers.Bounds&&(a=a.toArray()),a=new google.maps.LatLngBounds(new google.maps.LatLng(a[1],a[0]),new google.maps.LatLng(a[3],a[2])));return a}.createDelegate(this);b.doRequest=function(b,f,g,h,k,l,m){a.geocode({address:g.query,bounds:d()},function(a,d){var f;if(d===google.maps.GeocoderStatus.OK||d===google.maps.GeocoderStatus.ZERO_RESULTS)try{a=c.transformResults(a),f=h.readRecords({results:a})}catch(g){c.fireEvent("exception", c,"response",b,m,d,g)}else c.fireEvent("exception",c,"remote",b,m,d,null);f?k.call(l,f,m,!0):k.call(l,null,m,!1)})};this.store.proxy=b;1!=this.initialConfig.disabled&&this.enable()},transformResults:function(a){var b=a.length,c=Array(b),d,e,f,g;for(i=0;i<b;++i)d=a[i],e=d.geometry.location,f=d.geometry.viewport,g=f.getNorthEast(),f=f.getSouthWest(),c[i]={address:d.formatted_address,location:new OpenLayers.LonLat(e.lng(),e.lat()),viewport:new OpenLayers.Bounds(f.lng(),f.lat(),g.lng(),g.lat())};return c}}); Ext.reg(gxp.form.GoogleGeocoderComboBox.prototype.xtype,gxp.form.GoogleGeocoderComboBox);Ext.namespace("gxp.plugins"); gxp.plugins.GoogleGeocoder=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_googlegeocoder",updateField:"viewport",init:function(a){var b=new gxp.form.GoogleGeocoderComboBox(Ext.apply({listeners:{select:this.onComboSelect,scope:this}},this.outputConfig)),c=a.mapPanel.map.restrictedExtent;if(c&&!b.bounds)a.on({ready:function(){b.bounds=c.clone().transform(a.mapPanel.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"))}});this.combo=b;return gxp.plugins.GoogleGeocoder.superclass.init.apply(this, arguments)},addOutput:function(a){return gxp.plugins.GoogleGeocoder.superclass.addOutput.call(this,this.combo)},onComboSelect:function(a,b){if(this.updateField){var c=this.target.mapPanel.map,d=b.get(this.updateField).clone().transform(new OpenLayers.Projection("EPSG:4326"),c.getProjectionObject());d instanceof OpenLayers.Bounds?c.zoomToExtent(d,!0):c.setCenter(d)}}});Ext.preg(gxp.plugins.GoogleGeocoder.prototype.ptype,gxp.plugins.GoogleGeocoder);Ext.namespace("gxp.plugins"); gxp.plugins.FeatureEditorGrid=Ext.extend(Ext.grid.PropertyGrid,{ptype:"gxp_editorgrid",xtype:"gxp_editorgrid",feature:null,schema:null,fields:null,excludeFields:null,propertyNames:null,readOnly:null,border:!1,initComponent:function(){this.dateFormat||(this.dateFormat=Ext.form.DateField.prototype.format);this.timeFormat||(this.timeFormat=Ext.form.TimeField.prototype.format);this.customRenderers=this.customRenderers||{};this.customEditors=this.customEditors||{};var a=this.feature,b;if(this.fields){b= {};for(var c=0,d=this.fields.length;c<d;++c)b[this.fields[c]]=a.attributes[this.fields[c]]}else b=a.attributes;this.excludeFields||(this.excludeFields=[]);if(this.schema){var e=this.fields?this.fields.join(",").toUpperCase().split(","):[];this.schema.each(function(c){var d=c.get("type");if(!d.match(/^[^:]*:?((Multi)?(Point|Line|Polygon|Curve|Surface|Geometry))/)){var f=c.get("name");this.fields&&-1==e.indexOf(f.toUpperCase())&&this.excludeFields.push(f);var l=a.attributes[f],m=GeoExt.form.recordToField(c); (c=this.getAnnotationsFromSchema(c))&&c.label&&(this.propertyNames=this.propertyNames||{},this.propertyNames[f]=c.label);var q;if("string"==typeof l){var n;switch(d.split(":").pop()){case "date":n=this.dateFormat;m.editable=!1;break;case "dateTime":n||(n=this.dateFormat+" "+this.timeFormat,m.editable=!0);m.format=n;q={startedit:function(a,b){if(!(b instanceof Date)){var c=Date.parseDate(b.replace(/Z$/,""),"c");c&&this.setValue(c)}}};this.customRenderers[f]=function(){return function(a){var b=a;"string"== typeof a&&(b=Date.parseDate(a.replace(/Z$/,""),"c"));return b?b.format(n):a}}();break;case "boolean":q={startedit:function(a,b){this.setValue(Boolean(b))}}}}this.customEditors[f]=new Ext.grid.GridEditor({field:Ext.create(m),listeners:q});b[f]=l}},this);a.attributes=b}this.source=b;var f=this.excludeFields.length?this.excludeFields.join(",").toUpperCase().split(","):[];this.viewConfig={forceFit:!0,getRowClass:function(a){if(-1!==f.indexOf(a.get("name").toUpperCase()))return"x-hide-nosize"}};this.listeners= {beforeedit:function(){return this.featureEditor&&this.featureEditor.editing},propertychange:function(){this.featureEditor&&this.featureEditor.setFeatureState(this.featureEditor.getDirtyState())},scope:this};c=Ext.data.Store.prototype.sort;Ext.data.Store.prototype.sort=function(){};gxp.plugins.FeatureEditorGrid.superclass.initComponent.apply(this,arguments);Ext.data.Store.prototype.sort=c;this.propStore.isEditableValue=function(){return!0}},init:function(a){this.featureEditor=a;this.featureEditor.on("canceledit", this.onCancelEdit,this);this.featureEditor.add(this);this.featureEditor.doLayout()},destroy:function(){this.featureEditor&&(this.featureEditor.un("canceledit",this.onCancelEdit,this),this.featureEditor=null);gxp.plugins.FeatureEditorGrid.superclass.destroy.call(this)},onCancelEdit:function(a,b){b&&this.setSource(b.attributes)}});Ext.override(gxp.plugins.FeatureEditorGrid,gxp.plugins.SchemaAnnotations);Ext.preg(gxp.plugins.FeatureEditorGrid.prototype.ptype,gxp.plugins.FeatureEditorGrid); Ext.reg(gxp.plugins.FeatureEditorGrid.prototype.xtype,gxp.plugins.FeatureEditorGrid);Ext.namespace("gxp"); gxp.QueryPanel=Ext.extend(Ext.Panel,{layout:"form",spatialQuery:!0,attributeQuery:!0,caseInsensitiveMatch:!1,likeSubstring:!1,wildCardString:".*",selectedLayer:null,featureStore:null,attributeStore:null,geometryType:null,geometryName:null,queryByLocationText:"Query by location",currentTextText:"Current extent",queryByAttributesText:"Query by attributes",layerText:"Layer",initComponent:function(){this.addEvents("ready","beforelayerchange","layerchange","beforequery","query","storeload");this.mapExtentField= new Ext.form.TextField({fieldLabel:this.currentTextText,readOnly:!0,anchor:"100%",value:this.getFormattedMapExtent()});this.map.events.on({moveend:this.updateMapExtent,scope:this});this.createFilterBuilder(this.layerStore.getAt(0));this.items=[{xtype:"combo",name:"layer",fieldLabel:this.layerText,store:this.layerStore,value:this.layerStore.getAt(0).get("name"),displayField:"title",valueField:"name",mode:"local",allowBlank:!0,editable:!1,triggerAction:"all",listeners:{beforeselect:function(a,b,c){return this.fireEvent("beforelayerchange", this,b)},select:function(a,b,c){this.createFilterBuilder(b)},scope:this}},{xtype:"fieldset",title:this.queryByLocationText,checkboxToggle:!0,collapsed:!this.spatialQuery,anchor:"95%",items:[this.mapExtentField],listeners:{collapse:function(){this.spatialQuery=!1},expand:function(){this.spatialQuery=!0},scope:this}},{xtype:"fieldset",title:this.queryByAttributesText,checkboxToggle:!0,collapsed:!this.attributeQuery,anchor:"95%",items:[this.filterBuilder],listeners:{collapse:function(){this.attributeQuery= !1},expand:function(){this.attributeQuery=!0},scope:this}}];gxp.QueryPanel.superclass.initComponent.apply(this,arguments)},createFilterBuilder:function(a){this.selectedLayer=a;var b=this.filterBuilder&&this.filterBuilder.ownerCt;b&&b.remove(this.filterBuilder,!0);this.attributeStore=new GeoExt.data.AttributeStore({url:a.get("schema"),listeners:{load:function(b){this.geometryName=null;b.filterBy(function(b){var c=/gml:((Multi)?(Point|Line|Polygon|Curve|Surface|Geometry)).*/.exec(b.get("type"));c&& !this.geometryName&&(this.geometryName=b.get("name"),this.geometryType=c[1],this.fireEvent("layerchange",this,a));return!c},this);this.createFeatureStore()},scope:this},autoLoad:!0});this.filterBuilder=new gxp.FilterBuilder({attributes:this.attributeStore,allowGroups:!1,caseInsensitiveMatch:this.caseInsensitiveMatch});b&&(b.add(this.filterBuilder),b.doLayout())},getFormattedMapExtent:function(){return this.map&&this.map.getExtent()&&this.map.getExtent().toBBOX().replace(/\.(\d)\d*/g,".$1").replace(/,/g, ", ")},updateMapExtent:function(){this.mapExtentField.setValue(this.getFormattedMapExtent())},getFilter:function(){var a=this.attributeQuery&&this.filterBuilder.getFilter();a&&this.likeSubstring&&(a=this.wrapWildCards(a));var b=this.spatialQuery&&new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.BBOX,value:this.map.getExtent()});return a&&b?new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.AND,filters:[b,a]}):a||b},wrapWildCards:function(a){if(a instanceof OpenLayers.Filter.Logical)for(var b= 0,c=a.filters.length;b<c;++b)a=this.wrapWildCards(a.filters[b]);else a.type===OpenLayers.Filter.Comparison.LIKE&&(a.value=this.wildCardString+a.value+this.wildCardString);return a},getFieldType:function(a){return{"xsd:boolean":"boolean","xsd:int":"int","xsd:integer":"int","xsd:short":"int","xsd:long":"int","xsd:date":"date","xsd:string":"string","xsd:float":"float","xsd:double":"float"}[a]},createFeatureStore:function(){var a=[];this.attributeStore.each(function(b){a.push({name:b.get("name"),type:this.getFieldType(b.get("type"))})}, this);var b=this.selectedLayer;this.featureStore=new gxp.data.WFSFeatureStore({fields:a,srsName:this.map.getProjection(),url:b.get("url"),featureType:b.get("name"),featureNS:b.get("namespace"),geometryName:this.geometryName,schema:b.get("schema"),maxFeatures:this.maxFeatures,autoLoad:!1,autoSave:!1,listeners:{load:function(a,b,e){this.fireEvent("storeload",this,a,b,e)},scope:this}});this.fireEvent("ready",this,this.featureStore)},query:function(){this.featureStore&&!1!==this.fireEvent("beforequery", this)&&(this.featureStore.setOgcFilter(this.getFilter()),this.featureStore.load(),this.fireEvent("query",this,this.featureStore))},beforeDestroy:function(){this.map&&this.map.events&&this.map.events.un({moveend:this.updateMapExtent,scope:this});gxp.QueryPanel.superclass.beforeDestroy.apply(this,arguments)}});Ext.reg("gxp_querypanel",gxp.QueryPanel);Ext.namespace("gxp"); gxp.TextSymbolizer=Ext.extend(Ext.Panel,{fonts:void 0,symbolizer:null,defaultSymbolizer:null,attributes:null,colorManager:null,haloCache:null,border:!1,layout:"form",labelValuesText:"Label values",haloText:"Halo",sizeText:"Size",priorityText:"Priority",labelOptionsText:"Label options",autoWrapText:"Auto wrap",followLineText:"Follow line",maxDisplacementText:"Maximum displacement",repeatText:"Repeat",forceLeftToRightText:"Force left to right",groupText:"Grouping",spaceAroundText:"Space around",labelAllGroupText:"Label all segments in line group", maxAngleDeltaText:"Maximum angle delta",conflictResolutionText:"Conflict resolution",goodnessOfFitText:"Goodness of fit",polygonAlignText:"Polygon alignment",graphicResizeText:"Graphic resize",graphicMarginText:"Graphic margin",graphicTitle:"Graphic",fontColorTitle:"Font color and opacity",positioningText:"Label positioning",anchorPointText:"Anchor point",displacementXText:"Displacement (X-direction)",displacementYText:"Displacement (Y-direction)",perpendicularOffsetText:"Perpendicular offset",priorityHelp:"The higher the value of the specified field, the sooner the label will be drawn (which makes it win in the conflict resolution game)", autoWrapHelp:"Wrap labels that exceed a certain length in pixels",followLineHelp:"Should the label follow the geometry of the line?",maxDisplacementHelp:"Maximum displacement in pixels if label position is busy",repeatHelp:"Repeat labels after a certain number of pixels",forceLeftToRightHelp:"Labels are usually flipped to make them readable. If the character happens to be a directional arrow then this is not desirable",groupHelp:"Grouping works by collecting all features with the same label text, then choosing a representative geometry for the group. Road data is a classic example to show why grouping is useful. It is usually desirable to display only a single label for all of 'Main Street', not a label for every block of 'Main Street.'", spaceAroundHelp:"Overlapping and Separating Labels. By default GeoServer will not render labels 'on top of each other'. By using the spaceAround option you can either allow labels to overlap, or add extra space around labels. The value supplied for the option is a positive or negative size in pixels. Using the default value of 0, the bounding box of a label cannot overlap the bounding box of another label.",labelAllGroupHelp:"The labelAllGroup option makes sure that all of the segments in a line group are labeled instead of just the longest one.", conflictResolutionHelp:"By default labels are subjected to conflict resolution, meaning the renderer will not allow any label to overlap with a label that has been drawn already. Setting this parameter to false pull the label out of the conflict resolution game, meaning the label will be drawn even if it overlaps with other labels, and other labels drawn after it won\u2019t mind overlapping with it.",goodnessOfFitHelp:"Geoserver will remove labels if they are a particularly bad fit for the geometry they are labeling. For Polygons: the label is sampled approximately at every letter. The distance from these points to the polygon is determined and each sample votes based on how close it is to the polygon. The default value is 0.5.", graphic_resizeHelp:"Specifies a mode for resizing label graphics (such as highway shields) to fit the text of the label. The default mode, \u2018none\u2019, never modifies the label graphic. In stretch mode, GeoServer will resize the graphic to exactly surround the label text, possibly modifying the image\u2019s aspect ratio. In proportional mode, GeoServer will expand the image to be large enough to surround the text while preserving its original aspect ratio.",maxAngleDeltaHelp:"Designed to use used in conjuection with followLine, the maxAngleDelta option sets the maximum angle, in degrees, between two subsequent characters in a curved label. Large angles create either visually disconnected words or overlapping characters. It is advised not to use angles larger than 30.", polygonAlignHelp:"GeoServer normally tries to place horizontal labels within a polygon, and give up in case the label position is busy or if the label does not fit enough in the polygon. This options allows GeoServer to try alternate rotations for the labels. Possible options: the default value, only the rotation manually specified in the <Rotation> tag will be used (manual), If the label does not fit horizontally and the polygon is taller than wider the vertical alignement will also be tried (ortho), If the label does not fit horizontally the minimum bounding rectangle will be computed and a label aligned to it will be tried out as well (mbr).", graphic_marginHelp:"Similar to the margin shorthand property in CSS for HTML, its interpretation varies depending on how many margin values are provided: 1 = use that margin length on all sides of the label 2 = use the first for top & bottom margins and the second for left & right margins. 3 = use the first for the top margin, second for left & right margins, third for the bottom margin. 4 = use the first for the top margin, second for the right margin, third for the bottom margin, and fourth for the left margin.", initComponent:function(){this.symbolizer||(this.symbolizer={});Ext.applyIf(this.symbolizer,this.defaultSymbolizer);this.symbolizer.vendorOptions||(this.symbolizer.vendorOptions={});this.haloCache={};this.attributes.on("load",this.showHideGeometryOptions,this);this.attributes.load();var a={xtype:"combo",fieldLabel:this.labelValuesText,store:this.attributes,mode:"local",lastQuery:"",editable:!1,triggerAction:"all",allowBlank:!1,displayField:"name",valueField:"name",value:this.symbolizer.label&&this.symbolizer.label.replace(/^\${(.*)}$/, "$1"),listeners:{select:function(a,c){this.symbolizer.label="${"+c.get("name")+"}";this.fireEvent("change",this.symbolizer)},scope:this},width:120};this.attributesComboConfig=this.attributesComboConfig||{};Ext.applyIf(this.attributesComboConfig,a);this.labelWidth=80;this.items=[this.attributesComboConfig,{cls:"x-html-editor-tb",style:"background: transparent; border: none; padding: 0 0em 0.5em;",xtype:"toolbar",items:[{xtype:"gxp_fontcombo",fonts:this.fonts||void 0,width:110,value:this.symbolizer.fontFamily, listeners:{select:function(a,c){this.symbolizer.fontFamily=c.get("field1");this.fireEvent("change",this.symbolizer)},scope:this}},{xtype:"tbtext",text:this.sizeText+": "},{xtype:"numberfield",allowNegative:!1,emptyText:OpenLayers.Renderer.defaultSymbolizer.fontSize,value:this.symbolizer.fontSize,width:30,listeners:{change:function(a,c){c=parseFloat(c);isNaN(c)?delete this.symbolizer.fontSize:this.symbolizer.fontSize=c;this.fireEvent("change",this.symbolizer)},scope:this}},{enableToggle:!0,cls:"x-btn-icon", iconCls:"x-edit-bold",pressed:"bold"===this.symbolizer.fontWeight,listeners:{toggle:function(a,c){this.symbolizer.fontWeight=c?"bold":"normal";this.fireEvent("change",this.symbolizer)},scope:this}},{enableToggle:!0,cls:"x-btn-icon",iconCls:"x-edit-italic",pressed:"italic"===this.symbolizer.fontStyle,listeners:{toggle:function(a,c){this.symbolizer.fontStyle=c?"italic":"normal";this.fireEvent("change",this.symbolizer)},scope:this}}]},{xtype:"gxp_fillsymbolizer",fillText:this.fontColorTitle,symbolizer:this.symbolizer, colorProperty:"fontColor",opacityProperty:"fontOpacity",checkboxToggle:!1,autoHeight:!0,width:213,labelWidth:70,plugins:this.colorManager&&[new this.colorManager],listeners:{change:function(a){this.fireEvent("change",this.symbolizer)},scope:this}},{xtype:"fieldset",title:this.graphicTitle,checkboxToggle:!0,hideMode:"offsets",collapsed:!(this.symbolizer.fillColor||this.symbolizer.fillOpacity||this.symbolizer.vendorOptions["graphic-resize"]||this.symbolizer.vendorOptions["graphic-margin"]),labelWidth:70, items:[{xtype:"gxp_pointsymbolizer",symbolizer:this.symbolizer,listeners:{change:function(a){a.graphic=!!a.graphicName||!!a.externalGraphic;this.fireEvent("change",this.symbolizer)},scope:this},border:!1,labelWidth:70},this.createVendorSpecificField({name:"graphic-resize",xtype:"combo",store:["none","stretch","proportional"],mode:"local",listeners:{select:function(a,c){"none"===a.getValue()?this.graphicMargin.hide():(Ext.isEmpty(this.graphicMargin.getValue())&&(this.graphicMargin.setValue(0),this.symbolizer.vendorOptions["graphic-margin"]= 0),this.graphicMargin.show())},scope:this},width:100,triggerAction:"all",fieldLabel:this.graphicResizeText}),this.createVendorSpecificField({name:"graphic-margin",ref:"../graphicMargin",hidden:"stretch"!==this.symbolizer.vendorOptions["graphic-resize"]&&"proportional"!==this.symbolizer.vendorOptions["graphic-resize"],width:100,fieldLabel:this.graphicMarginText,xtype:"textfield"})],listeners:{collapse:function(){this.graphicCache={externalGraphic:this.symbolizer.externalGraphic,fillColor:this.symbolizer.fillColor, fillOpacity:this.symbolizer.fillOpacity,graphicName:this.symbolizer.graphicName,pointRadius:this.symbolizer.pointRadius,rotation:this.symbolizer.rotation,strokeColor:this.symbolizer.strokeColor,strokeWidth:this.symbolizer.strokeWidth,strokeDashStyle:this.symbolizer.strokeDashStyle};delete this.symbolizer.externalGraphic;delete this.symbolizer.fillColor;delete this.symbolizer.fillOpacity;delete this.symbolizer.graphicName;delete this.symbolizer.pointRadius;delete this.symbolizer.rotation;delete this.symbolizer.strokeColor; delete this.symbolizer.strokeWidth;delete this.symbolizer.strokeDashStyle;this.fireEvent("change",this.symbolizer)},expand:function(){Ext.apply(this.symbolizer,this.graphicCache);this.doLayout();this.fireEvent("change",this.symbolizer)},scope:this}},{xtype:"fieldset",title:this.haloText,checkboxToggle:!0,collapsed:!(this.symbolizer.haloRadius||this.symbolizer.haloColor||this.symbolizer.haloOpacity),autoHeight:!0,labelWidth:50,items:[{xtype:"numberfield",fieldLabel:this.sizeText,anchor:"89%",allowNegative:!1, emptyText:OpenLayers.Renderer.defaultSymbolizer.haloRadius,value:this.symbolizer.haloRadius,listeners:{change:function(a,c){c=parseFloat(c);isNaN(c)?delete this.symbolizer.haloRadius:this.symbolizer.haloRadius=c;this.fireEvent("change",this.symbolizer)},scope:this}},{xtype:"gxp_fillsymbolizer",symbolizer:{fillColor:"haloColor"in this.symbolizer?this.symbolizer.haloColor:OpenLayers.Renderer.defaultSymbolizer.haloColor,fillOpacity:"haloOpacity"in this.symbolizer?this.symbolizer.haloOpacity:100*OpenLayers.Renderer.defaultSymbolizer.haloOpacity}, defaultColor:OpenLayers.Renderer.defaultSymbolizer.haloColor,checkboxToggle:!1,width:190,labelWidth:60,plugins:this.colorManager&&[new this.colorManager],listeners:{change:function(a){this.symbolizer.haloColor=a.fillColor;this.symbolizer.haloOpacity=a.fillOpacity;this.fireEvent("change",this.symbolizer)},scope:this}}],listeners:{collapse:function(){this.haloCache={haloRadius:this.symbolizer.haloRadius,haloColor:this.symbolizer.haloColor,haloOpacity:this.symbolizer.haloOpacity};delete this.symbolizer.haloRadius; delete this.symbolizer.haloColor;delete this.symbolizer.haloOpacity;this.fireEvent("change",this.symbolizer)},expand:function(){Ext.apply(this.symbolizer,this.haloCache);this.doLayout();this.fireEvent("change",this.symbolizer)},scope:this}},{xtype:"fieldset",collapsed:!(this.symbolizer.labelAlign||this.symbolizer.vendorOptions.polygonAlign||this.symbolizer.labelXOffset||this.symbolizer.labelYOffset||this.symbolizer.labelPerpendicularOffset),title:this.positioningText,checkboxToggle:!0,autoHeight:!0, labelWidth:75,defaults:{width:100},items:[this.createField(Ext.applyIf({fieldLabel:this.anchorPointText,geometryTypes:["POINT"],value:this.symbolizer.labelAlign||"lb",store:[["lt","Left-top"],["ct","Center-top"],["rt","Right-top"],["lm","Left-center"],["cm","Center"],["rm","Right-center"],["lb","Left-bottom"],["cb","Center-bottom"],["rb","Right-bottom"]],listeners:{select:function(a,c){this.symbolizer.labelAlign=a.getValue();delete this.symbolizer.labelAnchorPointX;delete this.symbolizer.labelAnchorPointY; this.fireEvent("change",this.symbolizer)},scope:this}},this.attributesComboConfig)),this.createField({xtype:"numberfield",geometryTypes:["POINT"],fieldLabel:this.displacementXText,value:this.symbolizer.labelXOffset,listeners:{change:function(a,c){this.symbolizer.labelXOffset=c;this.fireEvent("change",this.symbolizer)},scope:this}}),this.createField({xtype:"numberfield",geometryTypes:["POINT"],fieldLabel:this.displacementYText,value:this.symbolizer.labelYOffset,listeners:{change:function(a,c){this.symbolizer.labelYOffset= c;this.fireEvent("change",this.symbolizer)},scope:this}}),this.createField({xtype:"numberfield",geometryTypes:["LINE"],fieldLabel:this.perpendicularOffsetText,value:this.symbolizer.labelPerpendicularOffset,listeners:{change:function(a,c){Ext.isEmpty(c)?delete this.symbolizer.labelPerpendicularOffset:this.symbolizer.labelPerpendicularOffset=c;this.fireEvent("change",this.symbolizer)},scope:this}}),this.createVendorSpecificField({name:"polygonAlign",geometryTypes:["POLYGON"],xtype:"combo",mode:"local", value:this.symbolizer.vendorOptions.polygonAlign||"manual",triggerAction:"all",store:["manual","ortho","mbr"],fieldLabel:this.polygonAlignText})]},{xtype:"fieldset",title:this.priorityText,checkboxToggle:!0,collapsed:!this.symbolizer.priority,autoHeight:!0,labelWidth:50,items:[Ext.applyIf({fieldLabel:this.priorityText,value:this.symbolizer.priority&&this.symbolizer.priority.replace(/^\${(.*)}$/,"$1"),allowBlank:!0,name:"priority",plugins:[{ptype:"gxp_formfieldhelp",dismissDelay:2E4,helpText:this.priorityHelp}], listeners:{select:function(a,c){this.symbolizer[a.name]="${"+c.get("name")+"}";this.fireEvent("change",this.symbolizer)},scope:this}},this.attributesComboConfig)]},{xtype:"fieldset",title:this.labelOptionsText,checkboxToggle:!0,collapsed:!(this.symbolizer.vendorOptions.autoWrap||this.symbolizer.vendorOptions.followLine||this.symbolizer.vendorOptions.maxAngleDelta||this.symbolizer.vendorOptions.maxDisplacement||this.symbolizer.vendorOptions.repeat||this.symbolizer.vendorOptions.forceLeftToRight||this.symbolizer.vendorOptions.group|| this.symbolizer.vendorOptions.spaceAround||this.symbolizer.vendorOptions.labelAllGroup||this.symbolizer.vendorOptions.conflictResolution||this.symbolizer.vendorOptions.goodnessOfFit||this.symbolizer.vendorOptions.polygonAlign),autoHeight:!0,labelWidth:80,defaults:{width:100},items:[this.createVendorSpecificField({name:"autoWrap",allowBlank:!1,fieldLabel:this.autoWrapText}),this.createVendorSpecificField({name:"followLine",geometryTypes:["LINE"],xtype:"checkbox",listeners:{check:function(a,c){c?this.maxAngleDelta.show(): this.maxAngleDelta.hide()},scope:this},fieldLabel:this.followLineText}),this.createVendorSpecificField({name:"maxAngleDelta",ref:"../maxAngleDelta",hidden:null==this.symbolizer.vendorOptions.followLine,geometryTypes:["LINE"],fieldLabel:this.maxAngleDeltaText}),this.createVendorSpecificField({name:"maxDisplacement",fieldLabel:this.maxDisplacementText}),this.createVendorSpecificField({name:"repeat",geometryTypes:["LINE"],fieldLabel:this.repeatText}),this.createVendorSpecificField({name:"forceLeftToRight", xtype:"checkbox",geometryTypes:["LINE"],fieldLabel:this.forceLeftToRightText}),this.createVendorSpecificField({name:"group",listeners:{check:function(a,c){"LINE"===this.geometryType&&(!1===c?this.labelAllGroup.hide():this.labelAllGroup.show())},scope:this},xtype:"checkbox",yesno:!0,fieldLabel:this.groupText}),this.createVendorSpecificField({name:"labelAllGroup",ref:"../labelAllGroup",geometryTypes:["LINE"],hidden:"yes"!==this.symbolizer.vendorOptions.group,xtype:"checkbox",fieldLabel:this.labelAllGroupText}), this.createVendorSpecificField({name:"conflictResolution",xtype:"checkbox",listeners:{check:function(a,c){c?this.spaceAround.show():this.spaceAround.hide()},scope:this},fieldLabel:this.conflictResolutionText}),this.createVendorSpecificField({name:"spaceAround",hidden:!0!==this.symbolizer.vendorOptions.conflictResolution,allowNegative:!0,ref:"../spaceAround",fieldLabel:this.spaceAroundText}),this.createVendorSpecificField({name:"goodnessOfFit",geometryTypes:["POLYGON"],fieldLabel:this.goodnessOfFitText})]}]; this.addEvents("change");gxp.TextSymbolizer.superclass.initComponent.call(this)},createField:function(a){var b=Ext.ComponentMgr.create(a);if(a.geometryTypes)this.on("geometrytype",function(c){-1===a.geometryTypes.indexOf(c)&&b.hide()});return b},createVendorSpecificField:function(a){var b=function(b,c){Ext.isEmpty(c)?delete this.symbolizer.vendorOptions[a.name]:this.symbolizer.vendorOptions[a.name]=!0===a.yesno?1==c?"yes":"no":c;this.fireEvent("change",this.symbolizer)},c=Ext.ComponentMgr.create(Ext.applyIf(a, {xtype:"numberfield",allowNegative:!1,value:a.value||this.symbolizer.vendorOptions[a.name],checked:!0===a.yesno?"yes"===this.symbolizer.vendorOptions[a.name]:this.symbolizer.vendorOptions[a.name],plugins:[{ptype:"gxp_formfieldhelp",dismissDelay:2E4,helpText:this[a.name.replace(/-/g,"_")+"Help"]}]}));c.on("change",b,this);c.on("check",b,this);if(a.geometryTypes)this.on("geometrytype",function(b){-1===a.geometryTypes.indexOf(b)&&c.hide()});return c},showHideGeometryOptions:function(){var a=/gml:((Multi)?(Point|Line|Polygon|Curve|Surface|Geometry)).*/, b=/gml:((Multi)?(Polygon|Surface)).*/,c=/gml:((Multi)?(Point)).*/,d=/gml:((Multi)?(Line|Curve|Surface)).*/,e=null;this.attributes.each(function(f){f=f.get("type");a.exec(f)&&(b.exec(f)?e="POLYGON":c.exec(f)?e="POINT":d.exec(f)&&(e="LINE"))},this);null!==e&&(this.geometryType=e,this.fireEvent("geometrytype",e))}});Ext.reg("gxp_textsymbolizer",gxp.TextSymbolizer);Ext.namespace("gxp.form"); gxp.form.FilterField=Ext.extend(Ext.form.CompositeField,{lowerBoundaryTip:"lower boundary",upperBoundaryTip:"upper boundary",caseInsensitiveMatch:!1,filter:null,attributes:null,attributesComboConfig:null,initComponent:function(){this.filter||(this.filter=this.createDefaultFilter());var a="remote",b=new GeoExt.data.AttributeStore;this.attributes&&(0!=this.attributes.getCount()?(a="local",this.attributes.each(function(a){/gml:((Multi)?(Point|Line|Polygon|Curve|Surface|Geometry)).*/.exec(a.get("type"))|| b.add([a])})):b=this.attributes);a={xtype:"combo",store:b,editable:"local"==a,typeAhead:!0,forceSelection:!0,mode:a,triggerAction:"all",ref:"property",allowBlank:this.allowBlank,displayField:"name",valueField:"name",value:this.filter.property,listeners:{select:function(a,b){this.items.get(1).enable();this.filter.property=b.get("name");this.fireEvent("change",this.filter,this)},blur:function(a){var b=a.store.findExact("name",a.getValue());-1!=b?a.fireEvent("select",a,a.store.getAt(b)):null!=a.startValue&& a.setValue(a.startValue)},scope:this},width:120};this.attributesComboConfig=this.attributesComboConfig||{};Ext.applyIf(this.attributesComboConfig,a);this.items=this.createFilterItems();this.addEvents("change");gxp.form.FilterField.superclass.initComponent.call(this)},validateValue:function(a,b){return this.filter.type===OpenLayers.Filter.Comparison.BETWEEN?null!==this.filter.property&&null!==this.filter.upperBoundary&&null!==this.filter.lowerBoundary:null!==this.filter.property&&null!==this.filter.value&& null!==this.filter.type},createDefaultFilter:function(){return new OpenLayers.Filter.Comparison({matchCase:!this.caseInsensitiveMatch})},createFilterItems:function(){var a=this.filter.type===OpenLayers.Filter.Comparison.BETWEEN;return[this.attributesComboConfig,Ext.applyIf({xtype:"gxp_comparisoncombo",ref:"type",disabled:null==this.filter.property,allowBlank:this.allowBlank,value:this.filter.type,listeners:{select:function(a,c){this.items.get(2).enable();this.items.get(3).enable();this.items.get(4).enable(); this.setFilterType(c.get("value"));this.fireEvent("change",this.filter,this)},scope:this}},this.comparisonComboConfig),{xtype:"textfield",disabled:null==this.filter.type,hidden:a,ref:"value",value:this.filter.value,width:50,grow:!0,growMin:50,anchor:"100%",allowBlank:this.allowBlank,listeners:{change:function(a,c){this.filter.value=c;this.fireEvent("change",this.filter,this)},scope:this}},{xtype:"textfield",disabled:null==this.filter.type,hidden:!a,value:this.filter.lowerBoundary,tooltip:this.lowerBoundaryTip, grow:!0,growMin:30,ref:"lowerBoundary",anchor:"100%",allowBlank:this.allowBlank,listeners:{change:function(a,c){this.filter.lowerBoundary=c;this.fireEvent("change",this.filter,this)},render:function(a){Ext.QuickTips.register({target:a.getEl(),text:this.lowerBoundaryTip})},autosize:function(a,c){a.setWidth(c);a.ownerCt.doLayout()},scope:this}},{xtype:"textfield",disabled:null==this.filter.type,hidden:!a,grow:!0,growMin:30,ref:"upperBoundary",value:this.filter.upperBoundary,allowBlank:this.allowBlank, listeners:{change:function(a,c){this.filter.upperBoundary=c;this.fireEvent("change",this.filter,this)},render:function(a){Ext.QuickTips.register({target:a.getEl(),text:this.upperBoundaryTip})},scope:this}}]},setFilterType:function(a){this.filter.type=a;a===OpenLayers.Filter.Comparison.BETWEEN?(this.items.get(2).hide(),this.items.get(3).show(),this.items.get(4).show()):(this.items.get(2).show(),this.items.get(3).hide(),this.items.get(4).hide());this.doLayout()},setFilter:function(a){var b=this.filter.type; this.filter=a;b!==a.type&&this.setFilterType(a.type);this.property.setValue(a.property);this.type.setValue(a.type);a.type===OpenLayers.Filter.Comparison.BETWEEN?(this.lowerBoundary.setValue(a.lowerBoundary),this.upperBoundary.setValue(a.upperBoundary)):this.value.setValue(a.value);this.fireEvent("change",this.filter,this)}});Ext.reg("gxp_filterfield",gxp.form.FilterField);Ext.namespace("gxp"); Ext.override(Ext.Tip,{showBy:function(a,b,c){Ext.isEmpty(b)&&(b=this.defaultAlign);var d=c[0];c=c[1];"b"===b.charAt(0)&&(c=-c);if("r"===b.charAt(0)||"r"===b.charAt(1))d=-d;"c"===b.charAt(0)&&(c=d=0);if("l"===b.charAt(0)||"r"===b.charAt(0))c=0;this.rendered||this.render(Ext.getBody());b=this.el.getAlignToXY(a,b||this.defaultAlign,[d,c]);0<document.body.scrollTop&&document.body.scrollTop>a.getTop()&&(b[1]+=a.getTop()-document.body.scrollTop);this.isVisible()?this.setPagePosition(b[0],b[1]):this.showAt(b)}}); GeoExt.FeatureTip=Ext.extend(Ext.Tip,{map:null,location:null,shouldBeVisible:null,initComponent:function(){var a=this.location.geometry.getCentroid();this.location=new OpenLayers.LonLat(a.x,a.y);this.map.events.on({move:this.show,scope:this});GeoExt.FeatureTip.superclass.initComponent.call(this)},beforeDestroy:function(){for(var a in this.youtubePlayers)this.youtubePlayers[a].destroy(),delete this.youtubePlayers[a];this.map.events.un({move:this.show,scope:this});GeoExt.FeatureTip.superclass.beforeDestroy.call(this)}, getPosition:function(){if(this.map.getExtent().containsLonLat(this.location)){var a=this.map.getPixelFromLonLat(this.location),b=Ext.fly(this.map.div).getBox(!0);return[a.x+b.x,a.y+b.y]}return null},show:function(){var a=this.getPosition();null===a||null!==this.shouldBeVisible&&!this.shouldBeVisible.call(this)?this.hide():this.isVisible()?this.setPagePosition(a[0],a[1]):this.showAt(a)}}); window.Timeline&&window.SimileAjax&&function(){SimileAjax.History.enabled=!1;Timeline._Band.prototype._onDblClick=Ext.emptyFn;Timeline.DefaultEventSource.prototype.remove=function(a){this._events.remove(a)};SimileAjax.EventIndex.prototype.remove=function(a){this._events.remove(this._idToEvent[a]);delete this._idToEvent[a]};Timeline._Band.prototype.zoom=function(a,b,c,d){this._zoomSteps&&(b=this.getCenterVisibleDate(),a=this._ether.zoom(a),this._etherPainter.zoom(a),this.setCenterVisibleDate(b))}}(); gxp.TimelinePanel=Ext.extend(Ext.Panel,{youtubePlayers:{},scrollInterval:500,annotationConfig:{timeAttr:"start_time",endTimeAttr:"end_time",filterAttr:"in_timeline",mapFilterAttr:"in_map"},layout:"border",initComponent:function(){Timeline.OriginalEventPainter.prototype._showBubble=this.handleEventClick.createDelegate(this);this.timelineContainer=new Ext.Container({region:"center"});this.eventSource=new Timeline.DefaultEventSource(0);this.items=[this.timelineContainer];this.initialConfig.viewer&&(delete this.viewer, this.bindViewer(this.initialConfig.viewer));this.initialConfig.annotationsStore&&this.bindAnnotationsStore(this.initialConfig.annotationsStore);this.initialConfig.playbackTool&&(delete this.playbackTool,this.bindPlaybackTool(this.initialConfig.playbackTool));this.ownerCt&&(this.ownerCt.on("beforecollapse",function(){this._silentMapMove=!0},this),this.ownerCt.on("beforeexpand",function(){delete this._silentMapMove},this),this.ownerCt.on("afterlayout",function(){delete this._silent},this));gxp.TimelinePanel.superclass.initComponent.call(this)}, handleEventClick:function(a,b,c){this.fireEvent("click",c.getProperty("fid"))},bindAnnotationsStore:function(a){this.annotationsStore=a;a.on("load",function(a,c,d){this.layerLookup.annotations=Ext.apply({titleAttr:"title",icon:Timeline.urlPrefix+"/images/note.png",layer:a.layer,visible:!0},this.annotationConfig);var e=[];a.each(function(a){e.push(a.getFeature())});this.addFeatures("annotations",e);0<c.length&&this.ownerCt.expand();this.showAnnotations()},this,{single:!0});a.on("write",this.onSave, this)},unbindAnnotationsStore:function(){this.annotationsStore&&this.annotationsStore.un("write",this.onSave,this)},clearEventsForFid:function(a,b){for(var c=this.eventSource.getAllEventIterator(),d=[];c.hasNext();){var e=c.next();e.getProperty("key")===a&&e.getProperty("fid")===b&&d.push(e.getID())}c=0;for(e=d.length;c<e;++c)this.eventSource.remove(d[c]);this.timeline&&this.timeline.layout()},onSave:function(a,b,c){a=[];for(var d=0,e=c.length;d<e;d++){var f=c[d].feature;a.push(f);f=f.fid;this.clearEventsForFid("annotations", f);this.tooltips&&this.tooltips[f]&&(this.tooltips[f].destroy(),this.tooltips[f]=null)}b!==Ext.data.Api.actions.destroy&&this.addFeatures("annotations",a);this.showAnnotations()},bindPlaybackTool:function(a){this.playbackTool=a;this.playbackTool.on("timechange",this.onTimeChange,this);this.playbackTool.on("rangemodified",this.onRangeModify,this)},unbindPlaybackTool:function(){this.playbackTool&&(this.playbackTool.un("timechange",this.onTimeChange,this),this.playbackTool.un("rangemodified",this.onRangeModify, this),this.playbackTool=null)},onTimeChange:function(a,b){this._silent=!0;!0!==this._ignoreTimeChange&&this.setCenterDate(b);delete this._silent},onRangeModify:function(a,b){this._silent=!0;this.setRange(b);delete this._silent},createTimeline:function(a){if(this.rendered&&(0!==this.timelineContainer.el.getSize().width||0!==this.timelineContainer.el.getSize().height)){var b=Timeline.ClassicTheme.create(),c=a[1]-a[0],d=[];50<=c/1E3/60/60/24/365?(d.push(Timeline.DateTime.DECADE),d.push(Timeline.DateTime.CENTURY)): (d.push(Timeline.DateTime.YEAR),d.push(Timeline.DateTime.DECADE));a=new Date(a[0]+c/2);d=[Timeline.createBandInfo({width:"80%",intervalUnit:d[0],intervalPixels:200,eventSource:this.eventSource,date:a,theme:b,layout:"original",zoomIndex:7,zoomSteps:[{pixelsPerInterval:25,unit:d[0]},{pixelsPerInterval:50,unit:d[0]},{pixelsPerInterval:75,unit:d[0]},{pixelsPerInterval:100,unit:d[0]},{pixelsPerInterval:125,unit:d[0]},{pixelsPerInterval:150,unit:d[0]},{pixelsPerInterval:175,unit:d[0]},{pixelsPerInterval:200, unit:d[0]},{pixelsPerInterval:225,unit:d[0]},{pixelsPerInterval:250,unit:d[0]},{pixelsPerInterval:275,unit:d[0]},{pixelsPerInterval:300,unit:d[0]},{pixelsPerInterval:325,unit:d[0]},{pixelsPerInterval:350,unit:d[0]},{pixelsPerInterval:375,unit:d[0]}]}),Timeline.createBandInfo({width:"20%",intervalUnit:d[1],intervalPixels:200,eventSource:this.eventSource,date:a,theme:b,layout:"overview"})];d[1].syncWith=0;d[1].highlight=!0;d[0].decorators=[new Timeline.PointHighlightDecorator({date:a,theme:b})];this.timeline= Timeline.create(this.timelineContainer.el.dom,d,Timeline.HORIZONTAL);this._silent=!0;this.timeline.getBand(0).addOnScrollListener(gxp.util.throttle(this.setPlaybackCenter.createDelegate(this),this.scrollInterval))}},setPlaybackCenter:function(a){a=a.getCenterVisibleDate();!0!==this._silent&&this.playbackTool&&!0!==this.playbackTool.playbackToolbar.playing&&(this._ignoreTimeChange=!0,this.playbackTool.setTime(a),this.timeline.getBand(0)._decorators[0]._date=this.playbackTool.playbackToolbar.control.currentValue, this.timeline.getBand(0)._decorators[0].paint(),delete this._ignoreTimeChange,this.showAnnotations())},bindViewer:function(a){this.viewer&&this.unbindViewer();this.viewer=a;this.layerLookup||(this.layerLookup={})},unbindViewer:function(){delete this.viewer;delete this.layerLookup},onLayout:function(){gxp.TimelinePanel.superclass.onLayout.call(this,arguments);!this.timeline&&this.playbackTool&&this.playbackTool.playbackToolbar&&(this.setRange(this.playbackTool.playbackToolbar.control.animationRange), this.setCenterDate(this.playbackTool.playbackToolbar.control.currentValue))},setRange:function(a){this.originalRange=a;this.timeline||this.createTimeline(a);if(this.timeline){var b=this.timeline.getBand(0);b.setMinVisibleDate(a[0]);b.setMaxVisibleDate(a[1]);this.timeline.getBand(1).getEtherPainter().setHighlight(a[0],a[1])}},buildHTML:function(a){var b=a.get("content"),c=b?b.indexOf("[youtube="):-1;if(-1!==c){var d=b.substr(0,c),e=b.indexOf("]",c),f=b.substr(e+1),b=b.substr(c+9,e-9),g=OpenLayers.Util.getParameters(b), c=g.w||250,e=g.h||250,g=g.v;void 0===g&&(g=b.substr(b.lastIndexOf("/")+1,-1!==b.indexOf("?")?b.indexOf("?")-(b.lastIndexOf("/")+1):void 0));b="http://www.youtube.com/embed/"+g;a="player_"+a.getFeature().fid;return d+'<br/><iframe id="'+a+'" type="text/html" width="'+c+'" height="'+e+'" src="'+b+"?enablejsapi=1&origin="+window.location.origin+'" frameborder="0"></iframe><br/>'+f}return b},displayTooltip:function(a){var b=null!==a.getFeature().geometry;this.tooltips||(this.tooltips={});var c=a.getFeature().fid, d=-1!==(a.get("content")||"").indexOf("[youtube="),e={hide:function(a){!0===d&&this.youtubePlayers[c].stopVideo()},show:function(a){!0===d&&this.youtubePlayers[c]._ready&&this.playbackTool.playbackToolbar.playing&&this.youtubePlayers[c].playVideo()},afterrender:function(){if(!0===d&&!this.youtubePlayers[c]){var a=this;a.playbackTool.playbackToolbar.playing&&(a.playbackTool.playbackToolbar._weStopped=!0,window.setTimeout(function(){a.playbackTool.playbackToolbar.control.stop()},0));this.youtubePlayers[c]= new YT.Player("player_"+c,{events:{onReady:function(b){b.target._ready=!0;(a.playbackTool.playbackToolbar.playing||a.playbackTool.playbackToolbar._weStopped)&&b.target.playVideo()},onStateChange:function(b){b.data===YT.PlayerState.PLAYING?!a.playbackTool.playbackToolbar._weStopped&&a.playbackTool.playbackToolbar.playing&&(a.playbackTool.playbackToolbar._weStopped=!0,a.playbackTool.playbackToolbar.control.stop()):b.data==YT.PlayerState.ENDED&&a.playbackTool.playbackToolbar._weStopped&&(a.playbackTool.playbackToolbar.control.play(), delete a.playbackTool.playbackToolbar._weStopped)}}})}},scope:this};this.tooltips[c]||(!b||b&&"geom"!==a.get("appearance")&&!Ext.isEmpty(a.get("appearance"))?this.tooltips[c]=new Ext.Tip({cls:"gxp-annotations-tip",maxWidth:500,bodyCssClass:"gxp-annotations-tip-body",listeners:e,title:a.get("title"),html:this.buildHTML(a)}):this.tooltips[c]=new GeoExt.FeatureTip({map:this.viewer.mapPanel.map,location:a.getFeature(),shouldBeVisible:function(){return!0===this._inTimeRange},cls:"gxp-annotations-tip", bodyCssClass:"gxp-annotations-tip-body",maxWidth:500,title:a.get("title"),listeners:e,html:this.buildHTML(a)}));e=this.tooltips[c];e._inTimeRange=!0;!b||b&&"geom"!==a.get("appearance")&&!Ext.isEmpty(a.get("appearance"))?(e.showBy(this.viewer.mapPanel.body,a.get("appearance"),[10,10]),e.showBy(this.viewer.mapPanel.body,a.get("appearance"),[10,10])):e.isVisible()||e.show();b&&this.annotationsLayer.addFeatures([a.getFeature()])},hideTooltip:function(a){var b=a.getFeature().fid,c=null!==a.getFeature().geometry; this.tooltips&&this.tooltips[b]&&(this.tooltips[b]._inTimeRange=!1,this.tooltips[b].hide(),c&&this.annotationsLayer.removeFeatures([a.getFeature()]))},showAnnotations:function(){this.annotationsLayer||(this.annotationsLayer=new OpenLayers.Layer.Vector(null,{displayInLayerSwitcher:!1}),this.viewer&&this.viewer.mapPanel.map.addLayer(this.annotationsLayer));var a=(new Date(this.playbackTool.playbackToolbar.control.currentValue)).getTime()/1E3;this.annotationsStore&&this.annotationsStore.each(function(b){var c= this.annotationConfig.mapFilterAttr;if(Ext.isBoolean(b.get(c))?b.get(c):"true"===b.get(c)){var c=parseFloat(b.get(this.annotationConfig.timeAttr)),d=b.get(this.annotationConfig.endTimeAttr),e=d!=c;if(""==d||null==d)d=this.playbackTool.playbackToolbar.control.animationRange[1];!0===e?a<=parseFloat(d)&&a>=c?this.displayTooltip(b):this.hideTooltip(b):0===c-a?this.displayTooltip(b):this.hideTooltip(b)}},this)},setCenterDate:function(a){a instanceof Date||(a=new Date(a));this.timeline&&(this.timeline.getBand(0)._decorators[0]._date= a,this.timeline.getBand(0)._decorators[0].paint(),this.timeline.getBand(0).setCenterVisibleDate(a));this.showAnnotations()},addFeatures:function(a,b){var c=!1,d=this.layerLookup[a].titleAttr,e=this.layerLookup[a].timeAttr,f=this.layerLookup[a].endTimeAttr,g=this.layerLookup[a].filterAttr;f&&(c=!0);for(var h=b.length,k=[],l,m=0;m<h;++m){a:{l=b[m].fid;for(var q=this.eventSource.getAllEventIterator();q.hasNext();){var n=q.next();if(n.getProperty("key")===a&&n.getProperty("fid")===l){l=!0;break a}}l= !1}if(!1===l)if(l=b[m].attributes,!1===c)k.push({start:OpenLayers.Date.parse(l[e]),title:l[d],durationEvent:!1,key:a,icon:this.layerLookup[a].icon,fid:b[m].fid});else if(Ext.isBoolean(l[g])?l[g]:"true"===l[g]){var q=l[e],n=l[f],s=q!=n;Ext.isEmpty(q)||(q=parseFloat(q),q=Ext.isNumber(q)?new Date(1E3*q):OpenLayers.Date.parse(q));Ext.isEmpty(n)||(n=parseFloat(n),n=Ext.isNumber(n)?new Date(1E3*n):OpenLayers.Date.parse(n));if(!1===s)n=void 0;else if(""==n||null==n)n=new Date(this.playbackTool.playbackToolbar.control.animationRange[1]); null!=q&&k.push({start:q,end:n,icon:this.layerLookup[a].icon,title:l[d],durationEvent:s,key:a,fid:b[m].fid})}}this.eventSource.loadJSON({dateTimeFormat:"javascriptnative",events:k},"mapstory.org")},onResize:function(){gxp.TimelinePanel.superclass.onResize.apply(this,arguments);this.timeline&&this.timeline.layout()},beforeDestroy:function(){gxp.TimelinePanel.superclass.beforeDestroy.call(this);this.annotationsLayer=null;this.unbindViewer();this.unbindAnnotationsStore();this.unbindPlaybackTool();this.eventSource= null;this.timeline&&(this.timeline.dispose(),this.timeline=null)}});Ext.reg("gxp_timelinepanel",gxp.TimelinePanel);Ext.namespace("gxp.plugins"); gxp.plugins.Timeline=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_timeline",playbackTool:null,menuText:"Timeline",tooltip:"Show Timeline",actionTarget:null,constructor:function(a){gxp.plugins.Timeline.superclass.constructor.apply(this,arguments);this.outputConfig||(this.outputConfig={});Ext.applyIf(this.outputConfig,{title:this.menuText})},addActions:function(){return gxp.plugins.Timeline.superclass.addActions.apply(this,[[{menuText:this.menuText,tooltip:this.tooltip,handler:function(){this.addOutput()}, scope:this}]])},addOutput:function(a){return gxp.plugins.Timeline.superclass.addOutput.call(this,Ext.apply({xtype:"gxp_timelinepanel",viewer:this.target,listeners:{click:function(a){this.fireEvent("click",a)},scope:this},annotationsStore:this.annotationsStore,playbackTool:this.target.tools[this.playbackTool]},this.outputConfig))},getTimelinePanel:function(){return this.output[0]},getState:function(){var a=gxp.plugins.Timeline.superclass.getState.call(this);a.outputConfig=Ext.apply(a.outputConfig|| {},this.getTimelinePanel().getState());return a},setAnnotationsStore:function(a){this.annotationsStore=a;this.output&&this.output[0]&&this.output[0].bindAnnotationsStore(a)}});Ext.preg(gxp.plugins.Timeline.prototype.ptype,gxp.plugins.Timeline);Ext.namespace("gxp.plugins"); gxp.plugins.Measure=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_measure",outputTarget:"map",buttonText:"Measure",lengthMenuText:"Length",areaMenuText:"Area",lengthTooltip:"Measure length",areaTooltip:"Measure area",measureTooltip:"Measure",constructor:function(a){gxp.plugins.Measure.superclass.constructor.apply(this,arguments)},destroy:function(){this.button=null;gxp.plugins.Measure.superclass.destroy.apply(this,arguments)},createMeasureControl:function(a,b){var c=new OpenLayers.StyleMap({"default":new OpenLayers.Style(null, {rules:[new OpenLayers.Rule({symbolizer:{Point:{pointRadius:4,graphicName:"square",fillColor:"white",fillOpacity:1,strokeWidth:1,strokeOpacity:1,strokeColor:"#333333"},Line:{strokeWidth:3,strokeOpacity:1,strokeColor:"#666666",strokeDashstyle:"dash"},Polygon:{strokeWidth:2,strokeOpacity:1,strokeColor:"#666666",fillColor:"white",fillOpacity:.3}}})]})}),d=function(){f&&f.destroy()},e=function(a){var b=a.measure,c=a.units;h.displaySystem="english";var d=-1<a.geometry.CLASS_NAME.indexOf("LineString")? h.getBestLength(a.geometry):h.getBestArea(a.geometry),e=d[0],d=d[1];h.displaySystem="metric";a=2==a.order?"<sup>2</sup>":"";return b.toFixed(2)+" "+c+a+"<br>"+e.toFixed(2)+" "+d+a},f,g=Ext.apply({},this.initialConfig.controlOptions);Ext.applyIf(g,{geodesic:!0,persist:!0,handlerOptions:{layerOptions:{styleMap:c}},eventListeners:{measurepartial:function(a){d();f=this.addOutput({xtype:"tooltip",html:e(a),title:b,autoHide:!1,closable:!0,draggable:!1,mouseOffset:[0,0],showDelay:1,listeners:{hide:d}}); if(0<a.measure){a=h.handler.lastUp;var c=this.target.mapPanel.getPosition();f.targetXY=[c[0]+a.x,c[1]+a.y];f.show()}},deactivate:d,scope:this}});var h=new OpenLayers.Control.Measure(a,g);return h},addActions:function(){this.activeIndex=0;this.button=new Ext.SplitButton({iconCls:"gxp-icon-measure-length",tooltip:this.measureTooltip,buttonText:this.buttonText,enableToggle:!0,toggleGroup:this.toggleGroup,allowDepress:!0,handler:function(a,b){a.pressed&&a.menu.items.itemAt(this.activeIndex).setChecked(!0)}, scope:this,listeners:{toggle:function(a,b){b||a.menu.items.each(function(a){a.setChecked(!1)})},render:function(a){Ext.ButtonToggleMgr.register(a)}},menu:new Ext.menu.Menu({items:[new Ext.menu.CheckItem(new GeoExt.Action({text:this.lengthMenuText,iconCls:"gxp-icon-measure-length",toggleGroup:this.toggleGroup,group:this.toggleGroup,listeners:{checkchange:function(a,b){this.activeIndex=0;this.button.toggle(b);b&&this.button.setIconClass(a.iconCls)},scope:this},map:this.target.mapPanel.map,control:this.createMeasureControl(OpenLayers.Handler.Path, this.lengthTooltip)})),new Ext.menu.CheckItem(new GeoExt.Action({text:this.areaMenuText,iconCls:"gxp-icon-measure-area",toggleGroup:this.toggleGroup,group:this.toggleGroup,allowDepress:!1,listeners:{checkchange:function(a,b){this.activeIndex=1;this.button.toggle(b);b&&this.button.setIconClass(a.iconCls)},scope:this},map:this.target.mapPanel.map,control:this.createMeasureControl(OpenLayers.Handler.Polygon,this.areaTooltip)}))]})});return gxp.plugins.Measure.superclass.addActions.apply(this,[this.button])}}); Ext.preg(gxp.plugins.Measure.prototype.ptype,gxp.plugins.Measure);Ext.namespace("gxp"); gxp.NewSourceDialog=Ext.extend(Ext.Panel,{title:"Add New Server...",cancelText:"Cancel",addServerText:"Add Server",invalidURLText:"Enter a valid URL to a WMS/TMS/REST endpoint (e.g. http://example.com/geoserver/wms)",contactingServerText:"Contacting Server...",bodyStyle:"padding: 0px",error:null,initComponent:function(){this.addEvents("urlselected");this.urlTextField=new Ext.form.TextField({fieldLabel:"URL",allowBlank:!1,width:240,msgTarget:"under",validator:this.urlValidator.createDelegate(this), listeners:{specialkey:function(a,b){b.getKey()===b.ENTER&&this.addServer()},scope:this}});this.form=new Ext.form.FormPanel({items:[{xtype:"combo",width:240,name:"type",fieldLabel:"Type",value:"WMS",mode:"local",triggerAction:"all",store:[["WMS","Web Map Service (WMS)"],["TMS","Tiled Map Service (TMS)"],["REST","ArcGIS REST Service (REST)"]]},this.urlTextField],border:!1,labelWidth:30,bodyStyle:"padding: 5px",autoWidth:!0,autoHeight:!0,listeners:{afterrender:function(){this.urlTextField.focus(!1,!0)}, scope:this}});this.bbar=[new Ext.Button({text:this.cancelText,handler:this.hide,scope:this}),new Ext.Toolbar.Fill,new Ext.Button({text:this.addServerText,iconCls:"add",handler:this.addServer,scope:this})];this.items=this.form;gxp.NewSourceDialog.superclass.initComponent.call(this);this.form.on("render",function(){this.loadMask=new Ext.LoadMask(this.form.getEl(),{msg:this.contactingServerText})},this);this.on({hide:this.reset,removed:this.reset,scope:this});this.on("urlselected",function(a,b){this.setLoading(); this.addSource(b,this.hide,function(){this.setError(this.sourceLoadFailureMessage)},this)},this)},addServer:function(){this.error=null;this.urlTextField.validate()&&this.fireEvent("urlselected",this,this.urlTextField.getValue(),this.form.getForm().findField("type").getValue())},reset:function(){this.error=null;this.urlTextField.reset();this.loadMask.hide()},urlRegExp:/^(http(s)?:)?\/\/([\w%]+:[\w%]+@)?([^@\/:]+)(:\d+)?\//i,urlValidator:function(a){a=this.urlRegExp.test(a)?!this.error||this.error: this.invalidURLText;this.error=null;return a},setLoading:function(){this.loadMask.show()},setError:function(a){this.loadMask.hide();this.error=a;this.urlTextField.validate()},addSource:function(a,b,c,d){}});Ext.reg("gxp_newsourcedialog",gxp.NewSourceDialog);Ext.namespace("gxp.plugins"); gxp.plugins.YouTubeFeedSource=Ext.extend(gxp.plugins.FeedSource,{ptype:"gxp_youtubesource",url:"http://gdata.youtube.com/feeds/api/videos?v=2&prettyprint=true&",format:"OpenLayers.Format.YouTube",title:"Youtube Videos",pointRadius:24,popupTemplate:'<tpl for="."><a target="_blank" href="{link}"><img height="180" width="240" title="{title}" src="{thumbnail}"/></a></tpl>',fixed:!1,createLayerRecord:function(a){Ext.isEmpty(a.params["max-results"])?a.params["max-results"]=50:a.params["max-results"]=Math.min(a.params["max-results"], 50);a.url=this.url;this.format=new OpenLayers.Format.GeoRSS({createFeatureFromItem:function(a){var b=OpenLayers.Format.GeoRSS.prototype.createFeatureFromItem.apply(this,arguments);b.attributes.thumbnail=this.getElementsByTagNameNS(a,"http://search.yahoo.com/mrss/","thumbnail")[4].getAttribute("url");b.attributes.content=OpenLayers.Util.getXmlNodeValue(this.getElementsByTagNameNS(a,"*","summary")[0]);return b}});var b=gxp.plugins.YouTubeFeedSource.superclass.createLayerRecord.apply(this,arguments); b.getLayer().protocol.filterToParams=function(a,b){if(a.type===OpenLayers.Filter.Spatial.BBOX){var e=a.value,f=e.getCenterLonLat(),e=Math.min((6378.137*e.right/180/3.1415926-6378.137*e.left/180/3.1415926)/2*2,1E3);Ext.apply(b,{location:""+f.lat+","+f.lon,"location-radius":e+"km"})}return b};return b},configureInfoPopup:function(a){var b=new Ext.XTemplate(this.popupTemplate);a.events.on({featureselected:function(a){a=a.feature;null!=this.target.selectControl.popup&&this.target.selectControl.popup.close(); this.target.selectControl.popup=new GeoExt.Popup({title:a.attributes.title,location:a,width:240,height:220,closeAction:"destroy",html:b.apply(a.attributes)});this.target.selectControl.popup.show()},featureunselected:function(a){this.target.selectControl&&this.target.selectControl.popup&&this.target.selectControl.popup.close()},scope:this})},getStyleMap:function(a){return new OpenLayers.StyleMap({"default":new OpenLayers.Style({externalGraphic:"${thumbnail}",pointRadius:24},{title:this.title}),select:new OpenLayers.Style({pointRadius:this.pointRadius+ 5})})}});Ext.preg(gxp.plugins.YouTubeFeedSource.prototype.ptype,gxp.plugins.YouTubeFeedSource);Ext.namespace("gxp"); gxp.FeedSourceDialog=Ext.extend(Ext.Container,{feedTypeText:"Source",addPicasaText:"Picasa Photos",addYouTubeText:"YouTube Videos",addRSSText:"GeoRSS Feed",addFeedText:"Add to Map",addTitleText:"Title",keywordText:"Keyword",doneText:"Done",titleText:"Add Feeds",maxResultsText:"Max Items",width:300,autoHeight:!0,closeAction:"destroy",initComponent:function(){this.addEvents("addfeed");this.feedTypes||(this.feedTypes=[[gxp.plugins.PicasaFeedSource.ptype,this.addPicasaText],[gxp.plugins.YouTubeFeedSource.ptype, this.addYouTubeText],[gxp.plugins.FeedSource.ptype,this.addRSSText]]);var a=new Ext.data.ArrayStore({fields:["type","name"],data:this.feedTypes}),b=new Ext.form.ComboBox({store:a,fieldLabel:this.feedTypeText,displayField:"name",valueField:"type",typeAhead:!0,width:180,mode:"local",triggerAction:"all",emptyText:"Select a feed source...",selectOnFocus:!0,listeners:{select:function(a){a.value==gxp.plugins.FeedSource.ptype?(c.show(),d.hide(),f.hide(),g.show()):(c.hide(),d.show(),f.show(),g.hide());h.setDisabled(null== a.value)},scope:this}}),c=new Ext.form.TextField({fieldLabel:"URL",allowBlank:!1,width:180,msgTarget:"right",validator:this.urlValidator.createDelegate(this)}),d=new Ext.form.TextField({fieldLabel:this.keywordText,allowBlank:!0,hidden:!0,width:180,msgTarget:"right"}),e=new Ext.form.TextField({fieldLabel:this.addTitleText,allowBlank:!0,width:180,msgTarget:"right"}),f=new Ext.form.ComboBox({fieldLabel:this.maxResultsText,hidden:!0,hiddenName:"max-results",store:new Ext.data.ArrayStore({fields:["max-results"], data:[[10],[25],[50],[100]]}),displayField:"max-results",mode:"local",triggerAction:"all",emptyText:"Choose number...",labelWidth:70,width:180,defaults:{labelWidth:70,width:180}}),g=new gxp.PointSymbolizer({bodyStyle:{padding:"10px"},width:280,border:!1,hidden:!0,labelWidth:70,defaults:{labelWidth:70},symbolizer:{pointGraphics:"circle",pointRadius:"5"}});g.find("name","rotation")[0].hidden=!0;"Point"===this.symbolType&&this.pointGraphics&&(cfg.pointGraphics=this.pointGraphics);var h=new Ext.Button({text:this.addFeedText, iconCls:"gxp-icon-addlayers",disabled:!0,handler:function(){var a=b.getValue(),h={name:e.getValue()};if("gxp_feedsource"!=a)h.params={q:d.getValue(),"max-results":f.getValue()};else{h.url=c.getValue();var m=g.symbolizer;h.defaultStyle={};h.selectStyle={};Ext.apply(h.defaultStyle,m);Ext.apply(h.selectStyle,m);Ext.apply(h.selectStyle,{fillColor:"Yellow",pointRadius:parseInt(m.pointRadius)+2})}this.fireEvent("addfeed",a,h)},scope:this}),a=["->",h,new Ext.Button({text:this.doneText,handler:function(){this.hide()}, scope:this})];this.items=this.panel=new Ext.Panel({bbar:a,autoScroll:!0,items:[b,e,c,d,f,g],layout:"form",border:!1,labelWidth:100,bodyStyle:"padding: 5px",autoWidth:!0,autoHeight:!0});gxp.FeedSourceDialog.superclass.initComponent.call(this)},urlRegExp:/^(http(s)?:)?\/\/([\w%]+:[\w%]+@)?([^@\/:]+)(:\d+)?\//i,urlValidator:function(a){a=this.urlRegExp.test(a)?!this.error||this.error:this.invalidURLText;this.error=null;return a}});Ext.reg("gxp_feedsourcedialog",gxp.FeedSourceDialog);Ext.namespace("gxp.plugins"); gxp.plugins.CatalogueSource=Ext.extend(gxp.plugins.WMSSource,{url:null,yx:null,title:null,lazy:!0,hidden:!0,proxyOptions:null,describeLayer:function(a,b,c){a=new (Ext.data.Record.create([{name:"owsType",type:"string"},{name:"owsURL",type:"string"},{name:"typeName",type:"string"}]))({owsType:"WFS",owsURL:a.get("url"),typeName:a.get("name")});b.call(c,a)},destroy:function(){this.store&&this.store.destroy();this.store=null;gxp.plugins.CatalogueSource.superclass.destroy.apply(this,arguments)}});Ext.namespace("gxp.plugins"); gxp.plugins.GeoNodeCatalogueSource=Ext.extend(gxp.plugins.CatalogueSource,{ptype:"gxp_geonodecataloguesource",rootProperty:"results",baseParams:null,fields:[{name:"title",convert:function(a){return[a]}},{name:"abstract",mapping:"description"},{name:"bounds",mapping:"bbox",convert:function(a){return{left:a.minx,right:a.maxx,bottom:a.miny,top:a.maxy}}},{name:"URI",mapping:"links",convert:function(a){var b=[],c;for(c in a)b.push({value:a[c].url});return b}}],createStore:function(){this.store=new Ext.data.Store({proxy:new Ext.data.HttpProxy(Ext.apply({url:this.url, method:"GET"},this.proxyOptions||{})),baseParams:Ext.apply({type:"layer"},this.baseParams),reader:new Ext.data.JsonReader({root:this.rootProperty},this.fields)});gxp.plugins.LayerSource.prototype.createStore.apply(this,arguments)},getPagingStart:function(){return 0},getPagingParamNames:function(){return{start:"startIndex",limit:"limit"}},filter:function(a){var b=void 0;if(void 0!==a.filters)for(var c=0,d=a.filters.length;c<d;++c){var e=a.filters[c];if(e instanceof OpenLayers.Filter.Spatial){b=e.value.toBBOX(); break}}Ext.apply(this.store.baseParams,{q:a.queryString});void 0!==a.limit&&Ext.apply(this.store.baseParams,{limit:a.limit});void 0!==b?Ext.apply(this.store.baseParams,{bbox:b}):delete this.store.baseParams.bbox;this.store.load()},createLayerRecord:function(a){a.restUrl=this.restUrl;a.queryable=!0;return gxp.plugins.GeoNodeCatalogueSource.superclass.createLayerRecord.apply(this,arguments)}});Ext.preg(gxp.plugins.GeoNodeCatalogueSource.prototype.ptype,gxp.plugins.GeoNodeCatalogueSource);Ext.namespace("gxp.form"); gxp.form.CSWFilterField=Ext.extend(Ext.form.CompositeField,{clearTooltip:"Clear the filter for this category",emptyText:"Select filter",property:null,map:null,type:OpenLayers.Filter.Comparison.EQUAL_TO,name:null,comboFieldLabel:null,comboStoreData:null,target:null,getFilter:function(){return"BoundingBox"===this.property?new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.BBOX,property:this.property,projection:"EPSG:4326",value:this.map.getExtent().transform(this.map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326"))}):new OpenLayers.Filter.Comparison({type:this.type,property:this.property,value:this.combo.getValue()})},initComponent:function(){this.items=[{ref:"combo",xtype:"combo",fieldLabel:this.comboFieldLabel,store:new Ext.data.ArrayStore({fields:["id","value"],data:this.comboStoreData}),displayField:"value",valueField:"id",mode:"local",listeners:{select:function(a,b){this.filter&&this.target.removeFilter(this.filter);this.filter=this.getFilter();this.target.addFilter(this.filter); return!1},scope:this},emptyText:this.emptyText,triggerAction:"all"},{xtype:"button",iconCls:"gxp-icon-removelayers",tooltip:this.clearTooltip,handler:function(a){this.target.removeFilter(this.filter);this.hide()},scope:this}];this.hidden=!0;gxp.form.CSWFilterField.superclass.initComponent.apply(this,arguments)},destroy:function(){this.map=this.target=this.filter=null;gxp.form.CSWFilterField.superclass.destroy.call(this)}});Ext.reg("gxp_cswfilterfield",gxp.form.CSWFilterField);Ext.namespace("gxp"); gxp.CatalogueSearchPanel=Ext.extend(Ext.Panel,{border:!1,maxRecords:10,map:null,selectedSource:null,sources:null,searchFieldEmptyText:"Search",searchButtonText:"Search",addTooltip:"Create filter",addMapTooltip:"Add to map",advancedTitle:"Advanced",datatypeLabel:"Data type",extentLabel:"Spatial extent",categoryLabel:"Category",datasourceLabel:"Data source",filterLabel:"Filter search by",removeSourceTooltip:"Switch back to original source",initComponent:function(){var a=this;this.addEvents("addlayer"); this.filters=[];var b=[],c;for(c in this.sources)b.push([c,this.sources[c].title]);1<=b.length&&(this.selectedSource=b[0][0]);c=[["datatype","data type"],["extent","spatial extent"],["category","category"]];1<b.length&&c.push(["csw","data source"]);this.sources[this.selectedSource].store.on("loadexception",function(a,b,c,g){c.success()&&Ext.Msg.show({title:g.message,msg:gxp.util.getOGCExceptionText(g.arg.exceptionReport),icon:Ext.MessageBox.ERROR,buttons:Ext.MessageBox.OK})});this.items=[{xtype:"form", border:!1,ref:"form",hideLabels:!0,autoHeight:!0,style:"margin-left: 5px; margin-right: 5px; margin-bottom: 5px; margin-top: 5px",items:[{xtype:"compositefield",items:[{xtype:"textfield",emptyText:this.searchFieldEmptyText,ref:"../../search",name:"search",listeners:{specialkey:function(a,b){b.getKey()==b.ENTER&&this.performQuery()},scope:this},width:250},{xtype:"button",text:this.searchButtonText,handler:this.performQuery,scope:this}]},{xtype:"fieldset",collapsible:!0,collapsed:!0,hideLabels:!1,hidden:!0, title:this.advancedTitle,items:[{xtype:"gxp_cswfilterfield",name:"datatype",property:"apiso:Type",comboFieldLabel:this.datatypeLabel,comboStoreData:[["dataset","Dataset"],["datasetcollection","Dataset collection"],["application","Application"],["service","Service"]],target:this},{xtype:"gxp_cswfilterfield",name:"extent",property:"BoundingBox",map:this.map,comboFieldLabel:this.extentLabel,comboStoreData:[["map","spatial extent of the map"]],target:this},{xtype:"gxp_cswfilterfield",name:"category", property:"apiso:TopicCategory",comboFieldLabel:this.categoryLabel,comboStoreData:[["farming","Farming"],["biota","Biota"],["boundaries","Boundaries"],["climatologyMeteorologyAtmosphere","Climatology/Meteorology/Atmosphere"],["economy","Economy"],["elevation","Elevation"],["environment","Environment"],["geoscientificinformation","Geoscientific Information"],["health","Health"],["imageryBaseMapsEarthCover","Imagery/Base Maps/Earth Cover"],["intelligenceMilitary","Intelligence/Military"],["inlandWaters", "Inland Waters"],["location","Location"],["oceans","Oceans"],["planningCadastre","Planning Cadastre"],["society","Society"],["structure","Structure"],["transportation","Transportation"],["utilitiesCommunications","Utilities/Communications"]],target:this},{xtype:"compositefield",id:"csw",ref:"../../cswCompositeField",hidden:!0,items:[{xtype:"combo",ref:"../../../sourceCombo",fieldLabel:this.datasourceLabel,store:new Ext.data.ArrayStore({fields:["id","value"],data:b}),displayField:"value",valueField:"id", mode:"local",listeners:{select:function(a,b){this.setSource(a.getValue())},render:function(){this.sourceCombo.setValue(this.selectedSource)},scope:this},triggerAction:"all"},{xtype:"button",iconCls:"gxp-icon-removelayers",tooltip:this.removeSourceTooltip,handler:function(a){this.setSource(this.initialConfig.selectedSource);this.sourceCombo.setValue(this.initialConfig.selectedSource);this.cswCompositeField.hide()},scope:this}]},{xtype:"compositefield",items:[{xtype:"combo",fieldLabel:this.filterLabel, store:new Ext.data.ArrayStore({fields:["id","value"],data:c}),displayField:"value",valueField:"id",mode:"local",triggerAction:"all"},{xtype:"button",iconCls:"gxp-icon-addlayers",tooltip:this.addTooltip,handler:function(a){a.ownerCt.items.each(function(a){if("combo"===a.getXType()){var b=a.getValue();a.clearValue();(a=this.form.getForm().findField(b))&&a.show()}},this)},scope:this}]}]},{xtype:"grid",width:"100%",anchor:"99%",viewConfig:{scrollOffset:0,forceFit:!0},border:!1,ref:"../grid",bbar:new Ext.PagingToolbar({listeners:{beforechange:function(b, c){var f=a.sources[a.selectedSource].getPagingStart();c.startPosition&&(c.startPosition+=f)}},onLoad:function(b,c,f){var g=a.sources[a.selectedSource].getPagingStart();this.rendered?(b=this.getParams(),this.cursor=f.params&&f.params[b.start]?f.params[b.start]-g:0,f=this.getPageData(),g=f.activePage,b=f.pages,this.afterTextItem.setText(String.format(this.afterPageText,f.pages)),this.inputItem.setValue(g),this.first.setDisabled(1==g),this.prev.setDisabled(1==g),this.next.setDisabled(g==b),this.last.setDisabled(g== b),this.refresh.enable(),this.updateInfo(),this.fireEvent("change",this,f)):this.dsLoaded=[b,c,f]},paramNames:this.sources[this.selectedSource].getPagingParamNames(),store:this.sources[this.selectedSource].store,pageSize:this.maxRecords}),loadMask:!0,hideHeaders:!0,store:this.sources[this.selectedSource].store,columns:[{id:"title",xtype:"templatecolumn",tpl:new Ext.XTemplate("<b>{title}</b><br/>{abstract}"),sortable:!0},{xtype:"actioncolumn",width:30,items:[{getClass:function(a,b,c){if(!1!==this.findWMS(c.get("URI"))|| !1!==this.findWMS(c.get("references")))return"gxp-icon-addlayers"},tooltip:this.addMapTooltip,handler:function(a,b,c){a=this.grid.store.getAt(b);this.addLayer(a)},scope:this}]}],autoExpandColumn:"title",autoHeight:!0}]}];gxp.CatalogueSearchPanel.superclass.initComponent.apply(this,arguments)},destroy:function(){this.map=this.sources=null;gxp.CatalogueSearchPanel.superclass.destroy.call(this)},setSource:function(a){this.selectedSource=a;a=this.sources[a].store;this.grid.reconfigure(a,this.grid.getColumnModel()); this.grid.getBottomToolbar().bindStore(a)},performQuery:function(){this.sources[this.selectedSource].filter({queryString:this.search.getValue(),limit:this.maxRecords,filters:this.filters})},addFilter:function(a){this.filters.push(a)},removeFilter:function(a){this.filters.remove(a)},findWMS:function(a){var b=["OGC:WMS-1.1.1-HTTP-GET-MAP","OGC:WMS"],c=null,d=null,e,f,g;e=0;for(f=a.length;e<f;++e)if(g=a[e],g.protocol&&-1!==b.indexOf(g.protocol.toUpperCase())&&g.value&&g.name){c=g.value;d=g.name;break}if(null=== c)for(e=0,f=a.length;e<f;++e)if(g=a[e],b=g.value?g.value:g,0<b.toLowerCase().indexOf("service=wms")){a=OpenLayers.Util.createUrlObject(b);c=a.protocol+"//"+a.host+":"+a.port+a.pathname;d=a.args.layers;break}return null!==c&&null!==d?{url:c,name:d}:!1},addLayer:function(a){var b=a.get("URI"),c=a.get("bounds"),d=c.left,e=c.right,f=c.bottom,g=c.top,c=Math.min(d,e),d=Math.max(d,e),e=Math.min(f,g),f=Math.max(f,g),b=this.findWMS(b);!1===b&&(b=a.get("references"),b=this.findWMS(b));!1!==b&&this.fireEvent("addlayer", this,this.selectedSource,Ext.apply({title:a.get("title")[0],bbox:[c,e,d,f],srs:"EPSG:4326",projection:a.get("projection")},b))}});Ext.reg("gxp_cataloguesearchpanel",gxp.CatalogueSearchPanel);Ext.ns("gxp.data","gxp.plugins"); gxp.data.TMSCapabilitiesReader=Ext.extend(Ext.data.DataReader,{constructor:function(a,b){a=a||{};a.format||(a.format=new OpenLayers.Format.TMSCapabilities);"function"!==typeof b&&(b=GeoExt.data.LayerRecord.create(b||a.fields||[{name:"name",type:"string"},{name:"title",type:"string"},{name:"tileMapUrl",type:"string"}]));gxp.data.TMSCapabilitiesReader.superclass.constructor.call(this,a,b)},read:function(a){var b=a.responseXML;b&&b.documentElement||(b=a.responseText);return this.readRecords(b)},readRecords:function(a){var b= [],c,d,e;if("string"===typeof a||a.nodeType)if(this.raw=a=this.meta.format.read(a),a.tileMaps)for(c=0,d=a.tileMaps.length;c<d;++c){var f=a.tileMaps[c];e=new OpenLayers.Projection(f.srs);if(this.meta.mapProjection.equals(e)){e=f.href;var g=e.substring(e.indexOf(this.meta.version+"/")+6);b.push(new this.recordType({layer:new OpenLayers.Layer.TMS(f.title,-1!==this.meta.baseUrl.indexOf(this.meta.version)?this.meta.baseUrl.replace(this.meta.version+"/",""):this.meta.baseUrl,{layername:g}),title:f.title, name:f.title,tileMapUrl:e}))}}else if(a.tileSets&&(e=new OpenLayers.Projection(a.srs),this.meta.mapProjection.equals(e))){f=[];c=0;for(d=a.tileSets.length;c<d;++c)f.push(a.tileSets[c].unitsPerPixel);e=this.meta.baseUrl;c=e.substring(e.indexOf(this.meta.version)+this.meta.version.length+1,e.lastIndexOf("/"));b.push(new this.recordType({layer:new OpenLayers.Layer.TMS(a.title,a.tileMapService.replace("/"+this.meta.version,""),{serverResolutions:f,type:a.tileFormat.extension,layername:c}),title:a.title, name:a.title,tileMapUrl:this.meta.baseUrl}))}return{totalRecords:b.length,success:!0,records:b}}}); gxp.plugins.TMSSource=Ext.extend(gxp.plugins.LayerSource,{ptype:"gxp_tmssource",version:"1.0.0",constructor:function(a){gxp.plugins.TMSSource.superclass.constructor.apply(this,arguments);this.format=new OpenLayers.Format.TMSCapabilities;"/"!==this.url.slice(-1)&&(this.url+="/")},createStore:function(){this.store=new Ext.data.Store({autoLoad:!0,listeners:{load:function(){this.title=this.store.reader.raw.title;this.fireEvent("ready",this)},exception:function(){this.fireEvent("failure",this,"Trouble creating TMS layer store from response.", "Unable to handle response.")},scope:this},proxy:new Ext.data.HttpProxy({url:-1===this.url.indexOf(this.version)?this.url+this.version:this.url,disableCaching:!1,method:"GET"}),reader:new gxp.data.TMSCapabilitiesReader({baseUrl:this.url,version:this.version,mapProjection:this.getMapProjection()})})},createLayerRecord:function(a,b,c){var d=this.store.findExact("name",a.name);if(-1<d){var d=this.store.getAt(d),e=d.getLayer();if(null!==e.serverResolutions)return d;Ext.Ajax.request({url:d.get("tileMapUrl"), success:function(d){var g=[];d=this.format.read(d.responseText);for(var h=0,k=d.tileSets.length;h<k;++h)g.push(d.tileSets[h].unitsPerPixel);e.addOptions({serverResolutions:g,type:d.tileFormat.extension});this.target.createLayerRecord({source:this.id,name:a.name},b,c)},scope:this})}}});Ext.preg(gxp.plugins.TMSSource.prototype.ptype,gxp.plugins.TMSSource);Ext.namespace("gxp.plugins"); gxp.plugins.AddLayers=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_addlayers",addActionMenuText:"Add layers",findActionMenuText:"Find layers",addFeedActionMenuText:"Add feeds",addActionTip:"Add layers",addServerText:"Add a New Server",addButtonText:"Add layers",untitledText:"Untitled",addLayerSourceErrorText:"Error getting {type} capabilities ({msg}).\nPlease check the url and try again.",availableLayersText:"Available Layers",searchText:"Search for layers",expanderTemplateText:"<p><b>Abstract:</b> {abstract}</p>", panelTitleText:"Title",layerSelectionText:"View available data from:",doneText:"Done",uploadRoles:["ROLE_ADMINISTRATOR"],uploadText:"Upload layers",relativeUploadOnly:!0,startSourceId:null,catalogSourceKey:null,selectedSource:null,addServerId:null,constructor:function(a){this.addEvents("sourceselected");gxp.plugins.AddLayers.superclass.constructor.apply(this,arguments)},addActions:function(){var a={tooltip:this.addActionTip,text:this.addActionText,menuText:this.addActionMenuText,disabled:!0,iconCls:"gxp-icon-addlayers"}, b;if(this.initialConfig.search||this.uploadSource){var c=[new Ext.menu.Item({iconCls:"gxp-icon-addlayers",text:this.addActionMenuText,handler:this.showCapabilitiesGrid,scope:this})];if(this.initialConfig.search&&this.initialConfig.search.selectedSource&&this.target.sources[this.initialConfig.search.selectedSource]){var d=new Ext.menu.Item({iconCls:"gxp-icon-addlayers",text:this.findActionMenuText,handler:this.showCatalogueSearch,scope:this});c.push(d);Ext.Ajax.request({method:"GET",url:this.target.sources[this.initialConfig.search.selectedSource].url, callback:function(a,b,c){!1===b&&(this.target.layerSources[this.initialConfig.search.selectedSource].disable(),d.hide())},scope:this})}this.initialConfig.feeds&&c.push(new Ext.menu.Item({iconCls:"gxp-icon-addlayers",text:this.addFeedActionMenuText,handler:this.showFeedDialog,scope:this}));this.uploadSource&&(b=this.createUploadButton(Ext.menu.Item))&&c.push(b);a=Ext.apply(a,{menu:new Ext.menu.Menu({items:c})})}else a=Ext.apply(a,{handler:this.showCapabilitiesGrid,scope:this});var e=gxp.plugins.AddLayers.superclass.addActions.apply(this, [a]);this.target.on("ready",function(){if(this.uploadSource){var a=this.target.layerSources[this.uploadSource];a?this.setSelectedSource(a):(delete this.uploadSource,b&&b.hide())}e[0].enable()},this);return e},showCatalogueSearch:function(){var a=this.initialConfig.search.selectedSource,b={},c=!1,d;for(d in this.target.layerSources){var e=this.target.layerSources[d];e instanceof gxp.plugins.CatalogueSource&&(c={},c[d]=e,Ext.apply(b,c),c=!0)}if(!1===c)window.console&&window.console.debug("No catalogue source specified"); else return a=gxp.plugins.AddLayers.superclass.addOutput.apply(this,[{sources:b,title:this.searchText,height:300,width:315,selectedSource:a,xtype:"gxp_cataloguesearchpanel",map:this.target.mapPanel.map}]),a.on({addlayer:function(a,b,c){a=this.target.layerSources[b];var d=OpenLayers.Bounds.fromArray(c.bbox,a.yx&&!0===a.yx[c.projection]),e=this.target.mapPanel.map.getProjection(),d=d.transform(c.srs,e);c.srs=e;c.bbox=d.toArray();c.source=null!==this.initialConfig.catalogSourceKey?this.initialConfig.catalogSourceKey: b;b=a.createLayerRecord(c);this.target.mapPanel.layers.add(b);d&&this.target.mapPanel.map.zoomToExtent(d)},scope:this}),(b=a.findParentByType("window"))&&b.center(),a},showCapabilitiesGrid:function(){this.capGrid?this.capGrid instanceof Ext.Window||this.addOutput(this.capGrid):this.initCapGrid();this.capGrid.show()},showFeedDialog:function(){if(!this.feedDialog){var a=this.outputTarget?Ext.Panel:Ext.Window;this.feedDialog=new a(Ext.apply({closeAction:"hide",autoScroll:!0,title:this.addFeedActionMenuText, items:[{xtype:"gxp_feedsourcedialog",target:this.target,listeners:{addfeed:function(a,c){var d={config:{ptype:a}};c.url&&(d.config.url=c.url);d=this.target.addLayerSource(d);c.source=d.id;d=d.createLayerRecord(c);this.target.mapPanel.layers.add([d]);this.feedDialog.hide()},scope:this}}]},this.initialConfig.outputConfig));a===Ext.Panel&&this.addOutput(this.feedDialog)}this.feedDialog instanceof Ext.Window||this.addOutput(this.feedDialog);this.feedDialog.show()},initCapGrid:function(){function a(){function a(b){d&& d.push(b);e--;0===e&&this.addLayers(d)}for(var b=this.selectedSource,c=h.getSelectionModel().getSelections(),d=[],e=c.length,f=0,g=c.length;f<g;++f){var k=b.createLayerRecord({name:c[f].get("name"),source:b.id},a,this);k&&a.call(this,k)}}var b,c=[],d=this.target,e;for(e in d.layerSources)b=d.layerSources[e],b.store&&!b.hidden&&c.push([e,b.title||e,b.url]);var f=new Ext.data.ArrayStore({fields:["id","title","url"],data:c});e=this.createExpander();var g=0;null!==this.startSourceId&&f.each(function(a){a.get("id")=== this.startSourceId&&(g=f.indexOf(a))},this);b=this.target.layerSources[c[g][0]];var h=new Ext.grid.GridPanel({store:b.store,autoScroll:!0,autoExpandColumn:"title",plugins:[e],loadMask:!0,colModel:new Ext.grid.ColumnModel([e,{id:"title",header:this.panelTitleText,dataIndex:"title",sortable:!0},{header:"Id",dataIndex:"name",width:120,sortable:!0}]),listeners:{rowdblclick:a,scope:this}}),k=new Ext.form.ComboBox({ref:"../../sourceComboBox",width:165,store:f,valueField:"id",displayField:"title",tpl:'<tpl for="."><div ext:qtip="{url}" class="x-combo-list-item">{title}</div></tpl>', triggerAction:"all",editable:!1,allowBlank:!1,forceSelection:!0,mode:"local",value:c[g][0],listeners:{select:function(a,b,c){b=b.get("id");b===this.addServerId?(m.outputTarget?m.addOutput(l):(new Ext.Window({title:gxp.NewSourceDialog.prototype.title,modal:!0,hideBorders:!0,width:300,items:l})).show(),k.reset()):(b=this.target.layerSources[b],h.reconfigure(b.store,h.getColumnModel()),h.getView().focusRow(0),this.setSelectedSource(b),function(){a.triggerBlur();a.el.blur()}.defer(100))},focus:function(a){d.proxy&& a.reset()},scope:this}});b=null;if(this.target.proxy||1<c.length)b=new Ext.Container({cls:"gxp-addlayers-sourceselect",items:[new Ext.Toolbar.TextItem({text:this.layerSelectionText}),k]}),b=[b];this.target.proxy&&(this.addServerId=Ext.id(),f.loadData([[this.addServerId,this.addServerText+"..."]],!0));var l={xtype:"gxp_newsourcedialog",header:!1,listeners:{hide:function(a){this.outputTarget||a.ownerCt.hide()},urlselected:function(a,b,c){a.setLoading();var d;switch(c){case "TMS":d="gxp_tmssource";break; case "REST":d="gxp_arcrestsource";break;default:d="gxp_wmscsource"}this.target.addLayerSource({config:{url:b,ptype:d},callback:function(b){b=new f.recordType({id:b,title:this.target.layerSources[b].title||this.untitledText});f.insert(0,[b]);k.onSelect(b,0);a.hide()},fallback:function(b,d){a.setError((new Ext.Template(this.addLayerSourceErrorText)).apply({type:c,msg:d}))},scope:this})},scope:this}},m=this;e={xtype:"container",region:"center",layout:"fit",hideBorders:!0,items:[h]};this.instructionsText&& e.items.push({xtype:"box",autoHeight:!0,autoEl:{tag:"p",cls:"x-form-item",style:"padding-left: 5px; padding-right: 5px"},html:this.instructionsText});var q=["->",new Ext.Button({text:this.addButtonText,iconCls:"gxp-icon-addlayers",handler:a,scope:this}),new Ext.Button({text:this.doneText,handler:function(){this.capGrid.hide()},scope:this})],n;this.uploadSource||(n=this.createUploadButton())&&q.unshift(n);n=this.outputTarget?Ext.Panel:Ext.Window;this.capGrid=new n(Ext.apply({title:this.availableLayersText, closeAction:"hide",layout:"border",height:300,width:315,modal:!0,items:e,tbar:b,bbar:q,listeners:{hide:function(a){h.getSelectionModel().clearSelections()},show:function(a){null===this.selectedSource?this.setSelectedSource(this.target.layerSources[c[g][0]]):this.setSelectedSource(this.selectedSource)},scope:this}},this.initialConfig.outputConfig));n===Ext.Panel&&this.addOutput(this.capGrid)},addLayers:function(a,b){for(var c=this.selectedSource,d=this.target.mapPanel.layers,e,f,g,h=0,k=a.length;h< k;++h)if(f=c.createLayerRecord({name:a[h].get("name"),source:c.id})||a[h])g=f.getLayer(),g.maxExtent&&(e?e.extend(f.getLayer().maxExtent):e=f.getLayer().maxExtent.clone()),"background"===f.get("group")?d.insert(1,[f]):d.add([f]);e&&this.target.mapPanel.map.zoomToExtent(e);if(1===a.length&&f&&(this.target.selectLayer(f),b&&this.postUploadAction)){var l,c=this.postUploadAction;Ext.isString(c)||(l=c.outputConfig,c=c.plugin);this.target.tools[c].addOutput(l)}},setSelectedSource:function(a,b){this.selectedSource= a;this.fireEvent("sourceselected",this,a);this.capGrid&&a.lazy&&a.store.load({callback:function(){var a=this.capGrid.sourceComboBox,b=a.store,e=a.valueField,f=b.findExact(e,a.getValue()),f=b.getAt(f),g=this.target.layerSources[f.get("id")];g?g.title===f.get("title")||Ext.isEmpty(g.title)||(f.set("title",g.title),a.setValue(f.get(e))):b.remove(f)}.createDelegate(this)})},createUploadButton:function(a){a=a||Ext.Button;var b,c=this.initialConfig.upload||!!this.initialConfig.uploadSource,d;if(c){var e= function(a,b,c){a in f?window.setTimeout(function(){b.call(c,f[a])},0):Ext.Ajax.request({url:a,disableCaching:!1,callback:function(d,e,q){d=q.status;f[a]=d;b.call(c,d)}})};"boolean"===typeof c&&(c={});b=new a({text:this.uploadText,iconCls:"gxp-icon-filebrowse",hidden:!this.uploadSource,handler:function(){this.target.doAuthorized(this.uploadRoles,function(){var a=new gxp.LayerUploadPanel(Ext.apply({title:this.outputTarget?this.uploadText:void 0,url:d,width:300,border:!1,bodyStyle:"padding: 10px 10px 0 10px;", labelWidth:65,autoScroll:!0,defaults:{anchor:"99%",allowBlank:!1,msgTarget:"side"},listeners:{uploadcomplete:function(a,c){for(var d=c["import"].tasks,e,f={},g=0,r=d.length;g<r;++g){e=d[g];if("ERROR"===e.state){Ext.Msg.alert(e.layer.originalName,e.errorMessage);return}var t;e.target.dataStore?t=e.target.dataStore.workspace.name:e.target.coverageStore&&(t=e.target.coverageStore.workspace.name);f[t+":"+e.layer.name]=!0}this.selectedSource.store.load({params:{_dc:Math.random()},callback:function(a,b, c){var d,e;this.capGrid&&this.capGrid.isVisible()&&(d=this.capGrid.get(0).get(0),e=d.getSelectionModel(),e.clearSelections());var g=[],h=0;this.selectedSource.store.each(function(a,b){a.get("name")in f&&(h=b,g.push(a))});d?window.setTimeout(function(){e.selectRecords(g);d.getView().focusRow(h)},100):this.addLayers(g,!0)},scope:this});this.outputTarget?a.hide():b.close()},scope:this}},c)),b;this.outputTarget?this.addOutput(a):(b=new Ext.Window({title:this.uploadText,modal:!0,resizable:!1,items:[a]}), b.show())},this)},scope:this});var f={};this.on({sourceselected:function(a,c){b[this.uploadSource?"show":"hide"]();this.isEligibleForUpload(c)&&(d=this.getGeoServerRestUrl(c.url),this.target.isAuthorized()&&e(d+"/imports",function(a){b.setVisible(200===a)},this))},scope:this})}return b},getGeoServerRestUrl:function(a){a=a.split("/");a.pop();a.push("rest");return a.join("/")},isEligibleForUpload:function(a){return a.url&&(this.relativeUploadOnly?"/"===a.url.charAt(0):!0)&&-1===(this.nonUploadSources|| []).indexOf(a.id)},createExpander:function(){return new Ext.grid.RowExpander({tpl:new Ext.Template(this.expanderTemplateText)})}});Ext.preg(gxp.plugins.AddLayers.prototype.ptype,gxp.plugins.AddLayers);Ext.namespace("gxp.slider"); gxp.slider.ClassBreakSlider=Ext.extend(Ext.slider.MultiSlider,{store:null,initComponent:function(){this.store=Ext.StoreMgr.lookup(this.store);"constrainThumbs"in this.initialConfig||(this.constrainThumbs=this.store.reader.raw instanceof OpenLayers.Style);this.values=this.storeToValues();this.on("changecomplete",this.valuesToStore);this.store.on("update",this.storeToValues,this);gxp.slider.ClassBreakSlider.superclass.initComponent.call(this)},storeToValues:function(){var a=[];this.store.each(function(b){var d= b.get("filter");d instanceof OpenLayers.Filter?d.type===OpenLayers.Filter.Comparison.BETWEEN?(0===this.store.indexOf(b)&&a.push(d.lowerBoundary),a.push(d.upperBoundary)):d.type===OpenLayers.Filter.Comparison.LESS_THAN&&a.push(d.value):a.push(d)},this);if(this.thumbs)for(var b=a.length-1;0<=b;--b)this.setValue(b,a[b]);return a},valuesToStore:function(){var a=this.getValues(),b=this.store;b.un("update",this.storeToValues,this);b.each(function(b){var d=b.get("filter"),e=a.shift();d instanceof OpenLayers.Filter? (d=d.clone(),d.type===OpenLayers.Filter.Comparison.BETWEEN?d.upperBoundary=e:d.type===OpenLayers.Filter.Comparison.LESS_THAN&&(d.value=e),b.get("filter").toString()!==d.toString()&&b.set("filter",d)):d!=e&&b.set("filter",e)},this);b.on("update",this.storeToValues,this)}});Ext.reg("gxp_classbreakslider",gxp.slider.ClassBreakSlider);Ext.namespace("gxp.form"); gxp.form.PlaybackModeComboBox=Ext.extend(Ext.form.ComboBox,{modeFieldText:"Playback Mode",normalOptText:"Normal",cumulativeOptText:"Cumulative",rangedOptText:"Ranged",modes:[],defaultMode:"track",agents:null,allowBlank:!1,mode:"local",triggerAction:"all",editable:!1,constructor:function(a){this.addEvents("beforemodechange","modechange");a.modes||this.modes.length||this.modes.push(["track",this.normalOptText],["cumulative",this.cumulativeOptText],["ranged",this.rangedOptText]);gxp.form.PlaybackModeComboBox.superclass.constructor.call(this, a)},initComponent:function(){Ext.applyIf(this,{displayField:"field2",valueField:"field1",store:this.modes,value:this.defaultMode,listeners:{select:this.setPlaybackMode,scope:this}});gxp.form.PlaybackModeComboBox.superclass.initComponent.call(this)},setPlaybackMode:function(a,b,c){this.fireEvent("beforemodechange");if(!this.agents&&window.console)window.console.warn("No agents configured for playback mode combobox");else{var d=b.get("field1");Ext.each(this.agents,function(a){a.tickMode=d;"range"!= d||a.rangeInterval||(a.rangeInterval=1)});this.fireEvent("modechange",this,d,this.agents)}}});Ext.reg("gxp_playbackmodecombo",gxp.form.PlaybackModeComboBox);Ext.namespace("gxp"); gxp.PlaybackOptionsPanel=Ext.extend(Ext.Panel,{layout:"fit",titleText:"Date & Time Options",rangeFieldsetText:"Time Range",animationFieldsetText:"Animation Options",startText:"Start",endText:"End",listOnlyText:"Use Exact List Values Only",stepText:"Animation Step",unitsText:"Animation Units",noUnitsText:"Snap To Time List",loopText:"Loop Animation",reverseText:"Reverse Animation",rangeChoiceText:"Choose the range for the time control",rangedPlayChoiceText:"Playback Mode",initComponent:function(){var a= Ext.applyIf(this.initialConfig,{minHeight:400,minWidth:275,ref:"optionsPanel",items:[{xtype:"form",layout:"form",autoScroll:!0,ref:"form",labelWidth:10,defaultType:"textfield",items:[{xtype:"fieldset",title:this.rangeFieldsetText,defaultType:"datefield",labelWidth:60,items:[{xtype:"displayfield",text:this.rangeChoiceText},{fieldLabel:this.startText,listeners:{select:this.setStartTime,change:this.setStartTime,scope:this},ref:"../../rangeStartField"},{fieldLabel:this.endText,listeners:{select:this.setEndTime, change:this.setEndTime,scope:this},ref:"../../rangeEndField"}]},{xtype:"fieldset",title:this.animationFieldsetText,labelWidth:100,items:[{boxLabel:this.listOnlyText,hideLabel:!0,xtype:"checkbox",handler:this.toggleListMode,scope:this,ref:"../../listOnlyCheck"},{fieldLabel:this.stepText,xtype:"numberfield",anchor:"-25",enableKeyEvents:!0,listeners:{change:this.setStep,scope:this},ref:"../../stepValueField"},{fieldLabel:this.unitsText,xtype:"combo",anchor:"-5",store:[[OpenLayers.TimeUnit.SECONDS,"Seconds"], [OpenLayers.TimeUnit.MINUTES,"Minutes"],[OpenLayers.TimeUnit.HOURS,"Hours"],[OpenLayers.TimeUnit.DAYS,"Days"],[OpenLayers.TimeUnit.MONTHS,"Months"],[OpenLayers.TimeUnit.YEARS,"Years"]],valueNotFoundText:this.noUnitsText,mode:"local",forceSelection:!0,autoSelect:!1,editable:!1,triggerAction:"all",listeners:{select:this.setUnits,scope:this},ref:"../../stepUnitsField"},{fieldLabel:this.rangedPlayChoiceText,xtype:"gxp_playbackmodecombo",agents:this.timeManager&&this.timeManager.agents,anchor:"-5",listeners:{modechange:this.setPlaybackMode, scope:this},ref:"../../playbackModeField"}]},{xtype:"checkbox",boxLabel:this.loopText,handler:this.setLoopMode,scope:this,ref:"../loopModeCheck"},{xtype:"checkbox",boxLabel:this.reverseText,handler:this.setReverseMode,scope:this,ref:"../reverseModeCheck"}]}],bbar:[{text:"Save",ref:"../saveBtn",hidden:this.readOnly,handler:function(){this.fireEvent("save",this)},scope:this}]});Ext.apply(this,a);this.on("show",this.populateForm,this);gxp.PlaybackOptionsPanel.superclass.initComponent.call(this)},destroy:function(){this.playbackToolbar= this.timeManager=null;this.un("show",this,this.populateForm);gxp.PlaybackOptionsPanel.superclass.destroy.call(this)},setStartTime:function(a,b){this.timeManager.setAnimationStart(b.getTime());this.timeManager.fixedRange=!0},setEndTime:function(a,b){this.timeManager.setAnimationEnd(b.getTime());this.timeManager.fixedRange=!0},toggleListMode:function(a,b){this.stepValueField.setDisabled(b);this.stepUnitsField.setDisabled(b);this.timeManager.snapToList=b},setUnits:function(a,b,c){b=b.get("field1");this.timeManager.timeUnits!= b&&(this.timeManager.timeUnits=b,this.timeManager.step=a.refOwner.stepValueField.value*OpenLayers.TimeStep[b],"track"!=this.playbackToolbar.playbackMode&&this.timeManager.incrementValue())},setStep:function(a,b,c){a.validate()&&b&&(this.timeManager.step=b*OpenLayers.TimeStep[this.timeManager.timeUnits],this.timeManager.timeStep=b,"ranged"==this.playbackToolbar.playbackMode&&this.timeManager.rangeInterval!=b&&(this.timeManager.rangeInterval=b,this.timeManager.incrementTimeValue(b)))},setPlaybackMode:function(a, b,c){var d=a.startValue;Ext.each(c,function(a){a.tickMode==d&&(a.tickMode=b)});this.disableListMode("ranged"==b);this.playbackToolbar.setPlaybackMode(b)},disableListMode:function(a){(a=!1!==a)&&this.listOnlyCheck.setValue(!a);this.listOnlyCheck.setDisabled(a)},setLoopMode:function(a,b){this.timeManager.loop=b},setReverseMode:function(a,b){this.timeManager.step*=-1},populateForm:function(a){this.readOnly?this.saveBtn.hide():this.saveBtn.show();this.doLayout();if(this.timeManager){a=new Date(this.timeManager.animationRange[0]); var b=new Date(this.timeManager.animationRange[1]),c=this.timeManager.timeStep,d=this.timeManager.timeUnit,e=this.timeManager.snapToList,f=this.playbackToolbar?this.playbackToolbar.playbackMode:this.timeManager.agents[0].tickMode,g=this.timeManager.loop,h=0>this.timeManager.step;this.rangeStartField.setValue(a);this.rangeStartField.originalValue=a;this.rangeEndField.setValue(b);this.rangeEndField.originalValue=b;this.stepValueField.originalValue=this.stepValueField.setValue(c);this.stepUnitsField.originalValue= this.stepUnitsField.setValue(d);this.listOnlyCheck.setValue(e);this.listOnlyCheck.originalValue=e;this.playbackModeField.agents&&this.playbackModeField.agents.length||(this.playbackModeField.agents=this.timeManager.agents);this.playbackModeField.setValue(f);this.playbackModeField.originalValue=f;this.loopModeCheck.setValue(g);this.loopModeCheck.originalValue=g;this.reverseModeCheck.setValue(h);this.reverseModeCheck.originalValue=h}},close:function(a){if(this.ownerCt&&this.ownerCt.close)this.ownerCt[this.ownerCt.closeAction]()}}); Ext.reg("gxp_playbackoptions",gxp.PlaybackOptionsPanel);Ext.namespace("gxp"); gxp.GoogleEarthPanel=Ext.extend(Ext.Panel,{HORIZONTAL_FIELD_OF_VIEW:30*Math.PI/180,map:null,mapPanel:null,layers:null,earth:null,projection:null,layerCache:null,initComponent:function(){this.addEvents("beforeadd","pluginfailure","pluginready");gxp.GoogleEarthPanel.superclass.initComponent.call(this);var a=this.mapPanel;!a||a instanceof GeoExt.MapPanel||(a=Ext.getCmp(a));if(!a)throw Error("Could not get map panel from config: "+this.mapPanel);this.map=a.map;this.layers=a.layers;this.projection=new OpenLayers.Projection("EPSG:4326"); this.on("render",this.onRenderEvent,this);this.on("show",this.onShowEvent,this);this.on("hide",function(){null!=this.earth&&this.updateMap();this.body.dom.innerHTML="";this.earth=null},this)},onEarthReady:function(a){this.earth=a;void 0===this.flyToSpeed?this.earth.getOptions().setFlyToSpeed(this.earth.SPEED_TELEPORT):null!==this.flyToSpeed&&this.earth.getOptions().setFlyToSpeed(this.flyToSpeed);this.resetCamera();this.setExtent(this.map.getExtent());this.earth.getNavigationControl().setVisibility(this.earth.VISIBILITY_SHOW); a=this.earth.getNavigationControl().getScreenXY();a.setXUnits(this.earth.UNITS_PIXELS);a.setYUnits(this.earth.UNITS_INSET_PIXELS);this.earth.getWindow().setVisibility(!0);this.layers.each(function(a){this.addLayer(a)},this);this.layers.on("remove",this.updateLayers,this);this.layers.on("update",this.updateLayers,this);this.layers.on("add",this.updateLayers,this);this.fireEvent("pluginready",this.earth)},onRenderEvent:function(){var a=this.ownerCt&&this.ownerCt.layout instanceof Ext.layout.CardLayout; if(!this.hidden&&!a)this.onShowEvent()},onShowEvent:function(){this.rendered&&(this.layerCache={},google.earth.createInstance(this.body.dom,this.onEarthReady.createDelegate(this),function(a){this.fireEvent("pluginfailure",this,a)}.createDelegate(this)))},beforeDestroy:function(){this.layers.un("remove",this.updateLayers,this);this.layers.un("update",this.updateLayers,this);this.layers.un("add",this.updateLayers,this);gxp.GoogleEarthPanel.superclass.beforeDestroy.call(this)},updateLayers:function(){if(this.earth){for(var a= this.earth.getFeatures(),b=a.getFirstChild();null!=b;)a.removeChild(b),b=a.getFirstChild();this.layers.each(function(a){this.addLayer(a)},this)}},addLayer:function(a,b){var c=a.getLayer(),d=c&&c.url;if(this.earth&&c instanceof OpenLayers.Layer.WMS&&"string"==typeof d&&!1!==this.fireEvent("beforeadd",a)){var e=c.id;if(this.layerCache[e])d=this.layerCache[e];else{var f=this.earth.createLink("kl_"+e),d=d.replace(/\?.*/,""),g=c.params;f.setHref(d+("/kml?mode=refresh&layers="+g.LAYERS+"&styles="+g.STYLES)); d=this.earth.createNetworkLink("nl_"+e);d.setName(e);d.set(f,!1,!1);this.layerCache[e]=d}d.setVisibility(c.getVisibility());void 0!==b&&b<this.earth.getFeatures().getChildNodes().getLength()?this.earth.getFeatures().insertBefore(this.earth.getFeatures().getChildNodes().item(b)):this.earth.getFeatures().appendChild(d)}},setExtent:function(a){a=a.transform(this.map.getProjectionObject(),this.projection);var b=a.getCenterLonLat();a=this.getExtentWidth(a)/(2*Math.tan(this.HORIZONTAL_FIELD_OF_VIEW));var c= this.earth.getView().copyAsLookAt(this.earth.ALTITUDE_RELATIVE_TO_GROUND);c.setLatitude(b.lat);c.setLongitude(b.lon);c.setRange(a);this.earth.getView().setAbstractView(c)},resetCamera:function(){var a=this.earth.getView().copyAsCamera(this.earth.ALTITUDE_RELATIVE_TO_GROUND);a.setRoll(0);a.setHeading(0);a.setTilt(0);this.earth.getView().setAbstractView(a)},getExtent:function(){var a=this.earth.getView().getViewportGlobeBounds();return new OpenLayers.Bounds(a.getWest(),a.getSouth(),a.getEast(),a.getNorth())}, updateMap:function(){var a=this.earth.getView().copyAsLookAt(this.earth.ALTITUDE_RELATIVE_TO_GROUND),b=this.reprojectToMap(new OpenLayers.LonLat(a.getLongitude(),a.getLatitude())),c=this.reprojectToMap(this.getExtent());this.map.zoomToExtent(c,!0);this.map.setCenter(b);var a=2*a.getRange()*Math.tan(this.HORIZONTAL_FIELD_OF_VIEW),d=this.map.getResolutionForZoom(this.map.getZoom()+1),c=this.map.getExtent(),b=new OpenLayers.Bounds(b.lon-this.map.getSize().w/2*d,b.lat+this.map.getSize().h/2*d,b.lon+this.map.getSize().w/ 2*d,b.lat-this.map.getSize().h/2*d),c=Math.abs(this.getExtentWidth(c)-a);Math.abs(this.getExtentWidth(b)-a)<c&&this.map.zoomTo(this.map.getZoom()+1)},getExtentWidth:function(a){var b=a.getCenterLonLat(),c=new OpenLayers.LonLat(a.left,b.lat);a=new OpenLayers.LonLat(a.right,b.lat);return 1E3*OpenLayers.Util.distVincenty(c,a)},reprojectToGE:function(a){return a.clone().transform(this.map.getProjectionObject(),this.projection)},reprojectToMap:function(a){return a.clone().transform(this.projection,this.map.getProjectionObject())}}); Ext.reg("gxp_googleearthpanel",gxp.GoogleEarthPanel);Ext.namespace("gxp.plugins"); gxp.plugins.QueryForm=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_queryform",featureManager:null,autoHide:!1,schema:null,queryActionText:"Query",cancelButtonText:"Cancel",queryMenuText:"Query layer",queryActionTip:"Query the selected layer",queryByLocationText:"Query by current map extent",queryByAttributesText:"Query by attributes",queryMsg:"Querying...",noFeaturesTitle:"No Match",noFeaturesMessage:"Your query did not return any results.",outputAction:0,autoExpand:null,addActions:function(a){this.initialConfig.actions|| a||(a=[{text:this.queryActionText,menuText:this.queryMenuText,iconCls:"gxp-icon-find",tooltip:this.queryActionTip,disabled:!0,toggleGroup:this.toggleGroup,enableToggle:!0,allowDepress:!0,toggleHandler:function(a,c){if(this.autoExpand&&0<this.output.length){var d=Ext.getCmp(this.autoExpand);d[c?"expand":"collapse"]();c?(d.expand(),d.ownerCt&&d.ownerCt instanceof Ext.Panel&&d.ownerCt.expand()):this.target.tools[this.featureManager].loadFeatures()}},scope:this}]);this.actions=gxp.plugins.QueryForm.superclass.addActions.apply(this, a);if(null!==this.actionTarget&&this.actions)this.target.tools[this.featureManager].on("layerchange",function(a,c,d){for(a=this.actions.length-1;0<=a;--a)this.actions[a].setDisabled(!d)},this)},addOutput:function(a){var b=this.target.tools[this.featureManager];a=Ext.apply({border:!1,bodyStyle:"padding: 10px",layout:"form",width:320,autoScroll:!0,items:[{xtype:"fieldset",ref:"spatialFieldset",title:this.queryByLocationText,anchor:"97%",style:"margin-bottom:0; border-left-color:transparent; border-right-color:transparent; border-width:1px 1px 0 1px; padding-bottom:0", checkboxToggle:!0},{xtype:"fieldset",ref:"attributeFieldset",title:this.queryByAttributesText,anchor:"97%",style:"margin-bottom:0",checkboxToggle:!0}],bbar:["->",{text:this.cancelButtonText,iconCls:"cancel",handler:function(){var a=this.outputTarget?c.ownerCt:c.ownerCt.ownerCt;a&&a instanceof Ext.Window&&a.hide();g(b,b.layerRecord,b.schema);b.loadFeatures()}},{text:this.queryActionText,iconCls:"gxp-icon-find",handler:function(){var a=[];!0!==c.spatialFieldset.collapsed&&a.push(new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.BBOX, property:b.featureStore.geometryName,value:this.target.mapPanel.map.getExtent()}));if(!0!==c.attributeFieldset.collapsed){var d=c.filterBuilder.getFilter();d&&a.push(d)}b.loadFeatures(1<a.length?new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.AND,filters:a}):a[0])},scope:this}]},a||{});var c=gxp.plugins.QueryForm.superclass.addOutput.call(this,a),d=null,e=!0;if(this.autoExpand){var f=function(){e&&(d.un("expand",f),d.un("collapse",f),d=null);e=!0},d=Ext.getCmp(this.autoExpand);d.on({expand:f, collapse:f})}var g=function(a,b,f){c.attributeFieldset.removeAll();c.setDisabled(!f);d&&(e=!1,d[f?"expand":"collapse"](),f&&d&&d.ownerCt&&d.ownerCt instanceof Ext.Panel&&d.ownerCt.expand());f?(c.attributeFieldset.add({xtype:"gxp_filterbuilder",ref:"../filterBuilder",attributes:f,allowBlank:!0,allowGroups:!1}),c.spatialFieldset.expand(),c.attributeFieldset.expand()):(c.attributeFieldset.rendered&&c.attributeFieldset.collapse(),c.spatialFieldset.rendered&&c.spatialFieldset.collapse());c.attributeFieldset.doLayout()}; b.on("layerchange",g);g(b,b.layerRecord,b.schema);b.on({beforequery:function(){(new Ext.LoadMask(c.getEl(),{store:b.featureStore,msg:this.queryMsg})).show()},query:function(a,b){if(b&&null!==this.target.tools[this.featureManager].featureStore&&(b.getCount()||Ext.Msg.show({title:this.noFeaturesTitle,msg:this.noFeaturesMessage,buttons:Ext.Msg.OK,icon:Ext.Msg.INFO}),this.autoHide)){var d=this.outputTarget?c.ownerCt:c.ownerCt.ownerCt;d instanceof Ext.Window&&d.hide()}},scope:this});return c}}); Ext.preg(gxp.plugins.QueryForm.prototype.ptype,gxp.plugins.QueryForm);Ext.namespace("gxp");gxp.LineSymbolizer=Ext.extend(Ext.Panel,{symbolizer:null,initComponent:function(){this.items=[{xtype:"gxp_strokesymbolizer",symbolizer:this.symbolizer,listeners:{change:function(a){this.fireEvent("change",this.symbolizer)},scope:this}}];this.addEvents("change");gxp.LineSymbolizer.superclass.initComponent.call(this)}});Ext.reg("gxp_linesymbolizer",gxp.LineSymbolizer);Ext.namespace("gxp.plugins"); gxp.plugins.WizardStep=Ext.extend(gxp.plugins.Tool,{autoActivate:!1,index:null,valid:!1,wizardContainer:null,wizardData:null,constructor:function(a){gxp.plugins.WizardStep.superclass.constructor.apply(this,arguments);this.wizardData={}},addOutput:function(a){a=Ext.ComponentMgr.create(Ext.apply(a,this.outputConfig));a.on("added",function(a,c){this.wizardContainer=c.ownerCt;this.index=c.ownerCt.items.indexOf(c);c.setDisabled(0!=this.index);c.ownerCt.on({wizardstepvalid:function(a,b){Ext.apply(this.wizardData, b);this.previousStepsCompleted()&&c.enable()},wizardstepinvalid:function(a){this.previousStepsCompleted()||c.disable()},scope:this});c.on({expand:this.activate,collapse:this.deactivate,scope:this})},this);return gxp.plugins.WizardStep.superclass.addOutput.call(this,a)},setValid:function(a,b){(this.valid=a)?this.wizardContainer.fireEvent("wizardstepvalid",this,b):this.wizardContainer.fireEvent("wizardstepinvalid",this)},previousStepsCompleted:function(){var a=this.index,b=!0;if(0<a){var c,d;for(d in this.target.tools)c= this.target.tools[d],c instanceof gxp.plugins.WizardStep&&c.index<a&&(b=b&&c.valid)}return b}});Ext.namespace("gxp.plugins"); gxp.plugins.Navigation=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_navigation",menuText:"Pan Map",tooltip:"Pan Map",constructor:function(a){gxp.plugins.Navigation.superclass.constructor.apply(this,arguments)},addActions:function(){var a;this.controlOptions?(this.controlOptions=this.controlOptions||{},Ext.applyIf(this.controlOptions,{dragPanOptions:{enableKinetic:!0}}),a=new OpenLayers.Control.Navigation(this.controlOptions)):(candidates=this.target.mapPanel.map.getControlsByClass("OpenLayers.Control.Navigation"), candidates.length&&(a=candidates[0]));a=[new GeoExt.Action({tooltip:this.tooltip,menuText:this.menuText,iconCls:"gxp-icon-pan",enableToggle:!0,pressed:!0,allowDepress:!1,control:a,map:a.map?null:this.target.mapPanel.map,toggleGroup:this.toggleGroup})];return gxp.plugins.Navigation.superclass.addActions.apply(this,[a])}});Ext.preg(gxp.plugins.Navigation.prototype.ptype,gxp.plugins.Navigation);Ext.namespace("gxp.plugins"); gxp.plugins.DeleteSelectedFeatures=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_deleteselectedfeatures",deleteMsgTitle:"Delete",deleteFeaturesMsg:"Are you sure you want to delete {0} selected features?",deleteFeatureMsg:"Are you sure you want to delete the selected feature?",menuText:"Delete selected features",tooltip:"Delete the currently selected features",iconCls:"delete",addActions:function(){var a=gxp.plugins.DeleteSelectedFeatures.superclass.addActions.apply(this,[{text:this.buttonText,menuText:this.menuText, iconCls:this.iconCls,tooltip:this.tooltip,handler:this.deleteFeatures,scope:this}]);a[0].disable();var b=this.target.tools[this.featureManager].featureLayer;b.events.on({featureselected:function(){a[0].isDisabled()&&a[0].enable()},featureunselected:function(){0==b.selectedFeatures.length&&a[0].disable()}});return a},deleteFeatures:function(){var a=this.target.tools[this.featureManager],b=a.featureLayer.selectedFeatures;Ext.Msg.show({title:this.deleteMsgTitle,msg:1<b.length?String.format(this.deleteFeaturesMsg, b.length):this.deleteFeatureMsg,buttons:Ext.Msg.YESNO,fn:function(c){if("yes"===c){c=a.featureStore;for(var d,e=b.length-1;0<=e;--e)d=b[e],d.layer.selectedFeatures.remove(d),d.layer.events.triggerEvent("featureunselected",{feature:d}),d.state!==OpenLayers.State.INSERT&&(d.state=OpenLayers.State.DELETE,c._removing=!0),c.remove(c.getRecordFromFeature(d)),delete c._removing;c.save()}},scope:this,icon:Ext.MessageBox.QUESTION})}});Ext.preg(gxp.plugins.DeleteSelectedFeatures.prototype.ptype,gxp.plugins.DeleteSelectedFeatures); Ext.namespace("gxp.menu"); gxp.menu.TimelineMenu=Ext.extend(Ext.menu.Menu,{filterLabel:"Filter",attributeLabel:"Label",showNotesText:"Show notes",layers:null,subMenuSize:[350,60],initComponent:function(){gxp.menu.TimelineMenu.superclass.initComponent.apply(this,arguments);this.timelinePanel=this.timelineTool&&this.timelineTool.getTimelinePanel();this.layers.on("add",this.onLayerAddOrRemove,this);this.layers.on("remove",this.onLayerAddOrRemove,this);this.onLayerAddOrRemove()},onRender:function(a,b){gxp.menu.TimelineMenu.superclass.onRender.apply(this,arguments)}, beforeDestroy:function(){this.layers&&this.layers.on&&(this.layers.un("add",this.onLayerAddOrRemove,this),this.layers.un("remove",this.onLayerAddOrRemove,this));delete this.layers;gxp.menu.TimelineMenu.superclass.beforeDestroy.apply(this,arguments)},onLayerAddOrRemove:function(){this.removeAll();if(this.timelinePanel.annotationsRecord){var a=this.timelinePanel.annotationsRecord,b=this.timelinePanel.getKey(a);this.add(new Ext.menu.CheckItem({text:this.showNotesText,checked:this.timelinePanel.layerLookup[b]&& this.timelinePanel.layerLookup[b].visible||!0,listeners:{checkchange:function(b,d){this.timelinePanel.setLayerVisibility(b,d,a,!1)},scope:this}}))}this.layers.each(function(a){var b=a.getLayer();if(b.displayInLayerSwitcher&&b.dimensions&&b.dimensions.time){var b=this.timelinePanel.getKey(a),e=this.timelinePanel.schemaCache[b],b=new Ext.menu.CheckItem({text:a.get("title"),checked:this.timelinePanel.layerLookup[b]&&this.timelinePanel.layerLookup[b].visible||!1,menu:new Ext.menu.Menu({plain:!0,style:{overflow:"visible"}, showSeparator:!1,items:[{xtype:"container",width:this.subMenuSize[0],height:this.subMenuSize[1],layout:"vbox",defaults:{border:!1},layoutConfig:{align:"stretch",pack:"start"},items:[{xtype:"form",labelWidth:75,height:30,items:[{xtype:"combo",forceSelection:!0,getListParent:function(){return this.el.up(".x-menu")},store:e,mode:"local",triggerAction:"all",value:this.timelinePanel.layerLookup[b]?this.timelinePanel.layerLookup[b].titleAttr:null,listeners:{select:function(b){this.timelinePanel.setTitleAttribute(a, b.getValue())},scope:this},displayField:"name",valueField:"name",fieldLabel:this.attributeLabel}]},{xtype:"container",layout:"hbox",id:"gxp_timemenufilter",layoutConfig:{align:"stretch",pack:"start"},defaults:{border:!1},items:[{width:25,xtype:"form",layout:"fit",items:[{xtype:"checkbox",checked:this.timelinePanel.layerLookup[b]&&void 0!==this.timelinePanel.layerLookup[b].clientSideFilter,ref:"../applyFilter",listeners:{check:function(b,d){var e=Ext.getCmp("gxp_timemenufilter").filter;e.isValid()&& this.timelinePanel.applyFilter(a,e.filter,d)},scope:this}}]},{flex:1,xtype:"form",labelWidth:75,items:[{xtype:"gxp_filterfield",ref:"../filter",filter:this.timelinePanel.layerLookup[b]?this.timelinePanel.layerLookup[b].clientSideFilter:null,listeners:{change:function(b,d){d.isValid()&&this.timelinePanel.applyFilter(a,b,Ext.getCmp("gxp_timemenufilter").applyFilter.getValue())},scope:this},attributesComboConfig:{getListParent:function(){return this.el.up(".x-menu")}},comparisonComboConfig:{getListParent:function(){return this.el.up(".x-menu")}}, fieldLabel:this.filterLabel,attributes:e}]}],height:30}]}]}),listeners:{checkchange:function(b,d){this.timelinePanel.setLayerVisibility(b,d,a)},scope:this}});this.add(b)}},this)}});Ext.reg("gxp_timelinemenu",gxp.menu.TimelineMenu);Ext.namespace("gxp.plugins"); gxp.plugins.Playback=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_playback",autoStart:!1,looped:!1,playbackMode:"track",menuText:"Time Playback",tooltip:"Show Time Playback Panel",actionTarget:null,outputTarget:"map",constructor:function(a){gxp.plugins.Playback.superclass.constructor.apply(this,arguments)},init:function(a){a.on("saved",function(){this.output&&(this.output[0].optionsWindow.optionsPanel.readOnly=!1)},this,{single:!0});gxp.plugins.Playback.superclass.init.call(this,a)},addOutput:function(a){delete this._ready; OpenLayers.Control.DimensionManager.prototype.maxFrameDelay=this.target.tests&&this.target.tests.dropFrames?10:NaN;a=Ext.applyIf(a||this.outputConfig||{},{xtype:"gxp_playbacktoolbar",mapPanel:this.target.mapPanel,playbackMode:this.playbackMode,prebuffer:this.target.prebuffer,maxframes:this.target.maxframes,looped:this.looped,autoPlay:this.autoStart,optionsWindow:new Ext.Window({title:gxp.PlaybackOptionsPanel.prototype.titleText,width:350,height:400,layout:"fit",items:[{xtype:"gxp_playbackoptions", readOnly:!this.target.isAuthorized()||!(this.target.id||this.target.mapID),listeners:{save:function(a){this.target.on("saved",function(){a.ownerCt.close()},this,{single:!0});this.target.save()},scope:this}}],closeable:!0,closeAction:"hide",renderTo:Ext.getBody(),listeners:{show:function(a){a=a.findByType("gxp_playbackoptions")[0];a.fireEvent("show",a)},hide:function(a){a=a.findByType("gxp_playbackoptions")[0];a.fireEvent("hide",a)}}})});a=gxp.plugins.Playback.superclass.addOutput.call(this,a);this.relayEvents(a, ["timechange","rangemodified"]);this.playbackToolbar=a;a.control.layers&&this.fireEvent("rangemodified",this,a.control.range);return a},addActions:function(a){this._ready=0;this.target.mapPanel.map.events.register("addlayer",this,function(a){var c=a.layer;c instanceof OpenLayers.Layer.WMS&&c.dimensions&&c.dimensions.time&&(this.target.mapPanel.map.events.unregister("addlayer",this,arguments.callee),this._ready+=1,1<this._ready&&this.addOutput())});this.target.on("ready",function(){this._ready+=1; 1<this._ready&&this.addOutput()},this)},setTime:function(a){return this.playbackToolbar.setTime(a)},getState:function(){var a=gxp.plugins.Playback.superclass.getState.call(this),b=this.playbackToolbar;if(b){var c=b.control;a.outputConfig=Ext.apply(b.initialConfig,{dynamicRange:b.dyanamicRange,playbackMode:b.playbackMode});if(c&&(b=c.modelCache||c.model,a.outputConfig.controlConfig={model:{dimension:b.dimension||c.dimension,values:b.values,range:b.range},animationRange:c.animationRange,timeStep:c.timeStep, timeUnits:c.timeUnits?c.timeUnits:void 0,loop:c.loop,snapToList:c.snapToList,dimension:b.dimension||c.dimension},1<c.agents.length)){for(var c=c.agents,b=[],d=0;d<c.length;d++){for(var e={type:c[d].CLASS_NAME.split("Agent.")[1],tickMode:c[d].tickMode,rangeInterval:c[d].rangeInterval,values:c[d].values,layers:[]},f=0;f<c[d].layers.length;f++){var g=this.target.mapPanel.layers.getByLayer(c[d].layers[f]),g=this.target.layerSources[g.get("source")].getConfigForRecord(g);e.layers.push({source:g.source, title:g.title,name:g.name,styles:g.styles?g.styles:void 0})}b.push(e)}a.outputConfig.controlConfig.agents=b}delete a.outputConfig.mapPanel;delete a.outputConfig.optionsWindow}return a}});Ext.preg(gxp.plugins.Playback.prototype.ptype,gxp.plugins.Playback);Ext.namespace("gxp.plugins"); gxp.plugins.ZoomToLayerExtent=Ext.extend(gxp.plugins.ZoomToExtent,{ptype:"gxp_zoomtolayerextent",menuText:"Zoom to layer extent",tooltip:"Zoom to layer extent",iconCls:"gxp-icon-zoom-to",destroy:function(){this.selectedRecord=null;gxp.plugins.ZoomToLayerExtent.superclass.destroy.apply(this,arguments)},extent:function(){var a=this.selectedRecord.getLayer(),b;OpenLayers.Layer.Vector&&(b=a instanceof OpenLayers.Layer.Vector&&a.getDataExtent());return a.restrictedExtent||b||a.maxExtent||map.maxExtent}, addActions:function(){var a=gxp.plugins.ZoomToLayerExtent.superclass.addActions.apply(this,arguments);a[0].disable();this.target.on("layerselectionchange",function(b){this.selectedRecord=b;a[0].setDisabled(!b||!b.get("layer"))},this);return a}});Ext.preg(gxp.plugins.ZoomToLayerExtent.prototype.ptype,gxp.plugins.ZoomToLayerExtent);Ext.namespace("gxp.plugins"); gxp.plugins.BingSource=Ext.extend(gxp.plugins.LayerSource,{ptype:"gxp_bingsource",title:"Bing Layers",roadTitle:"Bing Roads",aerialTitle:"Bing Aerial",labeledAerialTitle:"Bing Aerial With Labels",apiKey:"AqTGBsziZHIJYYxgivLBf0hVdrAk9mWO5cQcb8Yux8sW5M8c8opEC2lZqKR1ZZXf",createStore:function(){var a=[new OpenLayers.Layer.Bing({key:this.apiKey,name:this.roadTitle,type:"Road",buffer:1,transitionEffect:"resize"}),new OpenLayers.Layer.Bing({key:this.apiKey,name:this.aerialTitle,type:"Aerial",buffer:1,transitionEffect:"resize"}), new OpenLayers.Layer.Bing({key:this.apiKey,name:this.labeledAerialTitle,type:"AerialWithLabels",buffer:1,transitionEffect:"resize"})];this.store=new GeoExt.data.LayerStore({layers:a,fields:[{name:"source",type:"string"},{name:"name",type:"string",mapping:"type"},{name:"abstract",type:"string",mapping:"attribution"},{name:"group",type:"string",defaultValue:"background"},{name:"fixed",type:"boolean",defaultValue:!0},{name:"selected",type:"boolean"}]});this.store.each(function(a){a.set("group","background")}); this.fireEvent("ready",this)},createLayerRecord:function(a){var b,c=this.store.findExact("name",a.name);-1<c&&(b=this.store.getAt(c).copy(Ext.data.Record.id({})),c=b.getLayer().clone(),a.title&&(c.setName(a.title),b.set("title",a.title)),"visibility"in a&&(c.visibility=a.visibility),b.set("selected",a.selected||!1),b.set("source",a.source),b.set("name",a.name),"group"in a&&b.set("group",a.group),b.data.layer=c,b.commit());return b}});Ext.preg(gxp.plugins.BingSource.prototype.ptype,gxp.plugins.BingSource); Ext.namespace("gxp.plugins"); gxp.plugins.FeatureToField=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_featuretofield",format:"GeoJSON",addActions:function(){var a=this.target.tools[this.featureManager],b,c=new OpenLayers.Format[this.format];a.featureLayer.events.on({featureselected:function(a){this.target.field.setValue(c.write(a.feature));b=a.feature},featureunselected:function(){this.target.field.setValue("");b=null},scope:this});a.on("layerchange",function(){a.featureStore&&a.featureStore.on("save",function(a,e,f){if(f.create)for(a= f.create.length-1;0<=a;--a)e=f.create[a].feature,e==b&&this.target.field.setValue(c.write(e))},this)});return gxp.plugins.FeatureToField.superclass.addActions.apply(this,arguments)}});Ext.preg(gxp.plugins.FeatureToField.prototype.ptype,gxp.plugins.FeatureToField);Ext.namespace("gxp"); gxp.FeatureEditPopup=Ext.extend(GeoExt.Popup,{closeMsgTitle:"Save Changes?",closeMsg:"This feature has unsaved changes. Would you like to save your changes?",deleteMsgTitle:"Delete Feature?",deleteMsg:"Are you sure you want to delete this feature?",editButtonText:"Edit",editButtonTooltip:"Make this feature editable",deleteButtonText:"Delete",deleteButtonTooltip:"Delete this feature",cancelButtonText:"Cancel",cancelButtonTooltip:"Stop editing, discard changes",saveButtonText:"Save",saveButtonTooltip:"Save changes", layout:"fit",feature:null,schema:null,readOnly:!1,allowDelete:!1,editing:!1,editorPluginConfig:{ptype:"gxp_editorgrid"},modifyControl:null,geometry:null,attributes:null,cancelButton:null,saveButton:null,editButton:null,deleteButton:null,initComponent:function(){this.addEvents("startedit","stopedit","beforefeaturemodified","featuremodified","canceledit","cancelclose");var a=this.feature;a instanceof GeoExt.data.FeatureRecord&&(a=this.feature=a.getFeature());this.location||(this.location=a);this.anchored= !this.editing;!this.title&&a.fid&&(this.title=a.fid);this.editButton=new Ext.Button({text:this.editButtonText,tooltip:this.editButtonTooltip,iconCls:"edit",handler:this.startEditing,scope:this});this.deleteButton=new Ext.Button({text:this.deleteButtonText,tooltip:this.deleteButtonTooltip,iconCls:"delete",hidden:!this.allowDelete,handler:this.deleteFeature,scope:this});this.cancelButton=new Ext.Button({text:this.cancelButtonText,tooltip:this.cancelButtonTooltip,iconCls:"cancel",hidden:!0,handler:function(){this.stopEditing(!1)}, scope:this});this.saveButton=new Ext.Button({text:this.saveButtonText,tooltip:this.saveButtonTooltip,iconCls:"save",hidden:!0,handler:function(){this.stopEditing(!0)},scope:this});this.plugins=[Ext.apply({feature:a,schema:this.schema,fields:this.fields,excludeFields:this.excludeFields,propertyNames:this.propertyNames,readOnly:this.readOnly},this.editorPluginConfig)];this.bbar=new Ext.Toolbar({hidden:this.readOnly,items:[this.editButton,this.deleteButton,this.saveButton,this.cancelButton]});gxp.FeatureEditPopup.superclass.initComponent.call(this); this.on({show:function(){this.editing&&(this.editing=null,this.startEditing())},beforeclose:function(){if(this.editing){if(this.feature.state===this.getDirtyState())return Ext.Msg.show({title:this.closeMsgTitle,msg:this.closeMsg,buttons:Ext.Msg.YESNOCANCEL,fn:function(a){a&&"cancel"!==a?(this.stopEditing("yes"===a),this.close()):this.fireEvent("cancelclose",this)},scope:this,icon:Ext.MessageBox.QUESTION,animEl:this.getEl()}),!1;this.stopEditing(!1)}},scope:this})},getDirtyState:function(){return this.feature.state=== OpenLayers.State.INSERT?this.feature.state:OpenLayers.State.UPDATE},startEditing:function(){this.editing||(this.fireEvent("startedit",this),this.editing=!0,this.anc&&this.unanchorPopup(),this.editButton.hide(),this.deleteButton.hide(),this.saveButton.show(),this.cancelButton.show(),this.geometry=this.feature.geometry&&this.feature.geometry.clone(),this.attributes=Ext.apply({},this.feature.attributes),this.modifyControl=new OpenLayers.Control.ModifyFeature(this.feature.layer,{standalone:!0,vertexRenderIntent:this.vertexRenderIntent}), this.feature.layer.map.addControl(this.modifyControl),this.modifyControl.activate(),this.feature.geometry&&this.modifyControl.selectFeature(this.feature))},stopEditing:function(a){if(this.editing){this.fireEvent("stopedit",this);this.modifyControl.deactivate();this.modifyControl.destroy();var b=this.feature;if(b.state===this.getDirtyState())if(!0===a){this.fireEvent("beforefeaturemodified",this,b);if(this.schema){var c,d;for(d in b.attributes)c=this.schema.getAt(this.schema.findExact("name",d)),a= b.attributes[d],a instanceof Date&&(c=c.get("type").split(":").pop(),b.attributes[d]=a.format("date"==c?"Y-m-d":"c"))}this.fireEvent("featuremodified",this,b)}else b.state===OpenLayers.State.INSERT?(this.editing=!1,b.layer&&b.layer.destroyFeatures([b]),this.fireEvent("canceledit",this,null),this.close()):(d=b.layer,d.drawFeature(b,{display:"none"}),b.geometry=this.geometry,b.attributes=this.attributes,this.setFeatureState(null),d.drawFeature(b),this.fireEvent("canceledit",this,b));this.isDestroyed|| (this.cancelButton.hide(),this.saveButton.hide(),this.editButton.show(),this.allowDelete&&this.deleteButton.show());this.editing=!1}},deleteFeature:function(){Ext.Msg.show({title:this.deleteMsgTitle,msg:this.deleteMsg,buttons:Ext.Msg.YESNO,fn:function(a){"yes"===a&&(this.setFeatureState(OpenLayers.State.DELETE),this.fireEvent("featuremodified",this,this.feature),this.close())},scope:this,icon:Ext.MessageBox.QUESTION,animEl:this.getEl()})},setFeatureState:function(a){this.feature.state=a;(a=this.feature.layer)&& a.events.triggerEvent("featuremodified",{feature:this.feature})}});Ext.reg("gxp_featureeditpopup",gxp.FeatureEditPopup);Ext.namespace("gxp.plugins"); gxp.plugins.FeatureEditor=Ext.extend(gxp.plugins.ClickableFeatures,{ptype:"gxp_featureeditor",commitMessage:!1,splitButton:null,iconClsAdd:"gxp-icon-addfeature",closeOnSave:!1,supportAbstractGeometry:!1,supportNoGeometry:!1,iconClsEdit:"gxp-icon-editfeature",exceptionTitle:"Save Failed",exceptionText:"Trouble saving features",pointText:"Point",lineText:"Line",polygonText:"Polygon",noGeometryText:"Event",commitTitle:"Commit message",commitText:"Please enter a commit message for this edit:",createFeatureActionTip:"Create a new feature", createFeatureActionText:"Create",editFeatureActionTip:"Edit existing feature",editFeatureActionText:"Modify",splitButtonText:"Edit",splitButtonTooltip:"Edit features on selected WMS layer",outputTarget:"map",snappingAgent:null,readOnly:!1,modifyOnly:!1,showSelectedOnly:!0,roles:["ROLE_ADMINISTRATOR"],createAction:null,editAction:null,activeIndex:0,drawControl:null,popup:null,schema:null,constructor:function(a){this.addEvents("layereditable","featureeditable");gxp.plugins.FeatureEditor.superclass.constructor.apply(this, arguments)},init:function(a){gxp.plugins.FeatureEditor.superclass.init.apply(this,arguments);this.target.on("authorizationchange",this.onAuthorizationChange,this)},destroy:function(){this.target.un("authorizationchange",this.onAuthorizationChange,this);gxp.plugins.FeatureEditor.superclass.destroy.apply(this,arguments)},onAuthorizationChange:function(){this.target.isAuthorized(this.roles)||(this.selectControl.deactivate(),this.drawControl.deactivate());this.enableOrDisable()},addActions:function(){function a(a, d){var f=Array.prototype.slice.call(arguments);f.splice(0,2);if(!e&&b&&!b.isDestroyed){if(b.editing){var g=function(){c.featureStore.un("write",h,this);b.un("canceledit",h,this);b.un("cancelclose",g,this)},h=function(){e=!0;g.call(this);"setLayer"===d?this.target.selectLayer(f[0]):"clearFeatures"===d?window.setTimeout(function(){a[d].call(a)}):a[d].apply(a,f)};c.featureStore.on("write",h,this);b.on({canceledit:h,cancelclose:g,scope:this});b.close()}return!b.editing}e=!1}var b,c=this.getFeatureManager(), d=c.featureLayer,e=!1;c.on({beforequery:a.createDelegate(this,"loadFeatures",1),beforelayerchange:a.createDelegate(this,"setLayer",1),beforesetpage:a.createDelegate(this,"setPage",1),beforeclearfeatures:a.createDelegate(this,"clearFeatures",1),scope:this});this.drawControl=new OpenLayers.Control.DrawFeature(d,OpenLayers.Handler.Point,{eventListeners:{featureadded:function(a){!0===this.autoLoadFeature&&(this.autoLoadedFeature=a.feature)},activate:function(){this.target.doAuthorized(this.roles,function(){c.showLayer(this.id, this.showSelectedOnly&&"selected")},this)},deactivate:function(){c.hideLayer(this.id)},scope:this}});this.selectControl=new OpenLayers.Control.SelectFeature(d,{clickout:!1,multipleKey:"fakeKey",eventListeners:{activate:function(){this.target.doAuthorized(this.roles,function(){(!0===this.autoLoadFeature||c.paging)&&this.target.mapPanel.map.events.register("click",this,this.noFeatureClick);c.showLayer(this.id,this.showSelectedOnly&&"selected");this.selectControl.unselectAll(b&&b.editing&&{except:b.feature})}, this)},deactivate:function(){(!0===this.autoLoadFeature||c.paging)&&this.target.mapPanel.map.events.unregister("click",this,this.noFeatureClick);if(b){if(b.editing)b.on("cancelclose",function(){this.selectControl.activate()},this,{single:!0});b.on("close",function(){c.hideLayer(this.id)},this,{single:!0});b.close()}else c.hideLayer(this.id)},scope:this}});d.events.on({beforefeatureremoved:function(a){this.popup&&a.feature===this.popup.feature&&this.selectControl.unselect(a.feature)},featureunselected:function(a){(a= a.feature)&&this.fireEvent("featureeditable",this,a,!1);a&&a.geometry&&b&&!b.hidden&&b.close()},beforefeatureselected:function(a){if(b)return!b.editing},featureselected:function(a){var d=a.feature;d&&this.fireEvent("featureeditable",this,d,!0);var e=c.featureStore;if(!0===this._forcePopupForNoGeometry||this.selectControl.active&&null!==d.geometry)!1===this.readOnly&&(this.selectControl.deactivate(),c.showLayer(this.id,this.showSelectedOnly&&"selected")),b=this.addOutput({xtype:"gxp_featureeditpopup", collapsible:!0,feature:e.getByFeature(d),vertexRenderIntent:"vertex",readOnly:this.readOnly,fields:this.fields,excludeFields:this.excludeFields,editing:d.state===OpenLayers.State.INSERT,schema:this.schema,allowDelete:!0,width:200,height:250}),b.on({close:function(){!1===this.readOnly&&this.selectControl.activate();d.layer&&-1!==d.layer.selectedFeatures.indexOf(d)&&this.selectControl.unselect(d);d===this.autoLoadedFeature&&(d.layer&&d.layer.removeFeatures([a.feature]),this.autoLoadedFeature=null)}, featuremodified:function(a,b){e.on({beforewrite:{fn:function(a,b,c,d){!0===this.commitMessage&&(d.params.handle=this._commitMsg,delete this._commitMsg)},single:!0},beforesave:{fn:function(){a&&a.isVisible()&&a.disable();if(!0===this.commitMessage&&!this._commitMsg){var b=arguments.callee;Ext.Msg.show({prompt:!0,title:this.commitTitle,msg:this.commitText,buttons:Ext.Msg.OK,fn:function(a,c){"ok"===a&&(this._commitMsg=c,e.un("beforesave",b,this),e.save())},scope:this,multiline:!0});return!1}},single:!0!== this.commitMessage},write:{fn:function(){a&&(a.isVisible()&&a.enable(),this.closeOnSave&&a.close());var b=c.layerRecord;this.target.fireEvent("featureedit",c,{name:b.get("name"),source:b.get("source")})},single:!0},exception:{fn:function(b,d,f,g,h,k){b=this.exceptionText;"remote"===d?h.exceptionReport&&(b=gxp.util.getOGCExceptionText(h.exceptionReport)):b="Status: "+h.status;c.fireEvent("exception",c,h.exceptionReport||{},b,k);!1===c.hasListener("exception")&&!1===e.hasListener("exception")&&Ext.Msg.show({title:this.exceptionTitle, msg:b,icon:Ext.MessageBox.ERROR,buttons:{ok:!0}});a&&a.isVisible()&&(a.enable(),a.startEditing())},single:!0},scope:this});b.state===OpenLayers.State.DELETE&&(e._removing=!0,e.remove(e.getRecordFromFeature(b)),delete e._removing);e.save()},canceledit:function(a,b){e.commitChanges()},scope:this}),this.popup=b},sketchcomplete:function(a){c.featureLayer.events.register("featuresadded",this,function(a){c.featureLayer.events.unregister("featuresadded",this,arguments.callee);this.drawControl.deactivate(); this.selectControl.activate();this.selectControl.select(a.features[0])})},scope:this});var f=this.toggleGroup||Ext.id(),g=[],h={tooltip:this.createFeatureActionTip,menuText:this.initialConfig.createFeatureActionText,text:this.initialConfig.createFeatureActionText,iconCls:this.iconClsAdd,disabled:!0,hidden:this.modifyOnly||this.readOnly,toggleGroup:f,group:f,groupClass:null,enableToggle:!0,allowDepress:!0,control:this.drawControl,deactivateOnDisable:!0,map:this.target.mapPanel.map,listeners:{checkchange:this.onItemCheckchange, scope:this}};if(!0===this.supportAbstractGeometry){var k=[];!0===this.supportNoGeometry&&k.push(new Ext.menu.CheckItem({text:this.noGeometryText,iconCls:"gxp-icon-event",groupClass:null,group:f,listeners:{checkchange:function(a,b){if(!0===b){var c=new OpenLayers.Feature.Vector(null);c.state=OpenLayers.State.INSERT;d.addFeatures([c]);this._forcePopupForNoGeometry=!0;d.events.triggerEvent("featureselected",{feature:c});delete this._forcePopupForNoGeometry}this.createAction.items[0]instanceof Ext.menu.CheckItem? this.createAction.items[0].setChecked(!1):this.createAction.items[0].toggle(!1)},scope:this}}));var l=function(a,b,c){!0===b&&this.setHandler(c,!1);this.createAction.items[0]instanceof Ext.menu.CheckItem?this.createAction.items[0].setChecked(b):this.createAction.items[0].toggle(b)};k.push(new Ext.menu.CheckItem({groupClass:null,text:this.pointText,group:f,iconCls:"gxp-icon-point",listeners:{checkchange:l.createDelegate(this,[OpenLayers.Handler.Point],2)}}),new Ext.menu.CheckItem({groupClass:null, text:this.lineText,group:f,iconCls:"gxp-icon-line",listeners:{checkchange:l.createDelegate(this,[OpenLayers.Handler.Path],2)}}),new Ext.menu.CheckItem({groupClass:null,text:this.polygonText,group:f,iconCls:"gxp-icon-polygon",listeners:{checkchange:l.createDelegate(this,[OpenLayers.Handler.Polygon],2)}}));g.push(new GeoExt.Action(Ext.apply(h,{menu:new Ext.menu.Menu({items:k})})))}else g.push(new GeoExt.Action(h));g.push(new GeoExt.Action({tooltip:this.editFeatureActionTip,text:this.initialConfig.editFeatureActionText, menuText:this.initialConfig.editFeatureActionText,iconCls:this.iconClsEdit,disabled:!0,toggleGroup:f,group:f,groupClass:null,enableToggle:!0,allowDepress:!0,control:this.selectControl,deactivateOnDisable:!0,map:this.target.mapPanel.map,listeners:{checkchange:this.onItemCheckchange,scope:this}}));this.createAction=g[0];this.editAction=g[1];this.splitButton&&(this.splitButton=new Ext.SplitButton({menu:{items:[Ext.apply(new Ext.menu.CheckItem(g[0]),{text:this.createFeatureActionText}),Ext.apply(new Ext.menu.CheckItem(g[1]), {text:this.editFeatureActionText})]},disabled:!0,buttonText:this.splitButtonText,tooltip:this.splitButtonTooltip,iconCls:this.iconClsAdd,enableToggle:!0,toggleGroup:this.toggleGroup,allowDepress:!0,handler:function(a,b){a.pressed&&a.menu.items.itemAt(this.activeIndex).setChecked(!0)},scope:this,listeners:{toggle:function(a,b){b||a.menu.items.each(function(a){a.setChecked(!1)})},render:function(a){Ext.ButtonToggleMgr.register(a)}}}),g=[this.splitButton]);g=gxp.plugins.FeatureEditor.superclass.addActions.call(this, g);c.on("layerchange",this.onLayerChange,this);(f=this.getSnappingAgent())&&f.registerEditor(this);return g},onItemCheckchange:function(a,b){this.splitButton&&(this.activeIndex=a.ownerCt.items.indexOf(a),this.splitButton.toggle(b),b&&this.splitButton.setIconClass(a.iconCls))},getFeatureManager:function(){var a=this.target.tools[this.featureManager];if(!a)throw Error("Unable to access feature manager by id: "+this.featureManager);return a},getSnappingAgent:function(){var a,b=this.snappingAgent;if(b&& (a=this.target.tools[b],!a))throw Error("Unable to locate snapping agent with id: "+b);return a},setHandler:function(a,b){var c=this.drawControl,d=c.active;d&&c.deactivate();c.handler.destroy();c.handler=new a(c,c.callbacks,Ext.apply(c.handlerOptions,{multi:b}));d&&c.activate()},enableOrDisable:function(){var a=!this.schema;this.splitButton&&this.splitButton.setDisabled(a);this.createAction.setDisabled(a);this.editAction.setDisabled(a);return a},onLayerChange:function(a,b,c){this.schema=c;if(this.enableOrDisable())this.fireEvent("layereditable", this,b,!1);else{c=this.createAction;var d={Point:OpenLayers.Handler.Point,Line:OpenLayers.Handler.Path,Curve:OpenLayers.Handler.Path,Polygon:OpenLayers.Handler.Polygon,Surface:OpenLayers.Handler.Polygon},e=a.geometryType&&a.geometryType.replace("Multi","");(d=e&&d[e])?(this.setHandler(d,e!=a.geometryType),c.enable()):!0===this.supportAbstractGeometry&&a.geometryType&&"Geometry"===a.geometryType?c.enable():c.disable();this.fireEvent("layereditable",this,b,!0)}},select:function(a){this.selectControl.unselectAll(this.popup&& this.popup.editing&&{except:this.popup.feature});this.selectControl.select(a)}});Ext.preg(gxp.plugins.FeatureEditor.prototype.ptype,gxp.plugins.FeatureEditor);Ext.namespace("gxp.plugins"); gxp.plugins.RemoveLayer=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_removelayer",removeMenuText:"Remove layer",removeActionTip:"Remove layer",addActions:function(){var a,b=gxp.plugins.RemoveLayer.superclass.addActions.apply(this,[{menuText:this.removeMenuText,iconCls:"gxp-icon-removelayers",disabled:!0,tooltip:this.removeActionTip,handler:function(){var b=a;b&&this.target.mapPanel.layers.remove(b)},scope:this}]),c=b[0];this.target.on("layerselectionchange",function(b){a=b;c.setDisabled(1>=this.target.mapPanel.layers.getCount()|| !b)},this);var d=function(b){c.setDisabled(!a||1>=b.getCount())};this.target.mapPanel.layers.on({add:d,remove:d});return b}});Ext.preg(gxp.plugins.RemoveLayer.prototype.ptype,gxp.plugins.RemoveLayer);Ext.namespace("gxp.plugins"); gxp.plugins.OLSource=Ext.extend(gxp.plugins.LayerSource,{ptype:"gxp_olsource",createLayerRecord:function(a){var b,c=window;b=a.type.split(".");for(var d=0,e=b.length;d<e&&(c=c[b[d]],c);++d);if(c&&c.prototype&&c.prototype.initialize)b=function(){c.prototype.initialize.apply(this,a.args)},b.prototype=c.prototype,b=new b,"visibility"in a&&(b.visibility=a.visibility),b=new (GeoExt.data.LayerRecord.create([{name:"name",type:"string"},{name:"source",type:"string"},{name:"group",type:"string"},{name:"fixed", type:"boolean"},{name:"selected",type:"boolean"},{name:"type",type:"string"},{name:"args"},{name:"queryable",type:"boolean"}]))({layer:b,title:b.name,name:a.name||b.name,source:a.source,group:a.group,fixed:"fixed"in a?a.fixed:!1,selected:"selected"in a?a.selected:!1,queryable:"queryable"in a?a.queryable:!1,type:a.type,args:a.args,properties:"properties"in a?a.properties:void 0},b.id);else throw Error("Cannot construct OpenLayers layer from given type: "+a.type);return b},getConfigForRecord:function(a){var b= gxp.plugins.OLSource.superclass.getConfigForRecord.apply(this,arguments);a.getLayer();return Ext.apply(b,{type:a.get("type"),args:a.get("args")})}});Ext.preg(gxp.plugins.OLSource.prototype.ptype,gxp.plugins.OLSource);Ext.namespace("gxp.plugins"); gxp.plugins.Print=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_print",printService:null,printCapabilities:null,customParams:null,includeLegend:!1,menuText:"Print Map",tooltip:"Print Map",buttonText:"Print",notAllNotPrintableText:"Not All Layers Can Be Printed",nonePrintableText:"None of your current map layers can be printed",previewText:"Print Preview",openInNewWindow:!1,constructor:function(a){gxp.plugins.Print.superclass.constructor.apply(this,arguments)},addActions:function(){if(null!==this.printService|| null!=this.printCapabilities){var a=function(){k.show();k.setWidth(0);var a=0;k.items.get(0).items.get(0).items.each(function(b){b.getEl()&&(a+=b.getWidth())});k.setWidth(Math.max(k.items.get(0).printMapPanel.getWidth(),a+20));k.center()},b=function(){var a=null;if(!0===this.includeLegend){var b,d;for(b in this.target.tools)if(d=this.target.tools[b],"gxp_legend"===d.ptype){a=d.getLegendPanel();break}if(null===a)for(b in this.target.tools)if(d=this.target.tools[b],"gxp_layermanager"===d.ptype){a=d; break}}return k=new Ext.Window({title:this.previewText,modal:!0,border:!1,autoHeight:!0,resizable:!1,width:360,items:[new GeoExt.ux.PrintPreview({minWidth:336,mapTitle:this.target.about&&this.target.about.title,comment:this.target.about&&this.target.about["abstract"],printMapPanel:{autoWidth:!0,height:Math.min(420,Ext.get(document.body).getHeight()-150),limitScales:!0,map:Ext.applyIf({controls:[new OpenLayers.Control.Navigation({zoomWheelEnabled:!1,zoomBoxEnabled:!1}),new OpenLayers.Control.PanPanel, new OpenLayers.Control.ZoomPanel,new OpenLayers.Control.Attribution],eventListeners:{preaddlayer:function(a){return c(a.layer)}}},l.initialConfig.map),items:[{xtype:"gx_zoomslider",vertical:!0,height:100,aggressive:!0}],listeners:{afterlayout:function(a){k.setWidth(Math.max(360,this.getWidth()+24));k.center()}}},printProvider:f,includeLegend:this.includeLegend,legend:a,sourceMap:l})],listeners:{beforedestroy:e}})},c=function(a){return!0===a.getVisibility()&&(a instanceof OpenLayers.Layer.WMS||a instanceof OpenLayers.Layer.OSM)},d=function(){var a=[];l.layers.each(function(b){b=b.getLayer();c(b)&&a.push(b)});return a},e=function(){if(k){try{k.items.first().printMapPanel.printPage.destroy()}catch(a){}k=null}},f=new GeoExt.data.PrintProvider({capabilities:this.printCapabilities,url:this.printService,customParams:this.customParams,autoLoad:!1,listeners:{beforedownload:function(a,b){if(!0===this.openInNewWindow)return window.open(b),!1},beforeencodelegend:function(a,b,c){if(c&&"gxp_layermanager"===c.ptype){var d= [];(c=c.output)&&c[0]&&c[0].getRootNode().cascade(function(a){if(a.component&&!a.component.hidden){a=a.component;var c=this.encoders.legends[a.getXType()];d=d.concat(c.call(this,a,b.pages[0].scale))}},a);b.legends=d;return!1}},beforeprint:function(){k.items.get(0).printMapPanel.layers.each(function(a){a=a.get("layer").params;for(var b in a)a[b]instanceof Array&&(a[b]=a[b].join(","))})},loadcapabilities:function(){h&&(h.initialConfig.disabled=!1,h.enable())},print:function(){try{k.close()}catch(a){}}, printException:function(a,b){this.target.displayXHRTrouble&&this.target.displayXHRTrouble(b)},scope:this}}),g=gxp.plugins.Print.superclass.addActions.call(this,[{menuText:this.menuText,buttonText:this.buttonText,tooltip:this.tooltip,iconCls:"gxp-icon-print",disabled:null!==this.printCapabilities?!1:!0,handler:function(){if(0<d().length){var c=b.call(this);a.call(this);return c}Ext.Msg.alert(this.notAllNotPrintableText,this.nonePrintableText)},scope:this,listeners:{render:function(){f.loadCapabilities()}}}]), h=g[0].items[0],k,l=this.target.mapPanel;return g}}});Ext.preg(gxp.plugins.Print.prototype.ptype,gxp.plugins.Print);Ext.namespace("gxp.plugins"); gxp.plugins.StyleWriter=Ext.extend(Ext.util.Observable,{deletedStyles:null,constructor:function(a){this.initialConfig=a;Ext.apply(this,a);this.deletedStyles=[];gxp.plugins.StyleWriter.superclass.constructor.apply(this,arguments)},init:function(a){this.target=a;a.stylesStore.on({remove:function(a,c,d){a=c.get("name");c.get("name")===a&&this.deletedStyles.push(a)},scope:this});a.on({beforesaved:this.write,scope:this})},write:function(a,b){a.stylesStore.commitChanges();a.fireEvent("saved",a,a.selectedStyle.get("name"))}}); Ext.namespace("gxp.plugins"); gxp.plugins.GeoServerStyleWriter=Ext.extend(gxp.plugins.StyleWriter,{baseUrl:"/geoserver/rest",constructor:function(a){this.initialConfig=a;Ext.apply(this,a);gxp.plugins.GeoServerStyleWriter.superclass.constructor.apply(this,arguments)},write:function(a){delete this._failed;a=a||{};var b=[],c=this.target.stylesStore;c.each(function(a){(a.phantom||-1!==c.modified.indexOf(a))&&this.writeStyle(a,b)},this);var d=function(){var b=this.target;if(!0!==this._failed){this.deleteStyles();for(var c=this.target.stylesStore.getModifiedRecords(), d=c.length-1;0<=d;--d)c[d].phantom=!1;b.stylesStore.commitChanges();a.success&&a.success.call(a.scope);b.fireEvent("saved",b,b.selectedStyle.get("name"))}else b.fireEvent("savefailed",b,b.selectedStyle.get("name"))};0<b.length?gxp.util.dispatch(b,function(){this.assignStyles(a.defaultStyle,d)},this):this.assignStyles(a.defaultStyle,d)},writeStyle:function(a,b){var c=a.get("userStyle").name;b.push(function(b,e){Ext.Ajax.request({method:!0===a.phantom?"POST":"PUT",url:this.baseUrl+"/styles"+(!0===a.phantom? "":"/"+c+".xml"),headers:{"Content-Type":"application/vnd.ogc.sld+xml; charset=UTF-8"},xmlData:this.target.createSLD({userStyles:[c]}),failure:function(){this._failed=!0;b.call(this)},success:!0===a.phantom?function(){Ext.Ajax.request({method:"POST",url:this.baseUrl+"/layers/"+this.target.layerRecord.get("name")+"/styles.json",jsonData:{style:{name:c}},failure:function(){this._failed=!0;b.call(this)},success:b,scope:this})}:b,scope:this})})},assignStyles:function(a,b){var c=[];this.target.stylesStore.each(function(b){a|| !0!==b.get("userStyle").isDefault||(a=b.get("name"));b.get("name")!==a&&-1===this.deletedStyles.indexOf(b.id)&&c.push({name:b.get("name")})},this);Ext.Ajax.request({method:"PUT",url:this.baseUrl+"/layers/"+this.target.layerRecord.get("name")+".json",jsonData:{layer:{defaultStyle:{name:a},styles:0<c.length?{style:c}:{},enabled:!0}},success:b,failure:function(){this._failed=!0;b.call(this)},scope:this})},deleteStyles:function(){for(var a=0,b=this.deletedStyles.length;a<b;++a)Ext.Ajax.request({method:"DELETE", url:this.baseUrl+"/styles/"+this.deletedStyles[a]+"?purge=true"});this.deletedStyles=[]}});Ext.preg("gxp_geoserverstylewriter",gxp.plugins.GeoServerStyleWriter);Ext.namespace("gxp"); gxp.ScaleOverlay=Ext.extend(Ext.Panel,{map:null,zoomLevelText:"Zoom level",initComponent:function(){gxp.ScaleOverlay.superclass.initComponent.call(this);this.cls="map-overlay";this.map&&(this.map instanceof GeoExt.MapPanel&&(this.map=this.map.map),this.bind(this.map));this.on("beforedestroy",this.unbind,this)},addToMapPanel:function(a){this.on({afterrender:function(){this.bind(a.map)},scope:this})},stopMouseEvents:function(a){a.stopEvent()},removeFromMapPanel:function(a){a=this.getEl();a.un("mousedown", this.stopMouseEvents,this);a.un("click",this.stopMouseEvents,this);this.unbind()},addScaleLine:function(){var a=new Ext.BoxComponent({autoEl:{tag:"div",cls:"olControlScaleLine overlay-element overlay-scaleline"}});this.on("afterlayout",function(){a.getEl().dom.style.position="relative";a.getEl().dom.style.display="inline";this.getEl().on("click",this.stopMouseEvents,this);this.getEl().on("mousedown",this.stopMouseEvents,this)},this);a.on("render",function(){var b=new OpenLayers.Control.ScaleLine({geodesic:!0, div:a.getEl().dom});this.map.addControl(b);b.activate()},this);this.add(a)},handleZoomEnd:function(){var a=this.zoomStore.queryBy(function(a){return this.map.getZoom()==a.data.level},this);0<a.length?(a=a.items[0],this.zoomSelector.setValue("1 : "+parseInt(a.data.scale,10))):this.zoomSelector.rendered&&this.zoomSelector.clearValue()},addScaleCombo:function(){this.zoomStore=new GeoExt.data.ScaleStore({map:this.map});this.zoomSelector=new Ext.form.ComboBox({emptyText:this.zoomLevelText,tpl:'<tpl for="."><div class="x-combo-list-item">1 : {[parseInt(values.scale)]}</div></tpl>', editable:!1,triggerAction:"all",mode:"local",store:this.zoomStore,width:110});this.zoomSelector.on({click:this.stopMouseEvents,mousedown:this.stopMouseEvents,select:function(a,c,d){this.map.zoomTo(c.data.level)},scope:this});this.map.events.register("zoomend",this,this.handleZoomEnd);var a=new Ext.Panel({items:[this.zoomSelector],cls:"overlay-element overlay-scalechooser",border:!1});this.add(a)},bind:function(a){this.map=a;this.addScaleLine();this.addScaleCombo();this.doLayout()},unbind:function(){this.map&& this.map.events&&this.map.events.unregister("zoomend",this,this.handleZoomEnd);this.zoomSelector=this.zoomStore=null}});Ext.reg("gxp_scaleoverlay",gxp.ScaleOverlay);Ext.namespace("gxp.plugins"); gxp.plugins.WMSRasterStylesDialog={isRaster:null,init:function(a){Ext.apply(a,gxp.plugins.WMSRasterStylesDialog)},createRule:function(){var a=[new OpenLayers.Symbolizer[this.isRaster?"Raster":this.symbolType]];return new OpenLayers.Rule({symbolizers:a})},addRule:function(){var a=this.items.get(2).items.get(0);this.isRaster?(a.rules.push(this.createPseudoRule()),1==a.rules.length&&a.rules.push(this.createPseudoRule()),this.savePseudoRules()):(this.selectedStyle.get("userStyle").rules.push(this.createRule()), a.update(),this.selectedStyle.store.afterEdit(this.selectedStyle));this.updateRuleRemoveButton()},removeRule:function(){if(this.isRaster){var a=this.items.get(2).items.get(0),b=this.selectedRule;a.unselect();a.rules.remove(b);1==a.rules.length&&a.rules.remove(a.rules[0]);this.savePseudoRules()}else gxp.WMSStylesDialog.prototype.removeRule.apply(this,arguments)},duplicateRule:function(){var a=this.items.get(2).items.get(0);if(this.isRaster)a.rules.push(this.createPseudoRule({quantity:this.selectedRule.name, label:this.selectedRule.title,color:this.selectedRule.symbolizers[0].fillColor,opacity:this.selectedRule.symbolizers[0].fillOpacity})),this.savePseudoRules();else{var b=this.selectedRule.clone();b.name=gxp.util.uniqueName((b.title||b.name)+" (copy)");delete b.title;this.selectedStyle.get("userStyle").rules.push(b);a.update()}this.updateRuleRemoveButton()},editRule:function(){this.isRaster?this.editPseudoRule():gxp.WMSStylesDialog.prototype.editRule.apply(this,arguments)},editPseudoRule:function(){var a= this,b=this.selectedRule,c=new Ext.Window({title:"Color Map Entry: "+b.name,width:340,autoHeight:!0,modal:!0,items:[{bodyStyle:"padding-top: 5px",border:!1,defaults:{autoHeight:!0,hideMode:"offsets"},items:[{xtype:"form",border:!1,labelAlign:"top",defaults:{border:!1},style:{padding:"0.3em 0 0 1em"},items:[{layout:"column",defaults:{border:!1,style:{"padding-right":"1em"}},items:[{layout:"form",width:70,items:[{xtype:"numberfield",anchor:"95%",value:b.name,allowBlank:!1,fieldLabel:"Quantity",validator:function(c){for(var d= a.items.get(2).items.get(0).rules,g=d.length-1;0<=g;g--)if(b!==d[g]&&d[g].name==c)return"Quantity "+c+" is already defined";return!0},listeners:{valid:function(a){this.selectedRule.name=String(a.getValue());this.savePseudoRules()},scope:this}}]},{layout:"form",width:130,items:[{xtype:"textfield",fieldLabel:"Label",anchor:"95%",value:b.title,listeners:{valid:function(a){this.selectedRule.title=a.getValue();this.savePseudoRules()},scope:this}}]},{layout:"form",width:70,items:[new GeoExt.FeatureRenderer({symbolType:this.symbolType, symbolizers:[b.symbolizers[0]],isFormField:!0,fieldLabel:"Appearance"})]}]}]},{xtype:"gxp_polygonsymbolizer",symbolizer:b.symbolizers[0],bodyStyle:{padding:"10px"},border:!1,labelWidth:70,defaults:{labelWidth:70},listeners:{change:function(a){var b=c.findByType(GeoExt.FeatureRenderer)[0];b.setSymbolizers([a],{draw:b.rendered});this.selectedRule.symbolizers[0]=a;this.savePseudoRules()},scope:this}}]}]}),d=c.findByType("gxp_strokesymbolizer")[0];d.ownerCt.remove(d);c.show()},savePseudoRules:function(){var a= this.selectedStyle,b=this.items.get(2).items.get(0),a=a.get("userStyle"),b=b.rules;b.sort(function(a,b){var c=parseFloat(a.name),d=parseFloat(b.name);return c===d?0:c<d?-1:1});a=a.rules[0].symbolizers[0];a.colorMap=0<b.length?Array(b.length):void 0;for(var c,d=0,e=b.length;d<e;++d)c=b[d],a.colorMap[d]={quantity:parseFloat(c.name),label:c.title||void 0,color:c.symbolizers[0].fillColor||void 0,opacity:0==c.symbolizers[0].fill?0:c.symbolizers[0].fillOpacity};this.afterRuleChange(this.selectedRule)}, createLegend:function(a,b){var c=OpenLayers.Symbolizer.Raster;c&&a[0]&&a[0].symbolizers[0]instanceof c?(this.getComponent("rulesfieldset").setTitle("Color Map Entries"),this.isRaster=!0,this.addRasterLegend(a,b)):(this.isRaster=!1,this.addVectorLegend(a))},addRasterLegend:function(a,b){b=b||{};for(var c=a[0].symbolizers[0].colorMap||[],d=[],e=0,f=c.length;e<f;e++)d.push(this.createPseudoRule(c[e]));this.selectedRule=null!=b.selectedRuleIndex?d[b.selectedRuleIndex]:null;return this.addVectorLegend(d, {symbolType:"Polygon",enableDD:!1})},createPseudoRule:function(a){var b=-1;if(!a){var c=this.items.get(2);if(c.items)for(rules=c.items.get(0).rules,c=rules.length-1;0<=c;c--)b=Math.max(b,parseFloat(rules[c].name))}a=Ext.applyIf(a||{},{quantity:++b,color:"#000000",opacity:1});return new OpenLayers.Rule({title:a.label,name:String(a.quantity),symbolizers:[new OpenLayers.Symbolizer.Polygon({fillColor:a.color,fillOpacity:a.opacity,stroke:!1,fill:0!==a.opacity})]})},updateRuleRemoveButton:function(){this.items.get(3).items.get(1).setDisabled(!this.selectedRule|| !1===this.isRaster&&1>=this.items.get(2).items.get(0).rules.length)}};Ext.preg("gxp_wmsrasterstylesdialog",gxp.plugins.WMSRasterStylesDialog);Ext.namespace("gxp.menu"); gxp.menu.LayerMenu=Ext.extend(Ext.menu.Menu,{layerText:"Layer",layers:null,initComponent:function(){gxp.menu.LayerMenu.superclass.initComponent.apply(this,arguments);this.layers.on("add",this.onLayerAdd,this);this.onLayerAdd()},onRender:function(a,b){gxp.menu.LayerMenu.superclass.onRender.apply(this,arguments)},beforeDestroy:function(){this.layers&&this.layers.on&&this.layers.un("add",this.onLayerAdd,this);delete this.layers;gxp.menu.LayerMenu.superclass.beforeDestroy.apply(this,arguments)},onLayerAdd:function(){this.removeAll(); this.add({iconCls:"gxp-layer-visibility",text:this.layerText,canActivate:!1},"-");this.layers.each(function(a){if(a.getLayer().displayInLayerSwitcher){var b=new Ext.menu.CheckItem({text:a.get("title"),checked:a.getLayer().getVisibility(),group:a.get("group"),listeners:{checkchange:function(b,d){a.getLayer().setVisibility(d)}}});2<this.items.getCount()?this.insert(2,b):this.add(b)}},this)}});Ext.reg("gxp_layermenu",gxp.menu.LayerMenu);Ext.namespace("gxp"); gxp.RulePanel=Ext.extend(Ext.TabPanel,{fonts:void 0,symbolType:"Point",rule:null,attributes:null,nestedFilters:!0,minScaleDenominatorLimit:1.577757414193268E9*Math.pow(.5,19)*OpenLayers.DOTS_PER_INCH/256,maxScaleDenominatorLimit:1.577757414193268E9*OpenLayers.DOTS_PER_INCH/256,scaleLevels:20,scaleSliderTemplate:"{scaleType} Scale 1:{scale}",modifyScaleTipContext:Ext.emptyFn,labelFeaturesText:"Label Features",labelsText:"Labels",basicText:"Basic",advancedText:"Advanced",limitByScaleText:"Limit by scale", limitByConditionText:"Limit by condition",symbolText:"Symbol",nameText:"Name",initComponent:function(){Ext.applyIf(this,{plain:!0,border:!1});this.rule?this.initialConfig.symbolType||(this.symbolType=this.getSymbolTypeFromRule(this.rule)||this.symbolType):this.rule=new OpenLayers.Rule({name:this.uniqueRuleName()});this.activeTab=0;this.textSymbolizer=new gxp.TextSymbolizer({symbolizer:this.getTextSymbolizer(),attributes:this.attributes,fonts:this.fonts,listeners:{change:function(a){this.fireEvent("change", this,this.rule)},scope:this}});this.scaleLimitPanel=new gxp.ScaleLimitPanel({maxScaleDenominator:this.rule.maxScaleDenominator||void 0,limitMaxScaleDenominator:!!this.rule.maxScaleDenominator,maxScaleDenominatorLimit:this.maxScaleDenominatorLimit,minScaleDenominator:this.rule.minScaleDenominator||void 0,limitMinScaleDenominator:!!this.rule.minScaleDenominator,minScaleDenominatorLimit:this.minScaleDenominatorLimit,scaleLevels:this.scaleLevels,scaleSliderTemplate:this.scaleSliderTemplate,modifyScaleTipContext:this.modifyScaleTipContext, listeners:{change:function(a,b,c){this.rule.minScaleDenominator=b;this.rule.maxScaleDenominator=c;this.fireEvent("change",this,this.rule)},scope:this}});this.filterBuilder=new gxp.FilterBuilder({allowGroups:this.nestedFilters,filter:this.rule&&this.rule.filter&&this.rule.filter.clone(),attributes:this.attributes,listeners:{change:function(a){a=a.getFilter();this.rule.filter=a;this.fireEvent("change",this,this.rule)},scope:this}});this.items=[{title:this.labelsText,autoScroll:!0,bodyStyle:{padding:"10px"}, items:[{xtype:"fieldset",title:this.labelFeaturesText,autoHeight:!0,checkboxToggle:!0,collapsed:!this.hasTextSymbolizer(),items:[this.textSymbolizer],listeners:{collapse:function(){OpenLayers.Util.removeItem(this.rule.symbolizers,this.getTextSymbolizer());this.fireEvent("change",this,this.rule)},expand:function(){this.setTextSymbolizer(this.textSymbolizer.symbolizer);this.fireEvent("change",this,this.rule)},scope:this}}]}];if(this.getSymbolTypeFromRule(this.rule)||this.symbolType)this.items=[{title:this.basicText, autoScroll:!0,items:[this.createHeaderPanel(),this.createSymbolizerPanel()]},this.items[0],{title:this.advancedText,defaults:{style:{margin:"7px"}},autoScroll:!0,items:[{xtype:"fieldset",title:this.limitByScaleText,checkboxToggle:!0,collapsed:!(this.rule&&(this.rule.minScaleDenominator||this.rule.maxScaleDenominator)),autoHeight:!0,items:[this.scaleLimitPanel],listeners:{collapse:function(){delete this.rule.minScaleDenominator;delete this.rule.maxScaleDenominator;this.fireEvent("change",this,this.rule)}, expand:function(){var a=this.getActiveTab();this.activeTab=null;this.setActiveTab(a);a=!1;this.scaleLimitPanel.limitMinScaleDenominator&&(this.rule.minScaleDenominator=this.scaleLimitPanel.minScaleDenominator,a=!0);this.scaleLimitPanel.limitMaxScaleDenominator&&(this.rule.maxScaleDenominator=this.scaleLimitPanel.maxScaleDenominator,a=!0);a&&this.fireEvent("change",this,this.rule)},scope:this}},{xtype:"fieldset",title:this.limitByConditionText,checkboxToggle:!0,collapsed:!(this.rule&&this.rule.filter), autoHeight:!0,items:[this.filterBuilder],listeners:{collapse:function(){delete this.rule.filter;this.fireEvent("change",this,this.rule)},expand:function(){this.rule.filter=this.filterBuilder.getFilter();this.fireEvent("change",this,this.rule)},scope:this}}]}];this.items[0].autoHeight=!0;this.addEvents("change");this.on({tabchange:function(a,b){b.doLayout()},scope:this});gxp.RulePanel.superclass.initComponent.call(this)},hasTextSymbolizer:function(){for(var a,b,c=0,d=this.rule.symbolizers.length;c< d;++c)if(a=this.rule.symbolizers[c],a instanceof OpenLayers.Symbolizer.Text){b=a;break}return b},getTextSymbolizer:function(){var a=this.hasTextSymbolizer();a||(a=new OpenLayers.Symbolizer.Text({graphic:!1}));return a},setTextSymbolizer:function(a){for(var b,c=0,d=this.rule.symbolizers.length;c<d;++c)if(candidate=this.rule.symbolizers[c],this.rule.symbolizers[c]instanceof OpenLayers.Symbolizer.Text){this.rule.symbolizers[c]=a;b=!0;break}b||this.rule.symbolizers.push(a)},uniqueRuleName:function(){return OpenLayers.Util.createUniqueID("rule_")}, createHeaderPanel:function(){this.symbolizerSwatch=new GeoExt.FeatureRenderer({symbolType:this.symbolType,isFormField:!0,fieldLabel:this.symbolText});return{xtype:"form",border:!1,labelAlign:"top",defaults:{border:!1},style:{padding:"0.3em 0 0 1em"},items:[{layout:"column",defaults:{border:!1,style:{"padding-right":"1em"}},items:[{layout:"form",width:150,items:[{xtype:"textfield",fieldLabel:this.nameText,anchor:"95%",value:this.rule&&(this.rule.title||this.rule.name||""),listeners:{change:function(a, b){this.rule.title=b;this.fireEvent("change",this,this.rule)},scope:this}}]},{layout:"form",width:70,items:[this.symbolizerSwatch]}]}]}},createSymbolizerPanel:function(){var a,b,c=OpenLayers.Symbolizer[this.symbolType],d=!1;if(c){for(var e=0,f=this.rule.symbolizers.length;e<f;++e)if(a=this.rule.symbolizers[e],a instanceof c){d=!0;b=a;break}b||(b=new c({fill:!1,stroke:!1}))}else throw Error("Appropriate symbolizer type not included in build: "+this.symbolType);this.symbolizerSwatch.setSymbolizers([b], {draw:this.symbolizerSwatch.rendered});a={xtype:"gxp_"+this.symbolType.toLowerCase()+"symbolizer",symbolizer:b,bodyStyle:{padding:"10px"},border:!1,labelWidth:70,defaults:{labelWidth:70},listeners:{change:function(a){this.symbolizerSwatch.setSymbolizers([a],{draw:this.symbolizerSwatch.rendered});d||(this.rule.symbolizers.push(a),d=!0);this.fireEvent("change",this,this.rule)},scope:this}};"Point"===this.symbolType&&this.pointGraphics&&(a.pointGraphics=this.pointGraphics);return a},getSymbolTypeFromRule:function(a){for(var b, c,d=0,e=a.symbolizers.length;d<e;++d)if(b=a.symbolizers[d],!(b instanceof OpenLayers.Symbolizer.Text)){c=b.CLASS_NAME.split(".").pop();break}return c}});Ext.reg("gxp_rulepanel",gxp.RulePanel);Ext.namespace("gxp.plugins"); gxp.plugins.LoadingIndicator=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_loadingindicator",onlyShowOnFirstLoad:!1,loadingMapMessage:"Loading Map...",layerCount:0,busyMask:null,init:function(a){var b=a instanceof GeoExt.MapPanel?a.map:a.mapPanel.map;b.events.register("preaddlayer",this,function(a){var d=a.layer;if(d instanceof OpenLayers.Layer.WMS)d.events.on({loadstart:function(){this.layerCount++;this.busyMask||(this.busyMask=new Ext.LoadMask(b.div,{msg:this.loadingMapMessage}));this.busyMask.show(); !0===this.onlyShowOnFirstLoad&&d.events.unregister("loadstart",this,arguments.callee)},loadend:function(){this.layerCount--;0===this.layerCount&&this.busyMask.hide();!0===this.onlyShowOnFirstLoad&&d.events.unregister("loadend",this,arguments.callee)},scope:this})})},destroy:function(){Ext.destroy(this.busyMask);this.busyMask=null;gxp.plugins.LoadingIndicator.superclass.destroy.apply(this,arguments)}});Ext.preg(gxp.plugins.LoadingIndicator.prototype.ptype,gxp.plugins.LoadingIndicator);Ext.namespace("gxp"); gxp.NewSourceWindow=Ext.extend(Ext.Window,{bodyStyle:"padding: 0px",hideBorders:!0,width:300,closeAction:"hide",error:null,initComponent:function(){window.setTimeout(function(){throw"gxp.NewSourceWindow is deprecated. Use gxp.NewSourceDialog instead.";},0);this.addEvents("server-added");gxp.NewSourceWindow.superclass.initComponent.apply(this,arguments);this.addEvents("server-added");var a=this.add(new gxp.NewSourceDialog(Ext.applyIf({addSource:this.addSource,header:!1,listeners:{urlselected:function(a, c){this.fireEvent("server-added",c)}}},this.initialConfig)));this.setTitle(a.title);this.setLoading=a.setLoading.createDelegate(a);this.setError=a.setError.createDelegate(a);this.on("hide",a.onHide,a)},addSource:function(a,b,c,d){}});Ext.namespace("gxp"); gxp.Histogram=Ext.extend(Ext.BoxComponent,{onRender:function(a,b){if(!this.el){var c=document.createElement("div");c.id=this.getId();this.el=Ext.get(c)}this.el.addClass("gxp-histogram");this.quantities&&this.setQuantities(this.quantities);gxp.Histogram.superclass.onRender.apply(this,arguments)},setQuantities:function(a){for(this.quantities=a;this.el.dom.firstChild;)this.el.dom.removeChild(this.el.dom.firstChild);var b,c=0,d=Number.POSITIVE_INFINITY,e,f=a.length;for(e=0;e<f;++e)b=a[e],b<d&&(d=b),b> c&&(c=b);var c=100/c,g,h=100/f;for(e=0;e<f;++e)b=document.createElement("div"),b.className="bar",g=b.style,g.width=h+"%",g.left=e*h+"%",g.top=100-(a[e]-d)*c+"%",this.el.dom.appendChild(b)}});Ext.reg("gxp_histogram",gxp.Histogram);Ext.namespace("gxp.form"); gxp.form.ViewerField=Ext.extend(Ext.form.TextArea,{viewer:null,initComponent:function(){this.width=this.width||350;this.height=this.height||220;gxp.form.ViewerField.superclass.initComponent.call(this)},onRender:function(){this.el||(this.defaultAutoCreate={tag:"textarea",style:{color:"transparent",background:"none"}});gxp.form.ViewerField.superclass.onRender.apply(this,arguments);this.viewerEl=Ext.get(document.createElement("div"));this.viewerEl.setStyle("position","absolute");this.viewerEl.on({mouseenter:function(){this.hasFocus|| this.el.focus()},mousemove:function(){this.hasFocus||this.el.focus()},mouseleave:function(){this.hasFocus&&this.el.blur()},scope:this});this.el.dom.parentNode.appendChild(this.viewerEl.dom);this.viewerEl.anchorTo(this.el,"tl-tl");var a={border:!1,renderTo:this.viewerEl,width:this.width,height:this.height,style:"border: 1px solid transparent"},b=Ext.applyIf(this.initialConfig.viewer||{},{field:this,portalConfig:a});Ext.apply(b.portalConfig,a);this.viewer=new gxp.Viewer(b)}}); Ext.reg("gxp_viewerfield",gxp.form.ViewerField);Ext.namespace("gxp"); gxp.LayerUploadPanel=Ext.extend(Ext.FormPanel,{titleLabel:"Title",titleEmptyText:"Layer title",abstractLabel:"Description",abstractEmptyText:"Layer description",fileLabel:"Data",fieldEmptyText:"Browse for data archive...",uploadText:"Upload",uploadFailedText:"Upload failed",processingUploadText:"Processing upload...",waitMsgText:"Uploading your data...",invalidFileExtensionText:"File extension must be one of: ",optionsText:"Options",workspaceLabel:"Workspace",workspaceEmptyText:"Default workspace", dataStoreLabel:"Store",dataStoreEmptyText:"Choose a store",dataStoreNewText:"Create new store",crsLabel:"CRS",crsEmptyText:"Coordinate Reference System ID",invalidCrsText:"CRS identifier should be an EPSG code (e.g. EPSG:4326)",fileUpload:!0,validFileExtensions:".zip .tif .tiff .gz .tar.bz2 .tar .tgz .tbz2".split(" "),defaultDataStore:null,constructor:function(a){a.errorReader={read:a.handleUploadResponse||this.handleUploadResponse.createDelegate(this)};gxp.LayerUploadPanel.superclass.constructor.call(this, a)},selectedWorkspace:null,initComponent:function(){this.items=[{xtype:"textfield",name:"title",fieldLabel:this.titleLabel,emptyText:this.titleEmptyText,allowBlank:!0},{xtype:"textarea",name:"abstract",fieldLabel:this.abstractLabel,emptyText:this.abstractEmptyText,allowBlank:!0},{xtype:"fileuploadfield",id:"file",anchor:"90%",emptyText:this.fieldEmptyText,fieldLabel:this.fileLabel,name:"file",buttonText:"",buttonCfg:{iconCls:"gxp-icon-filebrowse"},listeners:{fileselected:function(a,b){a.setValue(b.split(/[/\\]/).pop())}}, validator:this.fileNameValidator.createDelegate(this)},{xtype:"fieldset",ref:"optionsFieldset",title:this.optionsText,checkboxToggle:!0,collapsed:!0,hidden:void 0!=this.workspace&&void 0!=this.store&&void 0!=this.crs,hideMode:"offsets",defaults:{anchor:"97%"},items:[this.createWorkspacesCombo(),this.createDataStoresCombo(),{xtype:"textfield",name:"nativeCRS",fieldLabel:this.crsLabel,emptyText:this.crsEmptyText,allowBlank:!0,regex:/^epsg:\d+$/i,regexText:this.invalidCrsText}],listeners:{collapse:function(a){a.items.each(function(a){a.reset()})}}}]; this.buttons=[{text:this.uploadText,handler:function(){var a=this.getForm();if(a.isValid()){var b=a.getFieldValues(),c={"import":{}};b.workspace&&(c["import"].targetWorkspace={workspace:{name:b.workspace}});Ext.isEmpty(b.store)&&this.defaultDataStore?c["import"].targetStore={dataStore:{name:this.defaultDataStore}}:Ext.isEmpty(b.store)||b.store===this.dataStoreNewText||(c["import"].targetStore={dataStore:{name:b.store}});Ext.Ajax.request({url:this.getUploadUrl(),method:"POST",jsonData:c,success:function(b){this._import= b.getResponseHeader("Location");this.optionsFieldset.expand();a.submit({url:this._import+"/tasks?expand=all",waitMsg:this.waitMsgText,waitMsgTarget:!0,reset:!0,scope:this})},scope:this})}},scope:this}];this.addEvents("workspaceselected","datastoreselected","uploadcomplete");this.getDefaultDataStore("default");gxp.LayerUploadPanel.superclass.initComponent.call(this)},fileNameValidator:function(a){for(var b=!1,c,d=0,e=this.validFileExtensions.length;d<e;++d)if(c=this.validFileExtensions[d],a.slice(-c.length).toLowerCase()=== c){b=!0;break}return b||this.invalidFileExtensionText+"<br/>"+this.validFileExtensions.join(", ")},createWorkspacesCombo:function(){return{xtype:"combo",name:"workspace",ref:"../workspace",fieldLabel:this.workspaceLabel,store:new Ext.data.JsonStore({url:this.getWorkspacesUrl(),autoLoad:!0,root:"workspaces.workspace",fields:["name","href"]}),displayField:"name",valueField:"name",mode:"local",allowBlank:!0,triggerAction:"all",forceSelection:!0,listeners:{select:function(a,b,c){this.getDefaultDataStore(b.get("name")); this.fireEvent("workspaceselected",this,b)},scope:this}}},createDataStoresCombo:function(){var a=new Ext.data.JsonStore({autoLoad:!1,root:"dataStores.dataStore",fields:["name","href"]});this.on({workspaceselected:function(d,e){c.reset();var f=e.get("href");a.removeAll();a.proxy=new Ext.data.HttpProxy({url:f.split(".json").shift()+"/datastores.json"});a.proxy.on("loadexception",b,this);a.load()},scope:this});var b=function(){var c=new a.recordType({name:this.dataStoreNewText});a.insert(0,c);a.proxy&& a.proxy.un("loadexception",b,this)};a.on("load",b,this);var c=new Ext.form.ComboBox({name:"store",ref:"../dataStore",emptyText:this.dataStoreEmptyText,fieldLabel:this.dataStoreLabel,store:a,displayField:"name",valueField:"name",mode:"local",allowBlank:!0,triggerAction:"all",forceSelection:!0,listeners:{select:function(a,b,c){this.fireEvent("datastoreselected",this,b)},scope:this}});return c},getDefaultDataStore:function(a){Ext.Ajax.request({url:this.url+"/workspaces/"+a+"/datastores/default.json", callback:function(b,c,d){this.defaultDataStore=null;200===d.status&&(b=Ext.decode(d.responseText),"default"===a&&b.dataStore&&b.dataStore.workspace&&(this.workspace.setValue(b.dataStore.workspace.name),c=new this.workspace.store.recordType({name:b.dataStore.workspace.name,href:b.dataStore.workspace.href}),this.fireEvent("workspaceselected",this,c)),b.dataStore&&!0===b.dataStore.enabled&&!/file/i.test(b.dataStore.type)&&(this.defaultDataStore=b.dataStore.name,this.dataStore.setValue(this.defaultDataStore)))}, scope:this})},getUploadUrl:function(){return this.url+"/imports"},getWorkspacesUrl:function(){return this.url+"/workspaces.json"},handleUploadResponse:function(a){var b=this.parseResponseText(a.responseText),c,d,e,f;a=this.getForm().getFieldValues();var g=!!b;if(b)if("string"===typeof b)g=!1,e=b;else if(d=b.tasks||[b.task],0===d.length)g=!1,e="Upload contains no suitable files.";else for(f=d.length-1;0<=f;--f)(b=d[f],b)?"NO_FORMAT"===b.state?(g=!1,e="Upload contains no suitable files."):"NO_CRS"!== b.state||a.nativeCRS||(g=!1,e="Coordinate Reference System (CRS) of source file "+b.data.file+" could not be determined. Please specify manually."):(g=!1,e="Unknown upload error");g?(a.title||a["abstract"]||a.nativeCRS)&&d[0].target.dataStore?(this.waitMsg=new Ext.LoadMask((this.ownerCt||this).getEl(),{msg:this.processingUploadText}),this.waitMsg.show(),Ext.Ajax.request({method:"PUT",url:d[0].layer.href,jsonData:{title:a.title||void 0,"abstract":a["abstract"]||void 0,srs:a.nativeCRS||void 0},success:this.finishUpload, failure:function(a){this.waitMsg&&this.waitMsg.hide();var b=[];try{var c=Ext.decode(a.responseText);if(c.errors)for(var d=0,e=c.errors.length;d<e;++d)b.push({id:~c.errors[d].indexOf("SRS")?"nativeCRS":"file",msg:c.errors[d]})}catch(f){b.push({id:"file",msg:a.responseText})}this.getForm().markInvalid(b)},scope:this})):this.finishUpload():c=[{data:{id:"file",msg:e||this.uploadFailedText}}];return{success:!1,records:c}},finishUpload:function(){Ext.Ajax.request({method:"POST",url:this._import,failure:this.handleFailure, success:this.handleUploadSuccess,scope:this})},parseResponseText:function(a){var b;try{b=Ext.decode(a)}catch(c){if(a=a.match(/^\s*<pre[^>]*>(.*)<\/pre>\s*/))try{b=Ext.decode(a[1])}catch(d){b=a[1]}}return b},handleUploadSuccess:function(a){Ext.Ajax.request({method:"GET",url:this._import+"?expand=all",failure:this.handleFailure,success:function(a){this.waitMsg&&this.waitMsg.hide();this.getForm().reset();a=Ext.decode(a.responseText);this.fireEvent("uploadcomplete",this,a);delete this._import},scope:this})}, handleFailure:function(a){a&&1223===a.status?this.handleUploadSuccess(a):(this.waitMsg&&this.waitMsg.hide(),this.getForm().markInvalid([{file:this.uploadFailedText}]))}});Ext.reg("gxp_layeruploadpanel",gxp.LayerUploadPanel);Ext.namespace("gxp"); gxp.StylePropertiesDialog=Ext.extend(Ext.Container,{titleText:"General",nameFieldText:"Name",titleFieldText:"Title",abstractFieldText:"Abstract",userStyle:null,initComponent:function(){Ext.applyIf(this,{layout:"form",items:[{xtype:"fieldset",title:this.titleText,labelWidth:75,defaults:{xtype:"textfield",anchor:"100%",listeners:{change:function(a,b){this.userStyle[a.name]=b;this.fireEvent("change",this,this.userStyle)},scope:this}},items:[{xtype:this.initialConfig.nameEditable?"textfield":"displayfield", fieldLabel:this.nameFieldText,name:"name",value:this.userStyle.name,maskRe:/[A-Za-z0-9_]/},{fieldLabel:this.titleFieldText,name:"title",value:this.userStyle.title},{xtype:"textarea",fieldLabel:this.abstractFieldText,name:"description",value:this.userStyle.description}]}]});this.addEvents("change");gxp.StylePropertiesDialog.superclass.initComponent.apply(this,arguments)}});Ext.reg("gxp_stylepropertiesdialog",gxp.StylePropertiesDialog);Ext.namespace("gxp"); gxp.WMSStylesDialog=Ext.extend(Ext.Container,{addStyleText:"Add",addStyleTip:"Add a new style",chooseStyleText:"Choose style",deleteStyleText:"Remove",deleteStyleTip:"Delete the selected style",editStyleText:"Edit",editStyleTip:"Edit the selected style",duplicateStyleText:"Duplicate",duplicateStyleTip:"Duplicate the selected style",addRuleText:"Add",addRuleTip:"Add a new rule",newRuleText:"New Rule",deleteRuleText:"Remove",deleteRuleTip:"Delete the selected rule",editRuleText:"Edit",editRuleTip:"Edit the selected rule", duplicateRuleText:"Duplicate",duplicateRuleTip:"Duplicate the selected rule",cancelText:"Cancel",saveText:"Save",styleWindowTitle:"User Style: {0}",ruleWindowTitle:"Style Rule: {0}",stylesFieldsetTitle:"Styles",rulesFieldsetTitle:"Rules",errorTitle:"Error saving style",errorMsg:"There was an error saving the style back to the server.",layerRecord:null,layerDescription:null,symbolType:null,stylesStore:null,selectedStyle:null,selectedRule:null,editable:!0,modified:!1,dialogCls:Ext.Window,initComponent:function(){this.addEvents("ready", "modified","styleselected","beforesaved","saved");Ext.applyIf(this,{layout:"form",disabled:!0,items:[{xtype:"fieldset",title:this.stylesFieldsetTitle,labelWidth:85,style:"margin-bottom: 0;"},{xtype:"toolbar",style:"border-width: 0 1px 1px 1px; margin-bottom: 10px;",items:[{xtype:"button",iconCls:"add",text:this.addStyleText,tooltip:this.addStyleTip,handler:this.addStyle,scope:this},{xtype:"button",iconCls:"delete",text:this.deleteStyleText,tooltip:this.deleteStyleTip,handler:function(){this.stylesStore.remove(this.selectedStyle)}, scope:this},{xtype:"button",iconCls:"edit",text:this.editStyleText,tooltip:this.editStyleTip,handler:function(){this.editStyle()},scope:this},{xtype:"button",iconCls:"duplicate",text:this.duplicateStyleText,tooltip:this.duplicateStyleTip,handler:function(){var a=this.selectedStyle,b=a.get("userStyle").clone();b.isDefault=!1;b.name=this.newStyleName();var c=this.stylesStore;c.add(new c.recordType({name:b.name,title:b.title,"abstract":b.description,userStyle:b}));this.editStyle(a)},scope:this}]}]}); this.createStylesStore();this.on({beforesaved:function(){this._saving=!0},saved:function(){delete this._saving},savefailed:function(){Ext.Msg.show({title:this.errorTitle,msg:this.errorMsg,icon:Ext.MessageBox.ERROR,buttons:{ok:!0}});delete this._saving},render:function(){gxp.util.dispatch([this.getStyles],function(){this.enable()},this)},scope:this});gxp.WMSStylesDialog.superclass.initComponent.apply(this,arguments)},addStyle:function(){if(this._ready){var a=this.selectedStyle,b=this.stylesStore,c= new OpenLayers.Style(null,{name:this.newStyleName(),rules:[this.createRule()]});b.add(new b.recordType({name:c.name,userStyle:c}));this.editStyle(a)}else this.on("ready",this.addStyle,this)},editStyle:function(a){var b=this.selectedStyle.get("userStyle"),c=new this.dialogCls(Ext.apply({bbar:["->",{text:this.cancelText,iconCls:"cancel",handler:function(){c.propertiesDialog.userStyle=b;c.destroy();a&&(this._cancelling=!0,this.stylesStore.remove(this.selectedStyle),this.changeStyle(a,{updateCombo:!0, markModified:!0}),delete this._cancelling)},scope:this},{text:this.saveText,iconCls:"save",handler:function(){c.destroy()}}]},{title:String.format(this.styleWindowTitle,b.title||b.name),shortTitle:b.title||b.name,bodyBorder:!1,autoHeight:!0,width:300,modal:!0,items:{border:!1,items:{xtype:"gxp_stylepropertiesdialog",ref:"../propertiesDialog",userStyle:b.clone(),nameEditable:!1,style:"padding: 10px;"}},listeners:{beforedestroy:function(){this.selectedStyle.set("userStyle",c.propertiesDialog.userStyle)}, scope:this}}));this.showDlg(c)},createSLD:function(a){a=a||{};var b={version:"1.0.0",namedLayers:{}},c=this.layerRecord.get("name");b.namedLayers[c]={name:c,userStyles:[]};this.stylesStore.each(function(d){a.userStyles&&-1===a.userStyles.indexOf(d.get("name"))||b.namedLayers[c].userStyles.push(d.get("userStyle"))});return(new OpenLayers.Format.SLD({multipleSymbolizers:!0,profile:"GeoServer"})).write(b)},saveStyles:function(a){!0===this.modified&&this.fireEvent("beforesaved",this,a)},updateStyleRemoveButton:function(){var a= this.selectedStyle&&this.selectedStyle.get("userStyle");this.items.get(1).items.get(1).setDisabled(!a||1>=this.stylesStore.getCount()||!0===a.isDefault)},updateRuleRemoveButton:function(){this.items.get(3).items.get(1).setDisabled(!this.selectedRule||2>this.items.get(2).items.get(0).rules.length)},createRule:function(){return new OpenLayers.Rule({symbolizers:[new OpenLayers.Symbolizer[this.symbolType]]})},addRulesFieldSet:function(){var a=new Ext.form.FieldSet({itemId:"rulesfieldset",title:this.rulesFieldsetTitle, autoScroll:!0,style:"margin-bottom: 0;",hideMode:"offsets",hidden:!0}),b=new Ext.Toolbar({style:"border-width: 0 1px 1px 1px;",hidden:!0,items:[{xtype:"button",iconCls:"add",text:this.addRuleText,tooltip:this.addRuleTip,handler:this.addRule,scope:this},{xtype:"button",iconCls:"delete",text:this.deleteRuleText,tooltip:this.deleteRuleTip,handler:this.removeRule,scope:this,disabled:!0},{xtype:"button",iconCls:"edit",text:this.editRuleText,toolitp:this.editRuleTip,handler:function(){this.layerDescription? this.editRule():this.describeLayer(this.editRule)},scope:this,disabled:!0},{xtype:"button",iconCls:"duplicate",text:this.duplicateRuleText,tip:this.duplicateRuleTip,handler:this.duplicateRule,scope:this,disabled:!0}]});this.add(a,b);this.doLayout();return a},addRule:function(){var a=this.items.get(2).items.get(0);this.selectedStyle.get("userStyle").rules.push(this.createRule());a.update();this.selectedStyle.store.afterEdit(this.selectedStyle);this.updateRuleRemoveButton()},removeRule:function(){var a= this.selectedRule;this.items.get(2).items.get(0).unselect();this.selectedStyle.get("userStyle").rules.remove(a);this.afterRuleChange()},duplicateRule:function(){var a=this.items.get(2).items.get(0),b=this.selectedRule.clone();this.selectedStyle.get("userStyle").rules.push(b);a.update();this.selectedStyle.store.afterEdit(this.selectedStyle);this.updateRuleRemoveButton()},editRule:function(){var a=this.selectedRule,b=a.clone(),c=new this.dialogCls({title:String.format(this.ruleWindowTitle,a.title|| a.name||this.newRuleText),shortTitle:a.title||a.name||this.newRuleText,layout:"fit",width:320,height:450,modal:!0,items:[{xtype:"gxp_rulepanel",ref:"rulePanel",symbolType:this.symbolType,rule:a,attributes:new GeoExt.data.AttributeStore({url:this.layerDescription.owsURL,baseParams:{SERVICE:this.layerDescription.owsType,REQUEST:"DescribeFeatureType",TYPENAME:this.layerDescription.typeName},method:"GET",disableCaching:!1}),autoScroll:!0,border:!1,defaults:{autoHeight:!0,hideMode:"offsets"},listeners:{change:this.saveRule, tabchange:function(){c instanceof Ext.Window&&c.syncShadow()},scope:this}}],bbar:["->",{text:this.cancelText,iconCls:"cancel",handler:function(){this.saveRule(c.rulePanel,b);c.destroy()},scope:this},{text:this.saveText,iconCls:"save",handler:function(){c.destroy()}}]});this.showDlg(c)},saveRule:function(a,b){var c=this.selectedStyle;this.items.get(2).items.get(0);var c=c.get("userStyle"),d=c.rules.indexOf(this.selectedRule);c.rules[d]=b;this.afterRuleChange(b)},afterRuleChange:function(a){this.items.get(2).items.get(0); this.selectedRule=a;this.selectedStyle.store.afterEdit(this.selectedStyle)},setRulesFieldSetVisible:function(a){this.items.get(3).setVisible(a&&this.editable);this.items.get(2).setVisible(a);this.doLayout()},parseSLD:function(a,b){var c=a.responseXML;c&&c.documentElement||(c=(new OpenLayers.Format.XML).read(a.responseText));var d=this.layerRecord.getLayer().params,e=this.initialConfig.styleName||d.STYLES;e&&(this.selectedStyle=this.stylesStore.getAt(this.stylesStore.findExact("name",e)));var f=new OpenLayers.Format.SLD({profile:"GeoServer", multipleSymbolizers:!0});try{var g=f.read(c).namedLayers[d.LAYERS].userStyles,h;d.SLD_BODY&&(h=f.read(d.SLD_BODY).namedLayers[d.LAYERS].userStyles,Array.prototype.push.apply(g,h));this.stylesStore.removeAll();this.selectedStyle=null;for(var k,l,m,q,c=0,n=g.length;c<n;++c)k=g[c],m=this.stylesStore.findExact("name",k.name),-1!==m&&this.stylesStore.removeAt(m),l=new this.stylesStore.recordType({name:k.name,title:k.title,"abstract":k.description,userStyle:k}),l.phantom=!1,this.stylesStore.add(l),this.selectedStyle|| e!==k.name&&(e||!0!==k.isDefault)||(this.selectedStyle=l),!0===k.isDefault&&(q=l);this.selectedStyle||(this.selectedStyle=q);this.addRulesFieldSet();this.createLegend(this.selectedStyle.get("userStyle").rules);this.stylesStoreReady();d.SLD_BODY&&this.markModified()}catch(s){window.console&&console.warn(s.message),this.setupNonEditable()}},createLegend:function(a){var b=OpenLayers.Symbolizer.Raster;if(b&&a[0]&&a[0].symbolizers[0]instanceof b)throw Error("Raster symbolizers are not supported.");this.addVectorLegend(a)}, setupNonEditable:function(){this.editable=!1;this.items.get(1).hide();(this.getComponent("rulesfieldset")||this.addRulesFieldSet()).add(this.createLegendImage());this.doLayout();this.items.get(3).hide();this.stylesStoreReady()},stylesStoreReady:function(){this.stylesStore.commitChanges();this.stylesStore.on({load:function(){this.addStylesCombo();this.updateStyleRemoveButton()},add:function(a,b,c){this.updateStyleRemoveButton();b=this.items.get(0).items.get(0);this.markModified();b.fireEvent("select", b,a.getAt(c),c);b.setValue(this.selectedStyle.get("name"))},remove:function(a,b,c){this._cancelling||(this._removing=!0,b=Math.min(c,a.getCount()-1),this.updateStyleRemoveButton(),c=this.items.get(0).items.get(0),this.markModified(),c.fireEvent("select",c,a.getAt(b),b),c.setValue(this.selectedStyle.get("name")),delete this._removing)},update:function(a,b){var c=b.get("userStyle");Ext.apply(b.data,{name:c.name,title:c.title||c.name,"abstract":c.description});this.changeStyle(b,{updateCombo:!0,markModified:!0})}, scope:this});this.stylesStore.fireEvent("load",this.stylesStore,this.stylesStore.getRange());this._ready=!0;this.fireEvent("ready")},markModified:function(){!1===this.modified&&(this.modified=!0);this._saving||this.fireEvent("modified",this,this.selectedStyle.get("name"))},createStylesStore:function(a){a=this.layerRecord.get("styles")||[];this.stylesStore=new Ext.data.JsonStore({data:{styles:a},idProperty:"name",root:"styles",fields:["name","title","abstract","legend","userStyle"],listeners:{add:function(a, c){for(var d,e=c.length-1;0<=e;--e)d=c[e],a.suspendEvents(),d.get("title")||d.set("title",d.get("name")),a.resumeEvents()}}})},getStyles:function(a){var b=this.layerRecord.getLayer();if(!0===this.editable){var c=b.params.VERSION;1.1<parseFloat(c)&&(c="1.1.1");Ext.Ajax.request({url:b.url,params:{SERVICE:"WMS",VERSION:c,REQUEST:"GetStyles",LAYERS:""+b.params.LAYERS},method:"GET",disableCaching:!1,success:this.parseSLD,failure:this.setupNonEditable,callback:a,scope:this})}else this.setupNonEditable()}, describeLayer:function(a){if(this.layerDescription)window.setTimeout(function(){a.call(this)},0);else{var b=this.layerRecord.getLayer(),c=b.params.VERSION;1.1<parseFloat(c)&&(c="1.1.1");Ext.Ajax.request({url:b.url,params:{SERVICE:"WMS",VERSION:c,REQUEST:"DescribeLayer",LAYERS:""+b.params.LAYERS},method:"GET",disableCaching:!1,success:function(a){this.layerDescription=(new OpenLayers.Format.WMSDescribeLayer).read(a.responseXML&&a.responseXML.documentElement?a.responseXML:a.responseText)[0]},callback:a, scope:this})}},addStylesCombo:function(){var a=this.stylesStore,a=new Ext.form.ComboBox(Ext.apply({fieldLabel:this.chooseStyleText,store:a,editable:!1,displayField:"title",valueField:"name",value:this.selectedStyle?this.selectedStyle.get("title"):this.layerRecord.getLayer().params.STYLES||"default",disabled:!a.getCount(),mode:"local",typeAhead:!0,triggerAction:"all",forceSelection:!0,anchor:"100%",listeners:{select:function(a,c){this.changeStyle(c);c.phantom||this._removing||this.fireEvent("styleselected", this,c.get("name"))},scope:this}},this.initialConfig.stylesComboOptions));this.items.get(0).add(a);this.doLayout()},createLegendImage:function(){var a=new GeoExt.WMSLegend({showTitle:!1,layerRecord:this.layerRecord,autoScroll:!0,defaults:{listeners:{render:function(b){b.getEl().on({load:function(c,d){d.getAttribute("src")!=b.defaultImgSrc&&(this.setRulesFieldSetVisible(!0),250<b.getEl().getHeight()&&a.setHeight(250))},error:function(){this.setRulesFieldSetVisible(!1)},scope:this})},scope:this}}}); return a},changeStyle:function(a,b){b=b||{};var c=this.items.get(2).items.get(0);this.selectedStyle=a;this.updateStyleRemoveButton();a.get("name");if(!0===this.editable){var d=a.get("userStyle"),e=c.rules.indexOf(this.selectedRule);c.ownerCt.remove(c);this.createLegend(d.rules,{selectedRuleIndex:e})}!0===b.updateCombo&&(this.items.get(0).items.get(0).setValue(d.name),!0===b.markModified&&this.markModified())},addVectorLegend:function(a,b){b=Ext.applyIf(b||{},{enableDD:!0});this.symbolType=b.symbolType; if(!this.symbolType){var c=["Point","Line","Polygon"];highest=0;for(var d=a[0].symbolizers,e,f=d.length-1;0<=f;f--)e=d[f].CLASS_NAME.split(".").pop(),highest=Math.max(highest,c.indexOf(e));this.symbolType=c[highest]}var g=this.items.get(2).add({xtype:"gx_vectorlegend",showTitle:!1,height:10<a.length?250:void 0,autoScroll:10<a.length,rules:a,symbolType:this.symbolType,selectOnClick:!0,enableDD:b.enableDD,listeners:{ruleselected:function(a,b){this.selectedRule=b;var c=this.items.get(3).items;this.updateRuleRemoveButton(); c.get(2).enable();c.get(3).enable()},ruleunselected:function(a,b){this.selectedRule=null;var c=this.items.get(3).items;c.get(1).disable();c.get(2).disable();c.get(3).disable()},rulemoved:function(){this.markModified()},afterlayout:function(){null!==this.selectedRule&&null===g.selectedRule&&-1!==g.rules.indexOf(this.selectedRule)&&g.selectRuleEntry(this.selectedRule)},scope:this}});this.setRulesFieldSetVisible(!0);return g},newStyleName:function(){var a=this.layerRecord.get("name");return a.split(":").pop()+ "_"+gxp.util.md5(a+new Date+Math.random()).substr(0,8)},showDlg:function(a){a.show()}}); gxp.WMSStylesDialog.createGeoServerStylerConfig=function(a,b){var c=a.getLayer();b||(b=a.get("restUrl"));b||(b=c.url.split("?").shift().replace(/\/(wms|ows)\/?$/,"/rest"));return{xtype:"gxp_wmsstylesdialog",layerRecord:a,plugins:[{ptype:"gxp_geoserverstylewriter",baseUrl:b}],listeners:{styleselected:function(a,b){c.mergeNewParams({styles:b})},modified:function(a,b){a.saveStyles()},saved:function(a,b){c.mergeNewParams({_olSalt:Math.random(),styles:b})},scope:this}}}; OpenLayers.Renderer.defaultSymbolizer={fillColor:"#808080",fillOpacity:1,strokeColor:"#000000",strokeOpacity:1,strokeWidth:1,strokeDashstyle:"solid",pointRadius:3,graphicName:"square",fontColor:"#000000",fontSize:10,haloColor:"#FFFFFF",haloOpacity:1,haloRadius:1,labelAlign:"cm"};Ext.reg("gxp_wmsstylesdialog",gxp.WMSStylesDialog);Ext.namespace("gxp"); gxp.PolygonSymbolizer=Ext.extend(Ext.Panel,{symbolizer:null,initComponent:function(){this.items=[{xtype:"gxp_fillsymbolizer",symbolizer:this.symbolizer,listeners:{change:function(a){this.fireEvent("change",this.symbolizer)},scope:this}},{xtype:"gxp_strokesymbolizer",symbolizer:this.symbolizer,listeners:{change:function(a){this.fireEvent("change",this.symbolizer)},scope:this}}];this.addEvents("change");gxp.PolygonSymbolizer.superclass.initComponent.call(this)}});Ext.reg("gxp_polygonsymbolizer",gxp.PolygonSymbolizer); Ext.namespace("gxp.plugins"); gxp.plugins.WMSCSource=Ext.extend(gxp.plugins.WMSSource,{ptype:"gxp_wmscsource",version:"1.1.1",constructor:function(a){a.baseParams={SERVICE:"WMS",REQUEST:"GetCapabilities",TILED:!0};a.format||(this.format=new OpenLayers.Format.WMSCapabilities({keepData:!0,profile:"WMSC",allowFallback:!0}));gxp.plugins.WMSCSource.superclass.constructor.apply(this,arguments)},createLayerRecord:function(a){var b=gxp.plugins.WMSCSource.superclass.createLayerRecord.apply(this,arguments);if(b){var c,d;this.store.reader.raw&& (c=this.store.reader.raw.capability);var e=c&&c.vendorSpecific?c.vendorSpecific.tileSets:a.capability&&a.capability.tileSets;c=b.get("layer");if(e)for(var f=this.getProjection(b)||this.getMapProjection(),g=0,h=e.length;g<h;g++){var k=e[g];if(k.layers===c.params.LAYERS){var l;for(d in k.srs){l=new OpenLayers.Projection(d);break}if(f.equals(l)){d=k.bbox[d].bbox;c.projection=l;c.addOptions({resolutions:k.resolutions,tileSize:new OpenLayers.Size(k.width,k.height),tileOrigin:new OpenLayers.LonLat(d[0], d[1])});break}}}else this.lazy&&(l=a.tileSize,d=a.tileOrigin,c.addOptions({resolutions:a.resolutions,tileSize:l?new OpenLayers.Size(l[0],l[1]):void 0,tileOrigin:d?OpenLayers.LonLat.fromArray(d):void 0}),d||(this.target.map.maxExtent?l=this.target.map.maxExtent:(d=a.srs||this.target.map.projection,l=OpenLayers.Projection.defaults[d].maxExtent),l&&(c.tileOrigin=OpenLayers.LonLat.fromArray(l))));c.params.TILED=!1!==a.cached&&!0;return b}},getConfigForRecord:function(a){var b=gxp.plugins.WMSCSource.superclass.getConfigForRecord.apply(this, arguments),c=b.name,d,e=a.getLayer();if(b.capability&&this.store.reader.raw){d=this.store.reader.raw.capability;var f=d.vendorSpecific&&d.vendorSpecific.tileSets;if(f)for(var g=f.length-1;0<=g;--g)if(d=f[g],d.layers===c&&d.srs[e.projection]){b.capability.tileSets=[d];break}}if(!b.capability||!b.capability.tileSets){if(c=e.options.tileSize)b.tileSize=[c.w,c.h];b.tileOrigin=e.options.tileOrigin;b.resolutions=e.options.resolutions}return Ext.applyIf(b,{cached:!!e.params.TILED})}}); Ext.preg(gxp.plugins.WMSCSource.prototype.ptype,gxp.plugins.WMSCSource);Ext.namespace("gxp.plugins"); gxp.plugins.SnappingAgent=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_snappingagent",init:function(a){gxp.plugins.SnappingAgent.superclass.init.apply(this,arguments);this.snappingTargets=[];this.controls={};this.setSnappingTargets(this.targets)},setSnappingTargets:function(a){this.clearSnappingTargets();if(a)for(var b=0,c=a.length;b<c;++b)this.addSnappingTarget(a[b])},clearSnappingTargets:function(){for(var a,b=0,c=this.snappingTargets.length;b<c;++b)a=this.snappingTargets[b],a.layer&&a.layer.destroy(); this.snappingTargets.length=0},addSnappingTarget:function(a){a=Ext.apply({},a);var b=this.target.mapPanel.map,c=new OpenLayers.Layer.Vector(a.name,{strategies:[new OpenLayers.Strategy.BBOX({ratio:1.5,autoActivate:!1})],displayInLayerSwitcher:!1,visibility:!1,minResolution:a.minResolution,maxResolution:a.maxResolution});a.layer=c;this.snappingTargets.push(a);var d=new gxp.plugins.FeatureManager({maxFeatures:null,paging:!1,layer:{source:a.source,name:a.name},listeners:{layerchange:function(){c.protocol= d.featureStore.proxy.protocol;b.addLayer(c);b.events.on({moveend:function(){this.updateSnappingTarget(a)},scope:this});this.updateSnappingTarget(a);this.target.on({featureedit:function(b,c){c.name==a.name&&c.source==a.source&&this.updateSnappingTarget(a,{force:!0})},scope:this})},scope:this}});d.init(this.target)},updateSnappingTarget:function(a,b){var c=a.minResolution||Number.NEGATIVE_INFINITY,d=a.maxResolution||Number.POSITIVE_INFINITY,e=this.target.mapPanel.map.getResolution();c<=e&&e<d&&(c=a.layer.visibility, a.layer.visibility=!0,a.layer.strategies[0].update(b),a.layer.visibility=c)},createSnappingControl:function(a){return new OpenLayers.Control.Snapping(Ext.applyIf({layer:a},this.initialConfig.controlOptions||this.initialConfig.options||{}))},registerEditor:function(a){var b=a.getFeatureManager(),b=this.createSnappingControl(b.featureLayer);this.controls[a.id]=b;a.on({layereditable:this.onLayerEditable,featureeditable:this.onFeatureEditable,scope:this})},onLayerEditable:function(a,b,c){a=this.controls[a.id]; if(c){c=[];for(var d,e,f=b.get("source"),g=b.get("name"),h=0,k=this.snappingTargets.length;h<k;++h)if(b=this.snappingTargets[h],b.restrictedLayers){e=!1;for(var l=0,m=b.restrictedLayers.length;l<m;++l)if(d=b.restrictedLayers[l],d.source===f&&d.name===g){e=!0;break}e&&c.push(b)}else c.push(b);a.setTargets(c);a.activate()}else a.deactivate()},onFeatureEditable:function(a,b,c){var d=a.getFeatureManager().layerRecord;a=d.get("source");for(var d=d.get("name"),e,f,g,h=0,k=this.snappingTargets.length;h< k;++h)e=this.snappingTargets[h],a===e.source&&d===e.name&&(f=this.targets[h].filter,b&&b.fid&&c?(g=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.NOT,filters:[new OpenLayers.Filter.FeatureId({fids:[b.fid]})]}),e.filter=f?new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.AND,filters:[f,g]}):g):e.filter=f)}});Ext.preg(gxp.plugins.SnappingAgent.prototype.ptype,gxp.plugins.SnappingAgent);Ext.namespace("gxp"); gxp.Viewer=Ext.extend(Ext.util.Observable,{defaultToolType:"gxp_tool",tools:null,selectedLayer:null,authenticate:null,saveErrorText:"Trouble saving: ",constructor:function(a){this.addEvents("ready","beforecreateportal","portalready","beforelayerselectionchange","layerselectionchange","featureedit","authorizationchange","beforesave","save","beforehashchange");Ext.apply(this,{layerSources:{},portalItems:[]});this.createLayerRecordQueue=[];(a.loadConfig||this.loadConfig).call(this,a,this.applyConfig); gxp.Viewer.superclass.constructor.apply(this,arguments)},selectLayer:function(a){a=a||null;var b=!1;!1!==this.fireEvent("beforelayerselectionchange",a)&&(b=!0,this.selectedLayer&&this.selectedLayer.set("selected",!1),(this.selectedLayer=a)&&this.selectedLayer.set("selected",!0),this.fireEvent("layerselectionchange",a));return b},loadConfig:function(a){this.applyConfig(a)},applyConfig:function(a){this.initialConfig=Ext.apply({},a);Ext.apply(this,this.initialConfig);this.load()},load:function(){this.proxy&& (OpenLayers.ProxyHost=this.proxy);this.initMapPanel();this.initTools();var a=[],b;for(b in this.sources)a.push(this.createSourceLoader(b));a.push(function(a){Ext.onReady(function(){this.initPortal();a()},this)});gxp.util.dispatch(a,this.activate,this)},createSourceLoader:function(a){return function(b){var c=this.sources[a];c.projection=this.initialConfig.map.projection;this.addLayerSource({id:a,config:c,callback:b,fallback:function(a,c,f){b()},scope:this})}},addLayerSource:function(a){var b=a.id|| Ext.id(null,"gxp-source-"),c,d=a.config;d.id=b;try{c=Ext.ComponentMgr.createPlugin(d,this.defaultSourceType)}catch(e){throw Error("Could not create new source plugin with ptype: "+a.config.ptype);}c.on({ready:{fn:function(){(a.callback||Ext.emptyFn).call(a.scope||this,b)},scope:this,single:!0},failure:{fn:function(){var c=a.fallback||Ext.emptyFn;delete this.layerSources[b];c.apply(a.scope||this,arguments)},scope:this,single:!0}});this.layerSources[b]=c;c.init(this);return c},initMapPanel:function(){var a= Ext.apply({},this.initialConfig.map),b={},c={wrapDateLine:void 0!==a.wrapDateLine?a.wrapDateLine:!0,maxResolution:a.maxResolution,numZoomLevels:a.numZoomLevels,displayInLayerSwitcher:!1};if(this.initialConfig.map)for(var d="theme controls resolutions projection units maxExtent restrictedExtent maxResolution numZoomLevels panMethod".split(" "),e,f=d.length-1;0<=f;--f)e=d[f],e in a&&(b[e]=a[e],delete a[e]);this.mapPanel=Ext.ComponentMgr.create(Ext.applyIf({xtype:a.xtype||"gx_mappanel",map:Ext.applyIf({theme:b.theme|| null,controls:b.controls||[new OpenLayers.Control.Navigation({zoomWheelOptions:{interval:250},dragPanOptions:{enableKinetic:!0}}),new OpenLayers.Control.PanPanel,new OpenLayers.Control.ZoomPanel,new OpenLayers.Control.Attribution],maxExtent:b.maxExtent&&OpenLayers.Bounds.fromArray(b.maxExtent),restrictedExtent:b.restrictedExtent&&OpenLayers.Bounds.fromArray(b.restrictedExtent),numZoomLevels:b.numZoomLevels||20},b),center:a.center&&new OpenLayers.LonLat(a.center[0],a.center[1]),resolutions:a.resolutions, forceInitialExtent:!0,layers:[new OpenLayers.Layer(null,c)],items:this.mapItems,plugins:this.mapPlugins,tbar:a.tbar||new Ext.Toolbar({hidden:!0})},a));this.mapPanel.getTopToolbar().on({afterlayout:this.mapPanel.map.updateSize,show:this.mapPanel.map.updateSize,hide:this.mapPanel.map.updateSize,scope:this.mapPanel.map});this.mapPanel.layers.on({add:function(a,b){for(var c,d=b.length-1;0<=d;d--)c=b[d],!0===c.get("selected")&&this.selectLayer(c)},remove:function(a,b){!0===b.get("selected")&&this.selectLayer()}, scope:this})},initTools:function(){this.tools={};if(this.initialConfig.tools&&0<this.initialConfig.tools.length)for(var a,b=0,c=this.initialConfig.tools.length;b<c;b++){try{a=Ext.ComponentMgr.createPlugin(this.initialConfig.tools[b],this.defaultToolType)}catch(d){throw Error("Could not create tool plugin with ptype: "+this.initialConfig.tools[b].ptype);}a.init(this)}},initPortal:function(){var a=Ext.apply({},this.portalConfig);0===this.portalItems.length&&(this.mapPanel.region="center",this.portalItems.push(this.mapPanel)); this.fireEvent("beforecreateportal");this.portal=Ext.ComponentMgr.create(Ext.applyIf(a,{layout:"fit",hideBorders:!0,items:{layout:"border",deferredRender:!1,items:this.portalItems}}),a.renderTo?"panel":"viewport");this.fireEvent("portalready")},activate:function(){Ext.QuickTips.init();this.addLayers();this.checkLayerRecordQueue();this.fireEvent("ready")},addLayers:function(){var a=this.initialConfig.map;if(a&&a.layers){for(var b,c,d=[],e=[],f=0;f<a.layers.length;++f)b=a.layers[f],(c=this.layerSources[b.source])? (b=c.createLayerRecord(b))&&("background"===b.get("group")?d.push(b):e.push(b)):window.console&&console.warn("Non-existing source '"+b.source+"' referenced in layer config.");a=this.mapPanel;d=d.concat(e);d.length&&a.layers.add(d)}},getLayerRecordFromMap:function(a){var b=null;this.mapPanel&&this.mapPanel.layers.each(function(c){if(c.get("source")==a.source&&c.get("name")==a.name)return b=c,!1});return b},createLayerRecord:function(a,b,c){this.createLayerRecordQueue.push({config:a,callback:b,scope:c}); this.checkLayerRecordQueue()},checkLayerRecordQueue:function(){for(var a,b,c,d,e=[],f=0,g=this.createLayerRecordQueue.length;f<g;++f)d=!1,a=this.createLayerRecordQueue[f],b=a.config.source,b in this.layerSources&&(b=this.layerSources[b],(c=b.createLayerRecord(a.config))?(function(a,b){window.setTimeout(function(){a.callback.call(a.scope,b)},0)}(a,c),d=!0):b.lazy&&b.store.load({callback:this.checkLayerRecordQueue,scope:this})),d||e.push(a);this.createLayerRecordQueue=e},getSource:function(a){return a&& this.layerSources[a.get("source")]},getState:function(){var a=Ext.apply({},this.initialConfig),b=this.mapPanel.map.getCenter();Ext.apply(a.map,{center:[b.lon,b.lat],zoom:this.mapPanel.map.zoom,layers:[]});var c={};this.mapPanel.layers.each(function(b){var e=b.getLayer();if(e.displayInLayerSwitcher&&!(e instanceof OpenLayers.Layer.Vector)){var f=b.get("source"),g=this.layerSources[f];if(!g)throw Error("Could not find source for record '"+b.get("name")+" and layer "+e.name+"'");a.map.layers.push(g.getConfigForRecord(b)); c[f]||(c[f]=g.getState())}},this);Ext.apply(this.sources,c);a.tools=[];Ext.iterate(this.tools,function(b,c,f){c.getState!=gxp.plugins.Tool.prototype.getState&&a.tools.push(c.getState())});return a},isAuthorized:function(a){var b=!0;if(this.authorizedRoles){b=!1;a||(a="ROLE_ADMINISTRATOR");Ext.isArray(a)||(a=[a]);for(var c=a.length-1;0<=c;--c)if(~this.authorizedRoles.indexOf(a[c])){b=!0;break}}return b},setAuthorizedRoles:function(a){this.authorizedRoles=a;this.fireEvent("authorizationchange")},cancelAuthentication:function(){this._authFn&& this.un("authorizationchange",this._authFn,this);this.fireEvent("authorizationchange")},isAuthenticated:function(a){return!this.authorizedRoles||0<this.authorizedRoles.length},doAuthorized:function(a,b,c){this.isAuthorized(a)||!this.authenticate?window.setTimeout(function(){b.call(c)},0):(this.authenticate(),this._authFn=function(){delete this._authFn;this.doAuthorized(a,b,c,!0)},this.on("authorizationchange",this._authFn,this,{single:!0}))},save:function(a,b){var c=Ext.util.JSON.encode(this.getState()), d,e;this.id?(d="PUT",e="../maps/"+this.id):(d="POST",e="../maps/");c={method:d,url:e,data:c};!1!==this.fireEvent("beforesave",c,a)&&OpenLayers.Request.issue(Ext.apply(c,{callback:function(c){this.handleSave(c);a&&a.call(b||this,c)},scope:this}))},handleSave:function(a){if(200==a.status){if(a=Ext.util.JSON.decode(a.responseText).id)this.id=a,a="#maps/"+a,!1!==this.fireEvent("beforehashchange",a)&&(window.location.hash=a),this.fireEvent("save",this.id)}else window.console&&console.warn(this.saveErrorText+ a.responseText)},destroy:function(){this.mapPanel.destroy();this.portal&&this.portal.destroy()}});(function(){OpenLayers.DOTS_PER_INCH=25.4/.28})();Ext.ns("gxp.data"); gxp.data.AutoCompleteReader=Ext.extend(GeoExt.data.FeatureReader,{read:function(a){var b=this.meta.uniqueField;this.features=[];for(var c=0,d=a.features.length;c<d;++c){var e=a.features[c];!1===this.isDuplicate(b,e.attributes[b])?this.features.push(e):e.destroy()}a.features=this.features;return gxp.data.AutoCompleteReader.superclass.read.apply(this,arguments)},isDuplicate:function(a,b){for(var c=0,d=this.features.length;c<d;++c)if(this.features[c].attributes[a]===b)return!0;return!1}});Ext.namespace("gxp.plugins"); gxp.plugins.WizardContainer={init:function(a){a.addEvents("wizardstepvalid","wizardstepinvalid","wizardstepexpanded");a.on("add",function(b){b.on("expand",function(){a.fireEvent("wizardstepexpanded",a.items.indexOf(b))})})}};Ext.preg("gxp_wizardcontainer",gxp.plugins.WizardContainer);Ext.namespace("gxp.grid"); gxp.grid.CapabilitiesGrid=Ext.extend(Ext.grid.GridPanel,{store:null,cm:null,expander:null,mapPanel:null,url:null,autoExpandColumn:"title",allowNewSources:!0,nameHeaderText:"Name",titleHeaderText:"Title",queryableHeaderText:"Queryable",layerSelectionLabel:"View available data from:",layerAdditionLabel:"or add a new server.",expanderTemplateText:"<p><b>Abstract:</b> {abstract}</p>",constructor:function(){this.addEvents("sourceselected");gxp.grid.CapabilitiesGrid.superclass.constructor.apply(this,arguments)}, initComponent:function(){this.store||(this.store=new GeoExt.data.WMSCapabilitiesStore({url:this.url+"?service=wms&request=GetCapabilities"}),this.store.load());this.on("afterrender",function(){this.fireEvent("sourceselected",this,this.store)},this);"expander"in this||(this.expander=new Ext.grid.RowExpander({tpl:new Ext.Template(this.expanderTemplateText)}));!this.plugins&&this.expander&&(this.plugins=this.expander);if(!this.cm){var a=[{id:"title",header:this.titleHeaderText,dataIndex:"title",sortable:!0}, {header:this.nameHeaderText,dataIndex:"name",width:180,sortable:!0},{header:this.queryableHeaderText,dataIndex:"queryable",width:70,renderer:function(a,b,e,f,g,h){b.css="x-btn";b="x-btn cancel";a&&(b="x-btn add");return'<div style="background-repeat: no-repeat; background-position: 50% 0%; height: 16px;" class="'+b+'">&nbsp;</div>'}}];this.expander&&a.unshift(this.expander);this.cm=new Ext.grid.ColumnModel(a)}"allowNewSources"in this||(this.allowNewSources=!!this.metaStore);if(this.allowNewSources|| this.metaStore&&1<this.metaStore.getCount())this.sourceComboBox=new Ext.form.ComboBox({store:this.metaStore,valueField:"identifier",displayField:"name",triggerAction:"all",editable:!1,allowBlank:!1,forceSelection:!0,mode:"local",value:this.metaStore.getAt(this.metaStore.findBy(function(a){return a.get("store")==this.store},this)).get("identifier"),listeners:{select:function(a,b,e){this.fireEvent("sourceselected",this,b.data.store);this.reconfigure(b.data.store,this.getColumnModel());this.expander&& (this.expander.ows=b.get("url"))},scope:this}}),this.metaStore.on("add",function(a,b,e){this.sourceComboBox.onSelect(b[0],e)},this),this.tbar=this.tbar||[],this.tbar.push(""+this.layerSelectionLabel),this.tbar.push(this.sourceComboBox);if(this.allowNewSources){var b=this;this.newSourceWindow||(this.newSourceWindow=new gxp.NewSourceWindow({modal:!0,metaStore:this.metaStore,addSource:function(){b.addSource.apply(b,arguments)}}));this.tbar.push(new Ext.Button({iconCls:"gxp-icon-addserver",text:this.layerAdditionLabel, handler:function(){this.newSourceWindow.show()},scope:this}))}gxp.grid.CapabilitiesGrid.superclass.initComponent.call(this)},addSource:function(a,b,c,d){d=d||this;c=new GeoExt.data.WMSCapabilitiesStore({url:a,autoLoad:!0});this.metaStore.add(new this.metaStore.recordType({url:a,store:c,identifier:a,name:a}));b.apply(d)},addLayers:function(a){var b=this.getSelectionModel().getSelections(),c,d;a=[];for(var e=0;e<b.length;e++)Ext.data.Record.AUTO_ID++,c=b[e].copy(Ext.data.Record.AUTO_ID),this.alignToGrid? (d=c.getLayer().clone(),d.maxExtent=new OpenLayers.Bounds(-180,-90,180,90)):(d=c.getLayer(),d instanceof OpenLayers.Layer.WMS&&(d=new OpenLayers.Layer.WMS(d.name,d.url,{layers:d.params.LAYERS},{attribution:d.attribution,maxExtent:OpenLayers.Bounds.fromArray(c.get("llbbox")).transform(new OpenLayers.Projection("EPSG:4326"),this.mapPanel.map.getProjectionObject())}))),c.data.layer=d,c.commit(!0),a.push(c);a.length&&(b=this.mapPanel.layers.findBy(function(a){return a.getLayer()instanceof OpenLayers.Layer.Vector}), -1!==b?this.mapPanel.layers.insert(b,a):this.mapPanel.layers.add(a))}});Ext.reg("gxp_capabilitiesgrid",gxp.grid.CapabilitiesGrid);Ext.namespace("gxp.plugins"); gxp.plugins.WMSFilterView=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_wmsfilterview",featureManager:null,init:function(a){gxp.plugins.WMSFilterView.superclass.init.apply(this,arguments);this.createFilterLayer()},createFilterLayer:function(){this.filterLayer=new OpenLayers.Layer.WMS(this.id+"filterlayer",Ext.BLANK_IMAGE_URL,{format:"image/png",transparent:!0},{buffer:0,displayInLayerSwitcher:!1,tileOptions:{maxGetUrlLength:2048}});var a=this.target.mapPanel.map;a.addLayer(this.filterLayer);a.events.on({addlayer:this.raiseLayer, scope:this});var b=this.target.tools[this.featureManager],c=new OpenLayers.Format.SLD,a=function(){this.filterLayer.setUrl(Ext.BLANK_IMAGE_URL);this.filterLayer.setVisibility(!1)}.bind(this);b.on({clearfeatures:a,beforelayerchange:a,beforequery:function(a,b){this.filterLayer.setUrl(Ext.BLANK_IMAGE_URL);this.filterLayer.setVisibility(!1)},query:function(a,e,f){if(f){e=new OpenLayers.Rule;var g=b.geometryType.replace(/^Multi/,""),h=b.style.all.rules[0].symbolizer;e.symbolizer[g]=Ext.applyIf(Ext.apply({}, h[g]||h),OpenLayers.Feature.Vector.style["default"]);e=new OpenLayers.Style(null,{rules:[e]});a=a.layerRecord.getLayer();this.filterLayer.setUrl(a.url);if(f instanceof OpenLayers.Filter.Logical){a=f.filters;for(g=a.length-1;0<=g;--g)a[g].type===OpenLayers.Filter.Spatial.BBOX&&a.remove(a[g]);1==a.length&&f.type!==OpenLayers.Filter.Comparison.NOT?f=a[0]:0==a.length&&(f=null)}else f.type===OpenLayers.Filter.Spatial.BBOX&&(f=null);a={};f&&(f instanceof OpenLayers.Filter.FeatureId?a.featureid=f.fids:a.cql_filter= (new OpenLayers.Format.CQL).write(f));this.filterLayer.mergeNewParams(Ext.apply(a,{sld_body:c.write({namedLayers:[{name:b.layerRecord.get("name"),userStyles:[e]}]}).replace(/( (xmlns|xsi):[^\"]*\"[^\"]*"|sld:)/g,"")}));this.filterLayer.setVisibility(!0)}},scope:this})},raiseLayer:function(){var a=this.filterLayer.map;a.setLayerIndex(this.filterLayer,a.layers.length)}});Ext.preg(gxp.plugins.WMSFilterView.prototype.ptype,gxp.plugins.WMSFilterView);Ext.namespace("gxp.slider"); gxp.slider.Tip=Ext.extend(Ext.slider.Tip,{hover:!0,dragging:!1,init:function(a){if(this.hover)a.on("render",this.registerThumbListeners,this);this.slider=a;gxp.slider.Tip.superclass.init.apply(this,arguments)},registerThumbListeners:function(){for(var a=0,b=this.slider.thumbs.length;a<b;++a)this.slider.thumbs[a].el.on({mouseover:this.createHoverListener(a),mouseout:function(){this.dragging||this.hide.apply(this,arguments)},scope:this})},createHoverListener:function(a){return function(){this.onSlide(this.slider, {},this.slider.thumbs[a]);this.dragging=!1}.createDelegate(this)},onSlide:function(a,b,c){this.dragging=!0;gxp.slider.Tip.superclass.onSlide.apply(this,arguments)}});Ext.namespace("gxp"); gxp.FilterBuilder=Ext.extend(Ext.Container,{builderTypeNames:["any","all","none","not all"],allowedBuilderTypes:null,allowBlank:!1,caseInsensitiveMatch:!1,preComboText:"Match",postComboText:"of the following:",cls:"gxp-filterbuilder",builderType:null,childFilterContainer:null,customizeFilterOnInit:!0,addConditionText:"add condition",addGroupText:"add group",removeConditionText:"remove condition",allowGroups:!0,initComponent:function(){Ext.applyIf(this,{defaultBuilderType:gxp.FilterBuilder.ANY_OF}); this.customizeFilterOnInit&&(this.filter=this.customizeFilter(this.filter));this.builderType=this.getBuilderType();this.items=[{xtype:"container",layout:"form",ref:"form",defaults:{anchor:"100%"},hideLabels:!0,items:[{xtype:"compositefield",style:"padding-left: 2px",items:[{xtype:"label",style:"padding-top: 0.3em",text:this.preComboText},this.createBuilderTypeCombo(),{xtype:"label",style:"padding-top: 0.3em",text:this.postComboText}]},this.createChildFiltersPanel(),{xtype:"toolbar",items:this.createToolBar()}]}]; this.addEvents("change");gxp.FilterBuilder.superclass.initComponent.call(this)},createToolBar:function(){var a=[{text:this.addConditionText,iconCls:"add",handler:function(){this.addCondition()},scope:this}];this.allowGroups&&a.push({text:this.addGroupText,iconCls:"add",handler:function(){this.addCondition(!0)},scope:this});return a},getFilter:function(){var a;this.filter&&(a=this.filter.clone(),a instanceof OpenLayers.Filter.Logical&&(a=this.cleanFilter(a)));return a},cleanFilter:function(a){if(a instanceof OpenLayers.Filter.Logical)if(a.type!==OpenLayers.Filter.Logical.NOT&&1===a.filters.length)a=this.cleanFilter(a.filters[0]);else for(var b,c=0,d=a.filters.length;c<d;++c)if(b=a.filters[c],b instanceof OpenLayers.Filter.Logical)if(b=this.cleanFilter(b))a.filters[c]=b;else{a=b;break}else{if(!b||null===b.type||null===b.property||null===b[a.type===OpenLayers.Filter.Comparison.BETWEEN?"lowerBoundary":"value"]){a=!1;break}}else a&&null!==a.type&&null!==a.property&&null!==a[a.type===OpenLayers.Filter.Comparison.BETWEEN? "lowerBoundary":"value"]||(a=!1);return a},customizeFilter:function(a){if(a){a=this.cleanFilter(a);var b,c,d;switch(a.type){case OpenLayers.Filter.Logical.AND:case OpenLayers.Filter.Logical.OR:if(a.filters&&0!==a.filters.length)for(c=0,d=a.filters.length;c<d;++c)b=a.filters[c],b instanceof OpenLayers.Filter.Logical&&(a.filters[c]=this.customizeFilter(b));else a.filters=[this.createDefaultFilter()];a=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.OR,filters:[a]});break;case OpenLayers.Filter.Logical.NOT:if(a.filters&& 0!==a.filters.length)if(b=a.filters[0],b instanceof OpenLayers.Filter.Logical)if(b.type!==OpenLayers.Filter.Logical.NOT){var e;c=0;for(d=b.filters.length;c<d;++c)e=b.filters[c],e instanceof OpenLayers.Filter.Logical&&(b.filters[c]=this.customizeFilter(e))}else a=b.filters&&0<b.filters.length?this.customizeFilter(b.filters[0]):this.wrapFilter(this.createDefaultFilter());else a.filters=[new OpenLayers.Filter.Logical({type:this.defaultBuilderType===gxp.FilterBuilder.NOT_ALL_OF?OpenLayers.Filter.Logical.AND: OpenLayers.Filter.Logical.OR,filters:[b]})];else a.filters=[new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.OR,filters:[this.createDefaultFilter()]})];break;default:a=this.wrapFilter(a)}}else a=this.wrapFilter(this.createDefaultFilter());return a},createDefaultFilter:function(){return new OpenLayers.Filter.Comparison({matchCase:!this.caseInsensitiveMatch})},wrapFilter:function(a){return new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.OR,filters:[new OpenLayers.Filter.Logical({type:this.defaultBuilderType=== gxp.FilterBuilder.ALL_OF?OpenLayers.Filter.Logical.AND:OpenLayers.Filter.Logical.OR,filters:[a]})]})},addCondition:function(a){var b,c;a?(c="gxp_filterbuilder",b=this.wrapFilter(this.createDefaultFilter())):(c="gxp_filterfield",b=this.createDefaultFilter());a=this.newRow({xtype:c,filter:b,columnWidth:1,attributes:this.attributes,allowBlank:a?void 0:this.allowBlank,customizeFilterOnInit:a&&!1,caseInsensitiveMatch:this.caseInsensitiveMatch,listeners:{change:function(){this.fireEvent("change",this)}, scope:this}});this.childFilterContainer.add(a);this.filter.filters[0].filters.push(b);this.childFilterContainer.doLayout()},removeCondition:function(a,b){var c=this.filter.filters[0].filters;0<c.length&&(c.remove(b),this.childFilterContainer.remove(a,!0));0===c.length&&this.addCondition();this.fireEvent("change",this)},createBuilderTypeCombo:function(){for(var a=this.allowedBuilderTypes||[gxp.FilterBuilder.ANY_OF,gxp.FilterBuilder.ALL_OF,gxp.FilterBuilder.NONE_OF],b=a.length,c=Array(b),d,e=0;e<b;++e)d= a[e],c[e]=[d,this.builderTypeNames[d]];return{xtype:"combo",store:new Ext.data.SimpleStore({data:c,fields:["value","name"]}),value:this.builderType,ref:"../../builderTypeCombo",displayField:"name",valueField:"value",triggerAction:"all",mode:"local",listeners:{select:function(a,b){this.changeBuilderType(b.get("value"));this.fireEvent("change",this)},scope:this},width:60}},changeBuilderType:function(a){if(a!==this.builderType){this.builderType=a;var b=this.filter.filters[0];switch(a){case gxp.FilterBuilder.ANY_OF:this.filter.type= OpenLayers.Filter.Logical.OR;b.type=OpenLayers.Filter.Logical.OR;break;case gxp.FilterBuilder.ALL_OF:this.filter.type=OpenLayers.Filter.Logical.OR;b.type=OpenLayers.Filter.Logical.AND;break;case gxp.FilterBuilder.NONE_OF:this.filter.type=OpenLayers.Filter.Logical.NOT;b.type=OpenLayers.Filter.Logical.OR;break;case gxp.FilterBuilder.NOT_ALL_OF:this.filter.type=OpenLayers.Filter.Logical.NOT,b.type=OpenLayers.Filter.Logical.AND}}},createChildFiltersPanel:function(){this.childFilterContainer=new Ext.Container; for(var a=this.filter.filters[0].filters,b,c=0,d=a.length;c<d;++c){b=a[c];var e={xtype:"gxp_filterfield",allowBlank:this.allowBlank,columnWidth:1,filter:b,attributes:this.attributes,listeners:{change:function(){this.fireEvent("change",this)},scope:this}};b=Ext.applyIf(b instanceof OpenLayers.Filter.Logical?{xtype:"gxp_filterbuilder"}:{xtype:"container",layout:"form",hideLabels:!0,items:e},e);this.childFilterContainer.add(this.newRow(b))}return this.childFilterContainer},newRow:function(a){var b=new Ext.Container({layout:"column", items:[{xtype:"container",width:28,height:26,style:"padding-left: 2px",items:{xtype:"button",tooltip:this.removeConditionText,iconCls:"delete",handler:function(c){this.removeCondition(b,a.filter)},scope:this}},a]});return b},getBuilderType:function(){var a=this.defaultBuilderType;if(this.filter){var b=this.filter.filters[0];if(this.filter.type===OpenLayers.Filter.Logical.NOT)switch(b.type){case OpenLayers.Filter.Logical.OR:a=gxp.FilterBuilder.NONE_OF;break;case OpenLayers.Filter.Logical.AND:a=gxp.FilterBuilder.NOT_ALL_OF}else switch(b.type){case OpenLayers.Filter.Logical.OR:a= gxp.FilterBuilder.ANY_OF;break;case OpenLayers.Filter.Logical.AND:a=gxp.FilterBuilder.ALL_OF}}return a},setFilter:function(a){this.filter=this.customizeFilter(a);this.changeBuilderType(this.getBuilderType());this.builderTypeCombo.setValue(this.builderType);this.form.remove(this.childFilterContainer);this.form.insert(1,this.createChildFiltersPanel());this.form.doLayout();this.fireEvent("change",this)}});gxp.FilterBuilder.ANY_OF=0;gxp.FilterBuilder.ALL_OF=1;gxp.FilterBuilder.NONE_OF=2; gxp.FilterBuilder.NOT_ALL_OF=3;Ext.reg("gxp_filterbuilder",gxp.FilterBuilder);Ext.ns("gxp.data");gxp.data.AutoCompleteProxy=Ext.extend(GeoExt.data.ProtocolProxy,{doRequest:function(a,b,c,d,e,f,g){c.query&&(c.filter=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.LIKE,matchCase:!1,property:this.protocol.propertyNames[0],value:"*"+c.query+"*"}),delete c.query);gxp.data.AutoCompleteProxy.superclass.doRequest.apply(this,arguments)}});Ext.namespace("gxp.plugins"); gxp.plugins.LayerProperties=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_layerproperties",menuText:"Layer Properties",toolTip:"Layer Properties",constructor:function(a){gxp.plugins.LayerProperties.superclass.constructor.apply(this,arguments);this.outputConfig||(this.outputConfig={width:325,autoHeight:!0})},addActions:function(){var a=gxp.plugins.LayerProperties.superclass.addActions.apply(this,[{menuText:this.menuText,iconCls:"gxp-icon-layerproperties",disabled:!0,tooltip:this.toolTip,handler:function(){this.removeOutput(); this.addOutput()},scope:this}]),b=a[0];this.target.on("layerselectionchange",function(a){b.setDisabled(!a||!a.get("properties"))},this);return a},addOutput:function(a){a=a||{};var b=this.target.selectedLayer;this.outputConfig.title=(this.initialConfig.outputConfig||{}).title||this.menuText+": "+b.get("title");this.outputConfig.shortTitle=b.get("title");var c=b.get("properties")||"gxp_layerpanel",d=this.layerPanelConfig;d&&d[c]&&Ext.apply(a,d[c]);a=gxp.plugins.LayerProperties.superclass.addOutput.call(this, Ext.apply({xtype:c,authorized:this.target.isAuthorized(),layerRecord:b,source:this.target.getSource(b),defaults:{style:"padding: 10px",autoHeight:this.outputConfig.autoHeight}},a));a.on({added:function(a){if(!this.outputTarget)a.on("afterrender",function(){a.ownerCt.ownerCt.center()},this,{single:!0})},scope:this});return a}});Ext.preg(gxp.plugins.LayerProperties.prototype.ptype,gxp.plugins.LayerProperties);Ext.namespace("gxp.plugins"); gxp.plugins.ZoomToDataExtent=Ext.extend(gxp.plugins.ZoomToExtent,{ptype:"gxp_zoomtodataextent",menuText:"Zoom to layer extent",tooltip:"Zoom to layer extent",closest:!1,iconCls:"gxp-icon-zoom-to",extent:function(){return this.target.tools[this.featureManager].featureLayer.getDataExtent()},addActions:function(){var a=gxp.plugins.ZoomToDataExtent.superclass.addActions.apply(this,arguments);a[0].disable();var b=this.target.tools[this.featureManager].featureLayer;b.events.on({featuresadded:function(){a[0].isDisabled()&& a[0].enable()},featuresremoved:function(){0==b.features.length&&a[0].disable()}});return a}});Ext.preg(gxp.plugins.ZoomToDataExtent.prototype.ptype,gxp.plugins.ZoomToDataExtent);Ext.namespace("gxp.plugins"); gxp.plugins.WMSGetFeatureInfo=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_wmsgetfeatureinfo",outputTarget:"map",popupCache:null,infoActionTip:"Get Feature Info",popupTitle:"Feature Info",buttonText:"Identify",format:"html",addActions:function(){this.popupCache={};var a=gxp.plugins.WMSGetFeatureInfo.superclass.addActions.call(this,[{tooltip:this.infoActionTip,iconCls:"gxp-icon-getfeatureinfo",buttonText:this.buttonText,toggleGroup:this.toggleGroup,enableToggle:!0,allowDepress:!0,toggleHandler:function(a, b){for(var d=0,h=c.controls.length;d<h;d++)b?c.controls[d].activate():c.controls[d].deactivate()}}]),b=this.actions[0].items[0],c={controls:[]},d=function(){for(var a=this.target.mapPanel.layers.queryBy(function(a){return a.get("queryable")}),d=this.target.mapPanel.map,g,h=0,k=c.controls.length;h<k;h++)g=c.controls[h],g.deactivate(),g.destroy();c.controls=[];a.each(function(a){var e=a.getLayer(),g=Ext.apply({},this.vendorParams),h;if(this.layerParams)for(var k=this.layerParams.length-1;0<=k;--k)h= this.layerParams[k].toUpperCase(),g[h]=e.params[h];var r=a.get("infoFormat");void 0===r&&(r="html"==this.format?"text/html":"application/vnd.ogc.gml");e=new OpenLayers.Control.WMSGetFeatureInfo(Ext.applyIf({url:e.url,queryVisible:!0,layers:[e],infoFormat:r,vendorParams:g,eventListeners:{getfeatureinfo:function(b){var c=a.get("title")||a.get("name");if("text/html"==r){var d=b.text.match(/<body[^>]*>([\s\S]*)<\/body>/);d&&!d[1].match(/^\s*$/)&&this.displayPopup(b,c,d[1])}else"text/plain"==r?this.displayPopup(b, c,"<pre>"+b.text+"</pre>"):b.features&&0<b.features.length&&this.displayPopup(b,c,null,a.get("getFeatureInfo"))},scope:this}},this.controlOptions));d.addControl(e);c.controls.push(e);b.pressed&&e.activate()},this)};this.target.mapPanel.layers.on("update",d,this);this.target.mapPanel.layers.on("add",d,this);this.target.mapPanel.layers.on("remove",d,this);return a},displayPopup:function(a,b,c,d){var e,f=a.xy.x+"."+a.xy.y;d=d||{};f in this.popupCache?e=this.popupCache[f]:(e=this.addOutput({xtype:"gx_popup", title:this.popupTitle,layout:"accordion",fill:!1,autoScroll:!0,location:a.xy,map:this.target.mapPanel,width:250,height:300,defaults:{layout:"fit",autoScroll:!0,autoHeight:!0,autoWidth:!0,collapsible:!0}}),e.on({close:function(a){return function(b){delete this.popupCache[a]}}(f),scope:this}),this.popupCache[f]=e);a=a.features;f=[];if(!c&&a)for(var g=0,h=a.length;g<h;++g)c=a[g],f.push(Ext.apply({xtype:"gxp_editorgrid",readOnly:!0,listeners:{beforeedit:function(a){return!1}},title:c.fid?c.fid:b,feature:c, fields:d.fields,propertyNames:d.propertyNames},this.itemConfig));else c&&f.push(Ext.apply({title:b,html:c},this.itemConfig));e.add(f);e.doLayout()}});Ext.preg(gxp.plugins.WMSGetFeatureInfo.prototype.ptype,gxp.plugins.WMSGetFeatureInfo);Ext.namespace("gxp.plugins"); gxp.plugins.GoogleSource=Ext.extend(gxp.plugins.LayerSource,{ptype:"gxp_googlesource",timeout:7E3,title:"Google Layers",roadmapAbstract:"Show street map",satelliteAbstract:"Show satellite imagery",hybridAbstract:"Show imagery with street names",terrainAbstract:"Show street map with terrain",otherParams:"sensor=false",constructor:function(a){this.config=a;gxp.plugins.GoogleSource.superclass.constructor.apply(this,arguments)},createStore:function(){gxp.plugins.GoogleSource.loader.onLoad({otherParams:this.otherParams, timeout:this.timeout,callback:this.syncCreateStore,errback:function(){delete this.store;this.fireEvent("failure",this,"The Google Maps script failed to load within the provided timeout ("+this.timeout/1E3+" s).")},scope:this})},syncCreateStore:function(){var a={ROADMAP:{"abstract":this.roadmapAbstract,MAX_ZOOM_LEVEL:20},SATELLITE:{"abstract":this.satelliteAbstract},HYBRID:{"abstract":this.hybridAbstract},TERRAIN:{"abstract":this.terrainAbstract,MAX_ZOOM_LEVEL:15}},b=[],c,d;for(c in a)d=google.maps.MapTypeId[c], b.push(new OpenLayers.Layer.Google("Google "+d.replace(/\w/,function(a){return a.toUpperCase()}),{type:d,typeName:c,MAX_ZOOM_LEVEL:a[c].MAX_ZOOM_LEVEL,maxExtent:new OpenLayers.Bounds(-2.003750834E7,-2.003750834E7,2.003750834E7,2.003750834E7),restrictedExtent:new OpenLayers.Bounds(-2.003750834E7,-2.003750834E7,2.003750834E7,2.003750834E7),projection:this.projection}));this.store=new GeoExt.data.LayerStore({layers:b,fields:[{name:"source",type:"string"},{name:"name",type:"string",mapping:"typeName"}, {name:"abstract",type:"string"},{name:"group",type:"string",defaultValue:"background"},{name:"fixed",type:"boolean",defaultValue:!0},{name:"selected",type:"boolean"}]});this.store.each(function(b){b.set("abstract",a[b.get("name")]["abstract"])});this.fireEvent("ready",this)},createLayerRecord:function(a){var b,c=function(b){return b.get("name")===a.name};-1==this.target.mapPanel.layers.findBy(c)&&(b=this.store.getAt(this.store.findBy(c)).clone(),c=b.getLayer(),a.title&&(c.setName(a.title),b.set("title", a.title)),"visibility"in a&&(c.visibility=a.visibility),b.set("selected",a.selected||!1),b.set("source",a.source),b.set("name",a.name),"group"in a&&b.set("group",a.group),b.commit());return b}}); gxp.plugins.GoogleSource.loader=new (Ext.extend(Ext.util.Observable,{ready:!(!window.google||!google.maps),loading:!1,constructor:function(){this.addEvents("ready","failure");return Ext.util.Observable.prototype.constructor.apply(this,arguments)},onScriptLoad:function(){var a=gxp.plugins.GoogleSource.loader;a.ready||(a.ready=!0,a.loading=!1,a.fireEvent("ready"))},onLoad:function(a){if(this.ready)window.setTimeout(function(){a.callback.call(a.scope)},0);else if(this.loading)this.on({ready:a.callback, failure:a.errback||Ext.emptyFn,scope:a.scope});else this.loadScript(a)},loadScript:function(a){function b(){document.getElementsByTagName("head")[0].appendChild(d)}var c={autoload:Ext.encode({modules:[{name:"maps",version:3.3,nocss:"true",callback:"gxp.plugins.GoogleSource.loader.onScriptLoad",other_params:a.otherParams}]})},d=document.createElement("script");d.src="//www.google.com/jsapi?"+Ext.urlEncode(c);var e=a.errback||Ext.emptyFn,c=a.timeout||gxp.plugins.GoogleSource.prototype.timeout;window.setTimeout(function(){gxp.plugins.GoogleSource.loader.ready|| (this.ready=this.loading=!1,document.getElementsByTagName("head")[0].removeChild(d),e.call(a.scope),this.fireEvent("failure"),this.purgeListeners())}.createDelegate(this),c);this.on({ready:a.callback,scope:a.scope});this.loading=!0;if(document.body)b();else Ext.onReady(b)}}));Ext.preg(gxp.plugins.GoogleSource.prototype.ptype,gxp.plugins.GoogleSource);Ext.namespace("gxp.form"); gxp.form.AutoCompleteComboBox=Ext.extend(Ext.form.ComboBox,{xtype:"gxp_autocompletecombo",fieldName:null,featureType:null,featurePrefix:null,fieldLabel:null,geometryName:null,maxFeatures:500,url:null,srsName:null,autoHeight:!0,hideTrigger:!0,customSortInfo:null,initComponent:function(){var a=[{name:this.fieldName}],b=[this.fieldName];null!==this.geometryName&&(a.push({name:this.geometryName}),b.push(this.geometryName));this.name||(this.name=this.fieldName);this.valueField=this.displayField=this.fieldName; this.tpl=new Ext.XTemplate('<tpl for="."><div class="x-form-field">',"{"+this.fieldName+"}","</div></tpl>");this.itemSelector="div.x-form-field";this.store=new Ext.data.Store({fields:a,reader:new gxp.data.AutoCompleteReader({uniqueField:this.fieldName},b),proxy:new gxp.data.AutoCompleteProxy({protocol:new OpenLayers.Protocol.WFS({version:"1.1.0",url:this.url,featureType:this.featureType,featurePrefix:this.featurePrefix,srsName:this.srsName,propertyNames:b,maxFeatures:this.maxFeatures}),setParamsAsOptions:!0}), sortInfo:this.customSortInfo&&{field:this.fieldName,direction:this.customSortInfo.direction}});this.customSortInfo&&(this.store.createSortFunction=this.createCustomSortFunction());return gxp.form.AutoCompleteComboBox.superclass.initComponent.apply(this,arguments)},createCustomSortFunction:function(){for(var a=new RegExp(this.customSortInfo.matcher),b=this.customSortInfo.parts.length,c=Array(b),d,e=0;e<b;++e)d=this.customSortInfo.parts[e],c[e]={index:e,sortType:Ext.data.SortTypes[d.sortType||"none"], order:d.order||0};c.sort(function(a,b){return a.order-b.order});return function(b,d){var e="DESC"==(d||"ASC").toUpperCase()?-1:1;return function(d,g){for(var m=d.data[b],q=g.data[b],n=a.exec(m)||[],s=a.exec(q)||[],r,t,v=0,w=c.length;v<w&&!(t=c[v],r=t.sortType(n[t.index+1]||m),t=t.sortType(s[t.index+1]||q),r=r>t?1:r<t?-1:0);++v);return e*r}}}});Ext.reg(gxp.form.AutoCompleteComboBox.prototype.xtype,gxp.form.AutoCompleteComboBox);Ext.namespace("gxp.plugins"); gxp.plugins.MapBoxSource=Ext.extend(gxp.plugins.LayerSource,{ptype:"gxp_mapboxsource",title:"MapBox Layers",blueMarbleTopoBathyJanTitle:"Blue Marble Topography & Bathymetry (January)",blueMarbleTopoBathyJulTitle:"Blue Marble Topography & Bathymetry (July)",blueMarbleTopoJanTitle:"Blue Marble Topography (January)",blueMarbleTopoJulTitle:"Blue Marble Topography (July)",controlRoomTitle:"Control Room",geographyClassTitle:"Geography Class",naturalEarthHypsoTitle:"Natural Earth Hypsometric",naturalEarthHypsoBathyTitle:"Natural Earth Hypsometric & Bathymetry", naturalEarth1Title:"Natural Earth I",naturalEarth2Title:"Natural Earth II",worldDarkTitle:"World Dark",worldLightTitle:"World Light",worldGlassTitle:"World Glass",worldPrintTitle:"World Print",createStore:function(){for(var a={projection:"EPSG:900913",numZoomLevels:19,serverResolutions:[156543.03390625,78271.516953125,39135.7584765625,19567.87923828125,9783.939619140625,4891.9698095703125,2445.9849047851562,1222.9924523925781,611.4962261962891,305.74811309814453,152.87405654907226,76.43702827453613, 38.218514137268066,19.109257068634033,9.554628534317017,4.777314267158508,2.388657133579254,1.194328566789627,.5971642833948135],buffer:1},b=[{name:"blue-marble-topo-bathy-jan",numZoomLevels:9},{name:"blue-marble-topo-bathy-jul",numZoomLevels:9},{name:"blue-marble-topo-jan",numZoomLevels:9},{name:"blue-marble-topo-jul",numZoomLevels:9},{name:"control-room",numZoomLevels:9},{name:"geography-class",numZoomLevels:9},{name:"natural-earth-hypso",numZoomLevels:7},{name:"natural-earth-hypso-bathy",numZoomLevels:7}, {name:"natural-earth-1",numZoomLevels:7},{name:"natural-earth-2",numZoomLevels:7},{name:"world-dark",numZoomLevels:12},{name:"world-light",numZoomLevels:12},{name:"world-glass",numZoomLevels:11},{name:"world-print",numZoomLevels:10}],c=b.length,d=Array(c),e,f=0;f<c;++f)e=b[f],d[f]=new OpenLayers.Layer.TMS(this[OpenLayers.String.camelize(e.name)+"Title"],["//a.tiles.mapbox.com/mapbox/","//b.tiles.mapbox.com/mapbox/","//c.tiles.mapbox.com/mapbox/","//d.tiles.mapbox.com/mapbox/"],OpenLayers.Util.applyDefaults({attribution:/^world/.test(name)? "<a href='http://mapbox.com'>MapBox</a> | Some Data &copy; OSM CC-BY-SA | <a href='http://mapbox.com/tos'>Terms of Service</a>":"<a href='http://mapbox.com'>MapBox</a> | <a href='http://mapbox.com/tos'>Terms of Service</a>",type:"png",tileOrigin:new OpenLayers.LonLat(-2.003750834E7,-2.003750834E7),layername:e.name,"abstract":'<div class="thumb-mapbox thumb-mapbox-'+e.name+'"></div>',numZoomLevels:e.numZoomLevels},a));this.store=new GeoExt.data.LayerStore({layers:d,fields:[{name:"source",type:"string"}, {name:"name",type:"string",mapping:"layername"},{name:"abstract",type:"string"},{name:"group",type:"string"},{name:"fixed",type:"boolean"},{name:"selected",type:"boolean"}]});this.fireEvent("ready",this)},createLayerRecord:function(a){var b,c=this.store.findExact("name",a.name);-1<c&&(b=this.store.getAt(c).copy(Ext.data.Record.id({})),c=b.getLayer().clone(),a.title&&(c.setName(a.title),b.set("title",a.title)),"visibility"in a&&(c.visibility=a.visibility),b.set("selected",a.selected||!1),b.set("source", a.source),b.set("name",a.name),"group"in a&&b.set("group",a.group),b.data.layer=c,b.commit());return b}});Ext.preg(gxp.plugins.MapBoxSource.prototype.ptype,gxp.plugins.MapBoxSource);Ext.namespace("gxp.plugins"); gxp.plugins.Styler=Ext.extend(gxp.plugins.Tool,{ptype:"gxp_styler",menuText:"Edit Styles",tooltip:"Manage layer styles",roles:["ROLE_ADMINISTRATOR"],sameOriginStyling:!0,rasterStyling:!1,requireDescribeLayer:!0,constructor:function(a){gxp.plugins.Styler.superclass.constructor.apply(this,arguments);this.outputConfig||(this.outputConfig={autoHeight:!0,width:265});Ext.applyIf(this.outputConfig,{closeAction:"close"})},init:function(a){gxp.plugins.Styler.superclass.init.apply(this,arguments);this.target.on("authorizationchange", this.enableOrDisable,this)},destroy:function(){this.target.un("authorizationchange",this.enableOrDisable,this);gxp.plugins.Styler.superclass.destroy.apply(this,arguments)},enableOrDisable:function(){this.target&&null!==this.target.selectedLayer&&this.handleLayerChange(this.target.selectedLayer)},addActions:function(){var a=gxp.plugins.Styler.superclass.addActions.apply(this,[{menuText:this.menuText,iconCls:"gxp-icon-palette",disabled:!0,tooltip:this.tooltip,handler:function(){this.target.doAuthorized(this.roles, this.addOutput,this)},scope:this}]);this.launchAction=a[0];this.target.on({layerselectionchange:this.handleLayerChange,scope:this});return a},handleLayerChange:function(a){this.launchAction.disable();if(a){var b=this.target.getSource(a);b instanceof gxp.plugins.WMSSource&&b.describeLayer(a,function(b){this.checkIfStyleable(a,b)},this)}},checkIfStyleable:function(a,b){if(b){var c=["WFS"];!0===this.rasterStyling&&c.push("WCS")}if(b?-1!==c.indexOf(b.get("owsType")):!this.requireDescribeLayer){var c= !1,c=this.target.layerSources[a.get("source")],d;d=(d=a.get("restUrl"))?d+"/styles":c.url.split("?").shift().replace(/\/(wms|ows)\/?$/,"/rest/styles");if(this.sameOriginStyling){if(c="/"===d.charAt(0),this.target.authenticate&&c){this.launchAction.enable();return}}else c=!0;c&&this.target.isAuthorized()&&this.enableActionIfAvailable(d)}},enableActionIfAvailable:function(a){Ext.Ajax.request({method:"PUT",url:a,callback:function(a,c,d){this.launchAction.setDisabled(405!==d.status)},scope:this})},addOutput:function(a){a= a||{};var b=this.target.selectedLayer;this.outputConfig.title=(this.initialConfig.outputConfig||{}).title||this.menuText+": "+b.get("title");this.outputConfig.shortTitle=b.get("title");Ext.apply(a,gxp.WMSStylesDialog.createGeoServerStylerConfig(b));!0===this.rasterStyling&&a.plugins.push({ptype:"gxp_wmsrasterstylesdialog"});Ext.applyIf(a,{style:"padding: 10px"});var c=gxp.plugins.Styler.superclass.addOutput.call(this,a);c.ownerCt.ownerCt instanceof Ext.Window||(c.dialogCls=Ext.Panel,c.showDlg=function(a){a.layout= "fit";a.autoHeight=!1;c.ownerCt.add(a)});c.stylesStore.on("load",function(){!this.outputTarget&&c.ownerCt.ownerCt instanceof Ext.Window&&c.ownerCt.ownerCt.center()})}});Ext.preg(gxp.plugins.Styler.prototype.ptype,gxp.plugins.Styler);
ajax/libs/vkui/4.23.0/components/View/ViewInfinite.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray"; import _objectSpread from "@babel/runtime/helpers/objectSpread2"; import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; import _createClass from "@babel/runtime/helpers/createClass"; import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized"; import _inherits from "@babel/runtime/helpers/inherits"; import _createSuper from "@babel/runtime/helpers/createSuper"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; var _excluded = ["popout", "modal", "platform", "activePanel", "splitCol", "configProvider", "history", "id", "nav", "onTransition", "onSwipeBack", "onSwipeBackStart", "onSwipeBackCancel", "window", "document", "scroll", "isBackCheck"]; import { createScopedElement } from "../../lib/jsxRuntime"; import * as React from 'react'; import { classNames } from "../../lib/classNames"; import { transitionEvent, animationEvent } from "../../lib/supportEvents"; import { getClassName } from "../../helpers/getClassName"; import { IOS, ANDROID, VKCOM } from "../../lib/platform"; import { Touch } from "../Touch/Touch"; import { withPlatform } from "../../hoc/withPlatform"; import { withContext } from "../../hoc/withContext"; import { ConfigProviderContext } from "../ConfigProvider/ConfigProviderContext"; import { SplitColContext } from "../SplitCol/SplitCol"; import { AppRootPortal } from "../AppRoot/AppRootPortal"; import { canUseDOM, withDOM } from "../../lib/dom"; import { ScrollContext } from "../AppRoot/ScrollContext"; import { NavTransitionProvider } from "../NavTransitionContext/NavTransitionContext"; import { getNavId } from "../../lib/getNavId"; import { warnOnce } from "../../lib/warnOnce"; import { swipeBackExcluded } from "./utils"; var warn = warnOnce('ViewInfinite'); var SwipeBackResults; (function (SwipeBackResults) { SwipeBackResults[SwipeBackResults["fail"] = 1] = "fail"; SwipeBackResults[SwipeBackResults["success"] = 2] = "success"; })(SwipeBackResults || (SwipeBackResults = {})); var scrollsCache = {}; var ViewInfinite = /*#__PURE__*/function (_React$Component) { _inherits(ViewInfinite, _React$Component); var _super = _createSuper(ViewInfinite); function ViewInfinite(props) { var _this; _classCallCheck(this, ViewInfinite); _this = _super.call(this, props); _defineProperty(_assertThisInitialized(_this), "scrolls", scrollsCache[getNavId(_this.props, warn)] || {}); _defineProperty(_assertThisInitialized(_this), "transitionFinishTimeout", void 0); _defineProperty(_assertThisInitialized(_this), "animationFinishTimeout", void 0); _defineProperty(_assertThisInitialized(_this), "panelNodes", {}); _defineProperty(_assertThisInitialized(_this), "transitionEndHandler", function (e) { if (!e || ['vkui-animation-ios-next-forward', 'vkui-animation-ios-prev-back', 'vkui-animation-view-next-forward', 'vkui-animation-view-prev-back'].includes(e.animationName)) { _this.flushTransition(_this.state.prevPanel, _this.state.isBack); } }); _defineProperty(_assertThisInitialized(_this), "swipingBackTransitionEndHandler", function (e) { // indexOf because of vendor prefixes in old browsers if (!e || e.propertyName.includes('transform') && e.target === _this.pickPanel(_this.state.swipeBackNextPanel)) { switch (_this.state.swipeBackResult) { case SwipeBackResults.fail: _this.onSwipeBackCancel(); break; case SwipeBackResults.success: _this.onSwipeBackSuccess(); } } }); _defineProperty(_assertThisInitialized(_this), "onMoveX", function (e) { if (swipeBackExcluded(e)) { return; } var _this$props = _this.props, platform = _this$props.platform, configProvider = _this$props.configProvider; if (platform === IOS && !configProvider.isWebView && (e.startX <= 70 || e.startX >= _this.window.innerWidth - 70) && !_this.state.browserSwipe) { _this.setState({ browserSwipe: true }); } if (platform === IOS && configProvider.isWebView && _this.props.onSwipeBack) { if (_this.state.animated && e.startX <= 70) { return; } if (e.startX <= 70 && !_this.state.swipingBack && _this.props.history.length > 1) { var prevScrolls = _this.scrolls[_this.state.activePanel] || []; _this.scrolls = _objectSpread(_objectSpread({}, _this.scrolls), {}, _defineProperty({}, _this.state.activePanel, [].concat(_toConsumableArray(prevScrolls), [_this.props.scroll.getScroll().y]))); _this.setState({ swipingBack: true, swipebackStartX: e.startX, swipeBackPrevPanel: _this.state.activePanel, swipeBackNextPanel: _this.props.history.slice(-2)[0] }); } if (_this.state.swipingBack) { var swipeBackShift; if (e.shiftX < 0) { swipeBackShift = 0; } else if (e.shiftX > _this.window.innerWidth - _this.state.swipebackStartX) { swipeBackShift = _this.window.innerWidth; } else { swipeBackShift = e.shiftX; } _this.setState({ swipeBackShift: swipeBackShift }); } } }); _defineProperty(_assertThisInitialized(_this), "onEnd", function (e) { if (_this.state.swipingBack) { var speed = _this.state.swipeBackShift / e.duration * 1000; if (_this.state.swipeBackShift === 0) { _this.onSwipeBackCancel(); } else if (_this.state.swipeBackShift >= _this.window.innerWidth) { _this.onSwipeBackSuccess(); } else if (speed > 250 || _this.state.swipebackStartX + _this.state.swipeBackShift > _this.window.innerWidth / 2) { _this.setState({ swipeBackResult: SwipeBackResults.success }); } else { _this.setState({ swipeBackResult: SwipeBackResults.fail }); } } }); _this.state = { animated: false, visiblePanels: [props.activePanel], activePanel: props.activePanel, isBack: undefined, prevPanel: null, nextPanel: null, swipingBack: false, swipebackStartX: 0, swipeBackShift: 0, swipeBackNextPanel: null, swipeBackPrevPanel: null, swipeBackResult: null, browserSwipe: false }; return _this; } _createClass(ViewInfinite, [{ key: "document", get: function get() { return this.props.document; } }, { key: "window", get: function get() { return this.props.window; } }, { key: "panels", get: function get() { return React.Children.toArray(this.props.children); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { var id = getNavId(this.props); if (id) { scrollsCache[id] = this.scrolls; } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { var _this2 = this; this.props.popout && !prevProps.popout && this.blurActiveElement(); this.props.modal && !prevProps.modal && this.blurActiveElement(); // Нужен переход if (prevProps.activePanel !== this.props.activePanel && !prevState.swipingBack && !prevState.browserSwipe) { var isBack = false; if (this.props.isBackCheck) { isBack = this.props.isBackCheck({ from: prevProps.activePanel, to: this.props.activePanel }); } else { var firstLayerId = this.panels.map(function (panel) { return getNavId(panel.props, warn); }).find(function (id) { return id === prevProps.activePanel || id === _this2.props.activePanel; }); isBack = firstLayerId === this.props.activePanel; } this.blurActiveElement(); var prevScrolls = this.scrolls[prevProps.activePanel] || []; var scrolls = _objectSpread(_objectSpread({}, this.scrolls), {}, _defineProperty({}, prevProps.activePanel, [].concat(_toConsumableArray(prevScrolls), [this.props.scroll.getScroll().y]))); this.scrolls = scrolls; if (this.shouldDisableTransitionMotion()) { this.flushTransition(prevProps.activePanel, isBack); } else { this.setState({ visiblePanels: [prevProps.activePanel, this.props.activePanel], prevPanel: prevProps.activePanel, nextPanel: this.props.activePanel, activePanel: null, animated: true, isBack: isBack }); // Фолбек анимации перехода if (!animationEvent.supported) { clearTimeout(this.animationFinishTimeout); this.animationFinishTimeout = setTimeout(this.transitionEndHandler, this.props.platform === ANDROID || this.props.platform === VKCOM ? 300 : 600); } } } // Закончилась анимация свайпа назад if (prevProps.activePanel !== this.props.activePanel && prevState.swipingBack) { var _objectSpread4; var nextPanel = this.state.swipeBackNextPanel; var prevPanel = this.state.swipeBackPrevPanel; var prevPanelScrolls = _toConsumableArray(this.scrolls[prevPanel] || []).slice(0, -1); var newPanelScrolls = _toConsumableArray(this.scrolls[nextPanel] || []); var scrollPosition = newPanelScrolls.pop(); this.scrolls = _objectSpread(_objectSpread({}, this.scrolls), {}, (_objectSpread4 = {}, _defineProperty(_objectSpread4, nextPanel, newPanelScrolls), _defineProperty(_objectSpread4, prevPanel, prevPanelScrolls), _objectSpread4)); this.setState({ swipeBackPrevPanel: null, swipeBackNextPanel: null, swipingBack: false, swipeBackResult: null, swipebackStartX: 0, swipeBackShift: 0, activePanel: nextPanel, visiblePanels: [nextPanel] }, function () { _this2.props.scroll.scrollTo(0, scrollPosition); prevProps.onTransition && prevProps.onTransition({ isBack: true, from: prevPanel, to: nextPanel }); }); } // Начался свайп назад if (!prevState.swipingBack && this.state.swipingBack) { this.props.onSwipeBackStart && this.props.onSwipeBackStart(); } // Началась анимация завершения свайпа назад. if (!prevState.swipeBackResult && this.state.swipeBackResult) { this.waitTransitionFinish(this.pickPanel(this.state.swipeBackNextPanel), this.swipingBackTransitionEndHandler); } // Если свайп назад отменился (когда пользователь недостаточно сильно свайпнул) if (prevState.swipeBackResult === SwipeBackResults.fail && !this.state.swipeBackResult) { var _newPanelScrolls = _toConsumableArray(this.scrolls[this.state.activePanel] || []); var _scrollPosition = _newPanelScrolls.pop(); this.scrolls = _objectSpread(_objectSpread({}, this.scrolls), {}, _defineProperty({}, this.state.activePanel, _newPanelScrolls)); this.props.scroll.scrollTo(0, _scrollPosition); } // Закончился Safari свайп if (prevProps.activePanel !== this.props.activePanel && this.state.browserSwipe) { this.setState({ browserSwipe: false, nextPanel: null, prevPanel: null, animated: false, visiblePanels: [this.props.activePanel], activePanel: this.props.activePanel }); } } }, { key: "shouldDisableTransitionMotion", value: function shouldDisableTransitionMotion() { return this.props.configProvider.transitionMotionEnabled === false || !this.props.splitCol.animate; } }, { key: "waitTransitionFinish", value: function waitTransitionFinish(elem, eventHandler) { if (transitionEvent.supported) { elem.removeEventListener(transitionEvent.name, eventHandler); elem.addEventListener(transitionEvent.name, eventHandler); } else { clearTimeout(this.transitionFinishTimeout); this.transitionFinishTimeout = setTimeout(eventHandler, this.props.platform === ANDROID || this.props.platform === VKCOM ? 300 : 600); } } }, { key: "blurActiveElement", value: function blurActiveElement() { if (typeof this.window !== 'undefined' && this.document.activeElement) { this.document.activeElement.blur(); } } }, { key: "pickPanel", value: function pickPanel(id) { return this.panelNodes[id]; } }, { key: "flushTransition", value: function flushTransition(prevPanel, isBack) { var _this3 = this; var activePanel = this.props.activePanel; var prevPanelScrolls = _toConsumableArray(this.scrolls[prevPanel] || []).slice(0, -1); var newPanelScrolls = _toConsumableArray(this.scrolls[activePanel] || []); var scrollPosition = isBack ? newPanelScrolls.pop() : 0; if (isBack) { var _objectSpread6; this.scrolls = _objectSpread(_objectSpread({}, this.scrolls), {}, (_objectSpread6 = {}, _defineProperty(_objectSpread6, prevPanel, prevPanelScrolls), _defineProperty(_objectSpread6, activePanel, newPanelScrolls), _objectSpread6)); } this.setState({ prevPanel: null, nextPanel: null, visiblePanels: [activePanel], activePanel: activePanel, animated: false, isBack: undefined }, function () { _this3.props.scroll.scrollTo(0, isBack ? scrollPosition : 0); _this3.props.onTransition && _this3.props.onTransition({ isBack: isBack, from: prevPanel, to: activePanel }); }); } }, { key: "onSwipeBackSuccess", value: function onSwipeBackSuccess() { this.props.onSwipeBack && this.props.onSwipeBack(); } }, { key: "onSwipeBackCancel", value: function onSwipeBackCancel() { this.props.onSwipeBackCancel && this.props.onSwipeBackCancel(); this.setState({ swipeBackPrevPanel: null, swipeBackNextPanel: null, swipingBack: false, swipeBackResult: null, swipebackStartX: 0, swipeBackShift: 0 }); } }, { key: "calcPanelSwipeStyles", value: function calcPanelSwipeStyles(panelId) { if (!canUseDOM) { return {}; } var isPrev = panelId === this.state.swipeBackPrevPanel; var isNext = panelId === this.state.swipeBackNextPanel; if (!isPrev && !isNext || this.state.swipeBackResult) { return {}; } var prevPanelTranslate = "".concat(this.state.swipeBackShift, "px"); var nextPanelTranslate = "".concat(-50 + this.state.swipeBackShift * 100 / this.window.innerWidth / 2, "%"); var prevPanelShadow = 0.3 * (this.window.innerWidth - this.state.swipeBackShift) / this.window.innerWidth; if (this.state.swipeBackResult) { return isPrev ? { boxShadow: "-2px 0 12px rgba(0, 0, 0, ".concat(prevPanelShadow, ")") } : {}; } if (isNext) { return { transform: "translate3d(".concat(nextPanelTranslate, ", 0, 0)"), WebkitTransform: "translate3d(".concat(nextPanelTranslate, ", 0, 0)") }; } if (isPrev) { return { transform: "translate3d(".concat(prevPanelTranslate, ", 0, 0)"), WebkitTransform: "translate3d(".concat(prevPanelTranslate, ", 0, 0)"), boxShadow: "-2px 0 12px rgba(0, 0, 0, ".concat(prevPanelShadow, ")") }; } return {}; } }, { key: "render", value: function render() { var _this4 = this; var _this$props2 = this.props, popout = _this$props2.popout, modal = _this$props2.modal, platform = _this$props2.platform, _1 = _this$props2.activePanel, splitCol = _this$props2.splitCol, configProvider = _this$props2.configProvider, history = _this$props2.history, id = _this$props2.id, nav = _this$props2.nav, onTransition = _this$props2.onTransition, onSwipeBack = _this$props2.onSwipeBack, onSwipeBackStart = _this$props2.onSwipeBackStart, onSwipeBackCancel = _this$props2.onSwipeBackCancel, window = _this$props2.window, document = _this$props2.document, scroll = _this$props2.scroll, isBackCheck = _this$props2.isBackCheck, restProps = _objectWithoutProperties(_this$props2, _excluded); var _this$state = this.state, prevPanel = _this$state.prevPanel, nextPanel = _this$state.nextPanel, activePanel = _this$state.activePanel, isBack = _this$state.isBack, animated = _this$state.animated, swipeBackPrevPanel = _this$state.swipeBackPrevPanel, swipeBackNextPanel = _this$state.swipeBackNextPanel, swipeBackResult = _this$state.swipeBackResult, swipingBack = _this$state.swipingBack; var hasPopout = !!popout; var hasModal = !!modal; var panels = this.panels.filter(function (panel) { var panelId = getNavId(panel.props, warn); return _this4.state.visiblePanels.includes(panelId) || panelId === swipeBackPrevPanel || panelId === swipeBackNextPanel; }).sort(function (panel) { var panelId = getNavId(panel.props, warn); var isPrevPanel = panelId === prevPanel || panelId === swipeBackPrevPanel; var isNextPanel = panelId === nextPanel || panelId === swipeBackNextPanel; if (isNextPanel) { return swipingBack || _this4.state.isBack ? -1 : 1; } if (isPrevPanel) { return swipingBack || _this4.state.isBack ? 1 : -1; } return 0; }); var disableAnimation = this.shouldDisableTransitionMotion(); var modifiers = { 'View--animated': !disableAnimation && this.state.animated, 'View--swiping-back': !disableAnimation && this.state.swipingBack, 'View--no-motion': disableAnimation }; return createScopedElement(Touch, _extends({ Component: "section" }, restProps, { vkuiClass: classNames(getClassName('View', platform), modifiers), onMoveX: this.onMoveX, onEnd: this.onEnd }), createScopedElement("div", { vkuiClass: "View__panels" }, panels.map(function (panel) { var panelId = getNavId(panel.props, warn); var isPrev = panelId === prevPanel || panelId === swipeBackPrevPanel; var compensateScroll = isPrev || panelId === swipeBackNextPanel || panelId === nextPanel && isBack; var isTransitionTarget = animated && panelId === (isBack ? prevPanel : nextPanel); var scrollList = _this4.scrolls[panelId] || []; var scroll = scrollList[scrollList.length - 1] || 0; return createScopedElement("div", { vkuiClass: classNames('View__panel', { 'View__panel--active': panelId === activePanel, 'View__panel--prev': panelId === prevPanel, 'View__panel--next': panelId === nextPanel, 'View__panel--swipe-back-prev': panelId === swipeBackPrevPanel, 'View__panel--swipe-back-next': panelId === swipeBackNextPanel, 'View__panel--swipe-back-success': swipeBackResult === SwipeBackResults.success, 'View__panel--swipe-back-failed': swipeBackResult === SwipeBackResults.fail }), onAnimationEnd: isTransitionTarget ? _this4.transitionEndHandler : null, ref: function ref(el) { return _this4.panelNodes[panelId] = el; }, style: _this4.calcPanelSwipeStyles(panelId), key: panelId }, createScopedElement("div", { vkuiClass: "View__panel-in", style: { marginTop: compensateScroll ? -scroll : null } }, createScopedElement(NavTransitionProvider, { entering: panelId === nextPanel || panelId === swipeBackNextPanel }, panel))); })), createScopedElement(AppRootPortal, null, hasPopout && createScopedElement("div", { vkuiClass: "View__popout" }, popout), hasModal && createScopedElement("div", { vkuiClass: "View__modal" }, modal))); } }]); return ViewInfinite; }(React.Component); _defineProperty(ViewInfinite, "defaultProps", { history: [] }); export default withContext(withContext(withContext(withPlatform(withDOM(ViewInfinite)), SplitColContext, 'splitCol'), ConfigProviderContext, 'configProvider'), ScrollContext, 'scroll'); //# sourceMappingURL=ViewInfinite.js.map
ajax/libs/yui/3.8.0pr1/datatable-core/datatable-core.js
sreym/cdnjs
YUI.add('datatable-core', function (Y, NAME) { /** The core implementation of the `DataTable` and `DataTable.Base` Widgets. @module datatable @submodule datatable-core @since 3.5.0 **/ var INVALID = Y.Attribute.INVALID_VALUE, Lang = Y.Lang, isFunction = Lang.isFunction, isObject = Lang.isObject, isArray = Lang.isArray, isString = Lang.isString, isNumber = Lang.isNumber, toArray = Y.Array, keys = Y.Object.keys, Table; /** _API docs for this extension are included in the DataTable class._ Class extension providing the core API and structure for the DataTable Widget. Use this class extension with Widget or another Base-based superclass to create the basic DataTable model API and composing class structure. @class DataTable.Core @for DataTable @since 3.5.0 **/ Table = Y.namespace('DataTable').Core = function () {}; Table.ATTRS = { /** Columns to include in the rendered table. If omitted, the attributes on the configured `recordType` or the first item in the `data` collection will be used as a source. This attribute takes an array of strings or objects (mixing the two is fine). Each string or object is considered a column to be rendered. Strings are converted to objects, so `columns: ['first', 'last']` becomes `columns: [{ key: 'first' }, { key: 'last' }]`. DataTable.Core only concerns itself with a few properties of columns. These properties are: * `key` - Used to identify the record field/attribute containing content for this column. Also used to create a default Model if no `recordType` or `data` are provided during construction. If `name` is not specified, this is assigned to the `_id` property (with added incrementer if the key is used by multiple columns). * `children` - Traversed to initialize nested column objects * `name` - Used in place of, or in addition to, the `key`. Useful for columns that aren't bound to a field/attribute in the record data. This is assigned to the `_id` property. * `id` - For backward compatibility. Implementers can specify the id of the header cell. This should be avoided, if possible, to avoid the potential for creating DOM elements with duplicate IDs. * `field` - For backward compatibility. Implementers should use `name`. * `_id` - Assigned unique-within-this-instance id for a column. By order of preference, assumes the value of `name`, `key`, `id`, or `_yuid`. This is used by the rendering views as well as feature module as a means to identify a specific column without ambiguity (such as multiple columns using the same `key`. * `_yuid` - Guid stamp assigned to the column object. * `_parent` - Assigned to all child columns, referencing their parent column. @attribute columns @type {Object[]|String[]} @default (from `recordType` ATTRS or first item in the `data`) @since 3.5.0 **/ columns: { // TODO: change to setter to clone input array/objects validator: isArray, setter: '_setColumns', getter: '_getColumns' }, /** Model subclass to use as the `model` for the ModelList stored in the `data` attribute. If not provided, it will try really hard to figure out what to use. The following attempts will be made to set a default value: 1. If the `data` attribute is set with a ModelList instance and its `model` property is set, that will be used. 2. If the `data` attribute is set with a ModelList instance, and its `model` property is unset, but it is populated, the `ATTRS` of the `constructor of the first item will be used. 3. If the `data` attribute is set with a non-empty array, a Model subclass will be generated using the keys of the first item as its `ATTRS` (see the `_createRecordClass` method). 4. If the `columns` attribute is set, a Model subclass will be generated using the columns defined with a `key`. This is least desirable because columns can be duplicated or nested in a way that's not parsable. 5. If neither `data` nor `columns` is set or populated, a change event subscriber will listen for the first to be changed and try all over again. @attribute recordType @type {Function} @default (see description) @since 3.5.0 **/ recordType: { getter: '_getRecordType', setter: '_setRecordType' }, /** The collection of data records to display. This attribute is a pass through to a `data` property, which is a ModelList instance. If this attribute is passed a ModelList or subclass, it will be assigned to the property directly. If an array of objects is passed, a new ModelList will be created using the configured `recordType` as its `model` property and seeded with the array. Retrieving this attribute will return the ModelList stored in the `data` property. @attribute data @type {ModelList|Object[]} @default `new ModelList()` @since 3.5.0 **/ data: { valueFn: '_initData', setter : '_setData', lazyAdd: false }, /** Content for the `<table summary="ATTRIBUTE VALUE HERE">`. Values assigned to this attribute will be HTML escaped for security. @attribute summary @type {String} @default '' (empty string) @since 3.5.0 **/ //summary: {}, /** HTML content of an optional `<caption>` element to appear above the table. Leave this config unset or set to a falsy value to remove the caption. @attribute caption @type HTML @default '' (empty string) @since 3.5.0 **/ //caption: {}, /** Deprecated as of 3.5.0. Passes through to the `data` attribute. WARNING: `get('recordset')` will NOT return a Recordset instance as of 3.5.0. This is a break in backward compatibility. @attribute recordset @type {Object[]|Recordset} @deprecated Use the `data` attribute @since 3.5.0 **/ recordset: { setter: '_setRecordset', getter: '_getRecordset', lazyAdd: false }, /** Deprecated as of 3.5.0. Passes through to the `columns` attribute. WARNING: `get('columnset')` will NOT return a Columnset instance as of 3.5.0. This is a break in backward compatibility. @attribute columnset @type {Object[]} @deprecated Use the `columns` attribute @since 3.5.0 **/ columnset: { setter: '_setColumnset', getter: '_getColumnset', lazyAdd: false } }; Y.mix(Table.prototype, { // -- Instance properties ------------------------------------------------- /** The ModelList that manages the table's data. @property data @type {ModelList} @default undefined (initially unset) @since 3.5.0 **/ //data: null, // -- Public methods ------------------------------------------------------ /** Gets the column configuration object for the given key, name, or index. For nested columns, `name` can be an array of indexes, each identifying the index of that column in the respective parent's "children" array. If you pass a column object, it will be returned. For columns with keys, you can also fetch the column with `instance.get('columns.foo')`. @method getColumn @param {String|Number|Number[]} name Key, "name", index, or index array to identify the column @return {Object} the column configuration object @since 3.5.0 **/ getColumn: function (name) { var col, columns, i, len, cols; if (isObject(name) && !isArray(name)) { // TODO: support getting a column from a DOM node - this will cross // the line into the View logic, so it should be relayed // Assume an object passed in is already a column def col = name; } else { col = this.get('columns.' + name); } if (col) { return col; } columns = this.get('columns'); if (isNumber(name) || isArray(name)) { name = toArray(name); cols = columns; for (i = 0, len = name.length - 1; cols && i < len; ++i) { cols = cols[name[i]] && cols[name[i]].children; } return (cols && cols[name[i]]) || null; } return null; }, /** Returns the Model associated to the record `id`, `clientId`, or index (not row index). If none of those yield a Model from the `data` ModelList, the arguments will be passed to the `view` instance's `getRecord` method if it has one. If no Model can be found, `null` is returned. @method getRecord @param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or identifier for a row or child element @return {Model} @since 3.5.0 **/ getRecord: function (seed) { var record = this.data.getById(seed) || this.data.getByClientId(seed); if (!record) { if (isNumber(seed)) { record = this.data.item(seed); } // TODO: this should be split out to base somehow if (!record && this.view && this.view.getRecord) { record = this.view.getRecord.apply(this.view, arguments); } } return record || null; }, // -- Protected and private properties and methods ------------------------ /** This tells `Y.Base` that it should create ad-hoc attributes for config properties passed to DataTable's constructor. This is useful for setting configurations on the DataTable that are intended for the rendering View(s). @property _allowAdHocAttrs @type Boolean @default true @protected @since 3.6.0 **/ _allowAdHocAttrs: true, /** A map of column key to column configuration objects parsed from the `columns` attribute. @property _columnMap @type {Object} @default undefined (initially unset) @protected @since 3.5.0 **/ //_columnMap: null, /** The Node instance of the table containing the data rows. This is set when the table is rendered. It may also be set by progressive enhancement, though this extension does not provide the logic to parse from source. @property _tableNode @type {Node} @default undefined (initially unset) @protected @since 3.5.0 **/ //_tableNode: null, /** Updates the `_columnMap` property in response to changes in the `columns` attribute. @method _afterColumnsChange @param {EventFacade} e The `columnsChange` event object @protected @since 3.5.0 **/ _afterColumnsChange: function (e) { this._setColumnMap(e.newVal); }, /** Updates the `modelList` attributes of the rendered views in response to the `data` attribute being assigned a new ModelList. @method _afterDataChange @param {EventFacade} e the `dataChange` event @protected @since 3.5.0 **/ _afterDataChange: function (e) { var modelList = e.newVal; this.data = e.newVal; if (!this.get('columns') && modelList.size()) { // TODO: this will cause a re-render twice because the Views are // subscribed to columnsChange this._initColumns(); } }, /** Assigns to the new recordType as the model for the data ModelList @method _afterRecordTypeChange @param {EventFacade} e recordTypeChange event @protected @since 3.6.0 **/ _afterRecordTypeChange: function (e) { var data = this.data.toJSON(); this.data.model = e.newVal; this.data.reset(data); if (!this.get('columns') && data) { if (data.length) { this._initColumns(); } else { this.set('columns', keys(e.newVal.ATTRS)); } } }, /** Creates a Model subclass from an array of attribute names or an object of attribute definitions. This is used to generate a class suitable to represent the data passed to the `data` attribute if no `recordType` is set. @method _createRecordClass @param {String[]|Object} attrs Names assigned to the Model subclass's `ATTRS` or its entire `ATTRS` definition object @return {Model} @protected @since 3.5.0 **/ _createRecordClass: function (attrs) { var ATTRS, i, len; if (isArray(attrs)) { ATTRS = {}; for (i = 0, len = attrs.length; i < len; ++i) { ATTRS[attrs[i]] = {}; } } else if (isObject(attrs)) { ATTRS = attrs; } return Y.Base.create('record', Y.Model, [], null, { ATTRS: ATTRS }); }, /** Tears down the instance. @method destructor @protected @since 3.6.0 **/ destructor: function () { new Y.EventHandle(Y.Object.values(this._eventHandles)).detach(); }, /** The getter for the `columns` attribute. Returns the array of column configuration objects if `instance.get('columns')` is called, or the specific column object if `instance.get('columns.columnKey')` is called. @method _getColumns @param {Object[]} columns The full array of column objects @param {String} name The attribute name requested (e.g. 'columns' or 'columns.foo'); @protected @since 3.5.0 **/ _getColumns: function (columns, name) { // Workaround for an attribute oddity (ticket #2529254) // getter is expected to return an object if get('columns.foo') is called. // Note 'columns.' is 8 characters return name.length > 8 ? this._columnMap : columns; }, /** Relays the `get()` request for the deprecated `columnset` attribute to the `columns` attribute. THIS BREAKS BACKWARD COMPATIBILITY. 3.4.1 and prior implementations will expect a Columnset instance returned from `get('columnset')`. @method _getColumnset @param {Object} ignored The current value stored in the `columnset` state @param {String} name The attribute name requested (e.g. 'columnset' or 'columnset.foo'); @deprecated This will be removed with the `columnset` attribute in a future version. @protected @since 3.5.0 **/ _getColumnset: function (_, name) { return this.get(name.replace(/^columnset/, 'columns')); }, /** Returns the Model class of the instance's `data` attribute ModelList. If not set, returns the explicitly configured value. @method _getRecordType @param {Model} val The currently configured value @return {Model} **/ _getRecordType: function (val) { // Prefer the value stored in the attribute because the attribute // change event defaultFn sets e.newVal = this.get('recordType') // before notifying the after() subs. But if this getter returns // this.data.model, then after() subs would get e.newVal === previous // model before _afterRecordTypeChange can set // this.data.model = e.newVal return val || (this.data && this.data.model); }, /** Initializes the `_columnMap` property from the configured `columns` attribute. If `columns` is not set, but there are records in the `data` ModelList, use `ATTRS` of that class. @method _initColumns @protected @since 3.5.0 **/ _initColumns: function () { var columns = this.get('columns') || [], item; // Default column definition from the configured recordType if (!columns.length && this.data.size()) { // TODO: merge superclass attributes up to Model? item = this.data.item(0); if (item.toJSON) { item = item.toJSON(); } this.set('columns', keys(item)); } this._setColumnMap(columns); }, /** Sets up the change event subscriptions to maintain internal state. @method _initCoreEvents @protected @since 3.6.0 **/ _initCoreEvents: function () { this._eventHandles.coreAttrChanges = this.after({ columnsChange : Y.bind('_afterColumnsChange', this), recordTypeChange: Y.bind('_afterRecordTypeChange', this), dataChange : Y.bind('_afterDataChange', this) }); }, /** Defaults the `data` attribute to an empty ModelList if not set during construction. Uses the configured `recordType` for the ModelList's `model` proeprty if set. @method _initData @protected @return {ModelList} @since 3.6.0 **/ _initData: function () { var recordType = this.get('recordType'), // TODO: LazyModelList if recordType doesn't have complex ATTRS modelList = new Y.ModelList(); if (recordType) { modelList.model = recordType; } return modelList; }, /** Initializes the instance's `data` property from the value of the `data` attribute. If the attribute value is a ModelList, it is assigned directly to `this.data`. If it is an array, a ModelList is created, its `model` property is set to the configured `recordType` class, and it is seeded with the array data. This ModelList is then assigned to `this.data`. @method _initDataProperty @param {Array|ModelList|ArrayList} data Collection of data to populate the DataTable @protected @since 3.6.0 **/ _initDataProperty: function (data) { var recordType; if (!this.data) { recordType = this.get('recordType'); if (data && data.each && data.toJSON) { this.data = data; if (recordType) { this.data.model = recordType; } } else { // TODO: customize the ModelList or read the ModelList class // from a configuration option? this.data = new Y.ModelList(); if (recordType) { this.data.model = recordType; } } // TODO: Replace this with an event relay for specific events. // Using bubbling causes subscription conflicts with the models' // aggregated change event and 'change' events from DOM elements // inside the table (via Widget UI event). this.data.addTarget(this); } }, /** Initializes the columns, `recordType` and data ModelList. @method initializer @param {Object} config Configuration object passed to constructor @protected @since 3.5.0 **/ initializer: function (config) { var data = config.data, columns = config.columns, recordType; // Referencing config.data to allow _setData to be more stringent // about its behavior this._initDataProperty(data); // Default columns from recordType ATTRS if recordType is supplied at // construction. If no recordType is supplied, but the data is // supplied as a non-empty array, use the keys of the first item // as the columns. if (!columns) { recordType = (config.recordType || config.data === this.data) && this.get('recordType'); if (recordType) { columns = keys(recordType.ATTRS); } else if (isArray(data) && data.length) { columns = keys(data[0]); } if (columns) { this.set('columns', columns); } } this._initColumns(); this._eventHandles = {}; this._initCoreEvents(); }, /** Iterates the array of column configurations to capture all columns with a `key` property. An map is built with column keys as the property name and the corresponding column object as the associated value. This map is then assigned to the instance's `_columnMap` property. @method _setColumnMap @param {Object[]|String[]} columns The array of column config objects @protected @since 3.6.0 **/ _setColumnMap: function (columns) { var map = {}; function process(cols) { var i, len, col, key; for (i = 0, len = cols.length; i < len; ++i) { col = cols[i]; key = col.key; // First in wins for multiple columns with the same key // because the first call to genId (in _setColumns) will // return the same key, which will then be overwritten by the // subsequent same-keyed column. So table.getColumn(key) would // return the last same-keyed column. if (key && !map[key]) { map[key] = col; } //TODO: named columns can conflict with keyed columns map[col._id] = col; if (col.children) { process(col.children); } } } process(columns); this._columnMap = map; }, /** Translates string columns into objects with that string as the value of its `key` property. All columns are assigned a `_yuid` stamp and `_id` property corresponding to the column's configured `name` or `key` property with any spaces replaced with dashes. If the same `name` or `key` appears in multiple columns, subsequent appearances will have their `_id` appended with an incrementing number (e.g. if column "foo" is included in the `columns` attribute twice, the first will get `_id` of "foo", and the second an `_id` of "foo1"). Columns that are children of other columns will have the `_parent` property added, assigned the column object to which they belong. @method _setColumns @param {null|Object[]|String[]} val Array of config objects or strings @return {null|Object[]} @protected **/ _setColumns: function (val) { var keys = {}, known = [], knownCopies = [], arrayIndex = Y.Array.indexOf; function copyObj(o) { var copy = {}, key, val, i; known.push(o); knownCopies.push(copy); for (key in o) { if (o.hasOwnProperty(key)) { val = o[key]; if (isArray(val)) { copy[key] = val.slice(); } else if (isObject(val, true)) { i = arrayIndex(val, known); copy[key] = i === -1 ? copyObj(val) : knownCopies[i]; } else { copy[key] = o[key]; } } } return copy; } function genId(name) { // Sanitize the name for use in generated CSS classes. // TODO: is there more to do for other uses of _id? name = name.replace(/\s+/, '-'); if (keys[name]) { name += (keys[name]++); } else { keys[name] = 1; } return name; } function process(cols, parent) { var columns = [], i, len, col, yuid; for (i = 0, len = cols.length; i < len; ++i) { columns[i] = // chained assignment col = isString(cols[i]) ? { key: cols[i] } : copyObj(cols[i]); yuid = Y.stamp(col); // For backward compatibility if (!col.id) { // Implementers can shoot themselves in the foot by setting // this config property to a non-unique value col.id = yuid; } if (col.field) { // Field is now known as "name" to avoid confusion with data // fields or schema.resultFields col.name = col.field; } if (parent) { col._parent = parent; } else { delete col._parent; } // Unique id based on the column's configured name or key, // falling back to the yuid. Duplicates will have a counter // added to the end. col._id = genId(col.name || col.key || col.id); if (isArray(col.children)) { col.children = process(col.children, col); } } return columns; } return val && process(val); }, /** Relays attribute assignments of the deprecated `columnset` attribute to the `columns` attribute. If a Columnset is object is passed, its basic object structure is mined. @method _setColumnset @param {Array|Columnset} val The columnset value to relay @deprecated This will be removed with the deprecated `columnset` attribute in a later version. @protected @since 3.5.0 **/ _setColumnset: function (val) { this.set('columns', val); return isArray(val) ? val : INVALID; }, /** Accepts an object with `each` and `getAttrs` (preferably a ModelList or subclass) or an array of data objects. If an array is passes, it will create a ModelList to wrap the data. In doing so, it will set the created ModelList's `model` property to the class in the `recordType` attribute, which will be defaulted if not yet set. If the `data` property is already set with a ModelList, passing an array as the value will call the ModelList's `reset()` method with that array rather than replacing the stored ModelList wholesale. Any non-ModelList-ish and non-array value is invalid. @method _setData @protected @since 3.5.0 **/ _setData: function (val) { if (val === null) { val = []; } if (isArray(val)) { this._initDataProperty(); // silent to prevent subscribers to both reset and dataChange // from reacting to the change twice. // TODO: would it be better to return INVALID to silence the // dataChange event, or even allow both events? this.data.reset(val, { silent: true }); // Return the instance ModelList to avoid storing unprocessed // data in the state and their vivified Model representations in // the instance's data property. Decreases memory consumption. val = this.data; } else if (!val || !val.each || !val.toJSON) { // ModelList/ArrayList duck typing val = INVALID; } return val; }, /** Relays the value assigned to the deprecated `recordset` attribute to the `data` attribute. If a Recordset instance is passed, the raw object data will be culled from it. @method _setRecordset @param {Object[]|Recordset} val The recordset value to relay @deprecated This will be removed with the deprecated `recordset` attribute in a later version. @protected @since 3.5.0 **/ _setRecordset: function (val) { var data; if (val && Y.Recordset && val instanceof Y.Recordset) { data = []; val.each(function (record) { data.push(record.get('data')); }); val = data; } this.set('data', val); return val; }, /** Accepts a Base subclass (preferably a Model subclass). Alternately, it will generate a custom Model subclass from an array of attribute names or an object defining attributes and their respective configurations (it is assigned as the `ATTRS` of the new class). Any other value is invalid. @method _setRecordType @param {Function|String[]|Object} val The Model subclass, array of attribute names, or the `ATTRS` definition for a custom model subclass @return {Function} A Base/Model subclass @protected @since 3.5.0 **/ _setRecordType: function (val) { var modelClass; // Duck type based on known/likely consumed APIs if (isFunction(val) && val.prototype.toJSON && val.prototype.setAttrs) { modelClass = val; } else if (isObject(val)) { modelClass = this._createRecordClass(val); } return modelClass || INVALID; } }); }, '@VERSION@', {"requires": ["escape", "model-list", "node-event-delegate"]});
examples/FixedActionButton.js
jsbranco/react-materialize
import React from 'react'; import Button from '../src/Button'; export default <Button floating fab='vertical' faicon='fa fa-plus' className='red' large style={{bottom: '45px', right: '24px'}}> <Button floating icon='insert_chart' className='red'/> <Button floating icon='format_quote' className='yellow darken-1'/> <Button floating icon='publish' className='green'/> <Button floating icon='attach_file' className='blue'/> </Button>;
lib/Accordion/AccordionStatusContext.js
folio-org/stripes-components
import React from 'react'; export const AccordionStatusContext = React.createContext(); export const withAccordionStatus = Component => { const WrappedComponent = props => ( <AccordionStatusContext.Consumer> {status => ( <Component accordionStatus={status?.status} setStatus={status?.setStatus} onToggle={status?.onToggle} {...props} /> )} </AccordionStatusContext.Consumer> ); WrappedComponent.displayName = `Wrapped${Component.displayName || Component.name || 'Component'}(withAccordionStatus)`; return WrappedComponent; };
src/helpers/__tests__/connectData-test.js
fkasper/sitrep-frontend
import { expect } from 'chai'; import React from 'react'; import { div } from 'react-dom'; import connectData from '../connectData'; describe('connectData', () => { let fetchData; let fetchDataDeferred; let WrappedComponent; let DataComponent; beforeEach(() => { fetchData = 'fetchDataFunction'; fetchDataDeferred = 'fetchDataDeferredFunction'; WrappedComponent = () => <div />; DataComponent = connectData(fetchData, fetchDataDeferred)(WrappedComponent); }); it('should set fetchData as a static property of the final component', () => { expect(DataComponent.fetchData).to.equal(fetchData); }); it('should set fetchDataDeferred as a static property of the final component', () => { expect(DataComponent.fetchDataDeferred).to.equal(fetchDataDeferred); }); });
src/scripts/components/projectConfig/ProjectConfigForm.component.js
kodokojo/kodokojo-ui
/** * Kodo Kojo - Software factory done right * Copyright © 2017 Kodo Kojo (infos@kodokojo.io) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import { compose } from 'redux' import { connect } from 'react-redux' import { Field, reduxForm, SubmissionError, propTypes } from 'redux-form' import { combineValidators } from 'revalidate' import { intlShape, injectIntl, FormattedMessage } from 'react-intl' import classNames from 'classnames' import filter from 'lodash/filter' import size from 'lodash/size' import isEmpty from 'lodash/isEmpty' // component commons import 'kodokojo-ui-commons/src/styles/_commons.less' import utilsTheme from 'kodokojo-ui-commons/src/styles/_utils.scss' import Card from 'kodokojo-ui-commons/src/scripts/components/card/Card.component' import CardContent from 'kodokojo-ui-commons/src/scripts/components/card/CardContent.component' import CardContainer from 'kodokojo-ui-commons/src/scripts/components/card/CardContainer.component' import Input from 'kodokojo-ui-commons/src/scripts/components/input/Input.component' import Checkbox from 'kodokojo-ui-commons/src/scripts/components/checkbox/Checkbox.component' import Button from 'kodokojo-ui-commons/src/scripts/components/button/Button.component' import FontIcon from 'kodokojo-ui-commons/src/scripts/components/fontIcon/FontIcon.component' // Component import { createProjectConfig } from './projectConfig.actions' import { projectNameValidator } from '../../services/validator.service' import { returnErrorKeyOrMessage } from '../../services/error.service' import { getBrickLogo } from '../../services/param.service' // validation function const validate = (values, props) => combineValidators({ projectName: projectNameValidator('projectName') })(values) // TODO UT // ProjectConfigForm component export class ProjectConfigForm extends React.Component { static propTypes = { bricks: React.PropTypes.object, createProjectConfig: React.PropTypes.func.isRequired, intl: intlShape.isRequired, userId: React.PropTypes.string.isRequired, ...propTypes } constructor(props) { super(props) this.state = { brickList: {} } } componentWillReceiveProps(nextProps) { if (isEmpty(this.state.brickList) && nextProps.bricks && nextProps.bricks.list.length && nextProps.bricks.list.length > 0) { const defaultBricks = {} nextProps.bricks.list.forEach((brickType, brickTypeIndex) => { brickType.forEach((brick, brickIndex) => { defaultBricks[`brick${brickTypeIndex}-${brickIndex}`] = { value: brick, // check the first brick for a given type (SCM / CI / Repository) checked: brickIndex === 0 } }) }) this.setState({ brickList: defaultBricks }) } } handleChangeBrick = (brickCheckbox, brick) => { const brickChecked = { [brickCheckbox]: { checked : this.state.brickList[brickCheckbox] !== undefined ? !this.state.brickList[brickCheckbox].checked : true, value: brick } } this.setState({ brickList: { ...this.state.brickList, ...brickChecked } }) } handleSubmitProject = (values) => { const { userId, createProjectConfig, organisation } = this.props // eslint-disable-line no-shadow const nextProjectName = values.projectName const stackConfiguration = { name: 'build-A', type: 'BUILD', brickConfigs: filter(this.state.brickList, { 'checked': true }).map(brickElement => brickElement.value) } return createProjectConfig({ projectConfigName: nextProjectName.trim(), projectConfigOwner: userId, projectConfigUsers: [userId], stackConfiguration: stackConfiguration, organisationId: organisation.id }) .then(Promise.resolve) .catch(err => Promise.reject( new SubmissionError( { projectName: returnErrorKeyOrMessage( { component: 'project', code: err.message }) } ) )) } render() { const { bricks, handleSubmit, submitting } = this.props // eslint-disable-line no-shadow const { formatMessage } = this.props.intl const bricksDetails = bricks && bricks.list && bricks.list.length ? bricks.list : undefined return ( <form id="projectForm" name="projectForm" noValidate onSubmit={ handleSubmit(this.handleSubmitProject) } > <CardContainer> <div style={{ display: 'flex', flex: '1 1 auto', flexFlow: 'column', alignContent: 'stretch', alignSelf: 'stretch' }}> <div style={{ display: 'flex', flexFlow: 'row' }}> <Card primary row style={{ flex: '1 100%', marginBottom: '10px' }} > <CardContent className={ utilsTheme['content-gutter--large'] } raw row > <div className={ classNames(utilsTheme['title--default'], utilsTheme['content-spacer--large']) } style={{ flex: '0 220px' }} > <span className={ utilsTheme['text-uppercase'] }> <FormattedMessage id={ 'project-add-label' }/> </span> </div> <div style={{ flex: '0 60%', paddingTop: '20px' }} > <div style={{ width: '50%' }}> <Field component={ Input } disabled={ submitting } errorKey="project-name-label" label={ formatMessage({ id: 'project-name-label' }) } name="projectName" required type="text" /> <Field component="input" id="projectUsers" name="projectUsers" type="hidden" /> </div> </div> </CardContent> </Card> </div> <div style={{ display: 'flex', flex: '0 0 auto' }}> <div style={{ display: 'flex', flex: '0 200px', flexFlow: 'column', alignItems: 'stretch', justifyContent: 'stretch' }}> <Card style={{ flex: '1 1 auto', marginRight: '10px' }} > <CardContent className={ utilsTheme['content-gutter--large'] } raw > <div className={ utilsTheme['content-spacer--large'] } style={{ display: 'flex', flexFlow: 'column wrap', alignItems: 'flex-start' }} > <div style={{ display: 'flex', flexFlow: 'column wrap', alignItems: 'center', flex: '1 1 auto' }} > <div className={ classNames(utilsTheme['title--default']) } > <span className={ utilsTheme['text-uppercase'] }> <FormattedMessage id={ 'stack-bricks-label' }/> </span> </div> <FontIcon className={ classNames(utilsTheme['icon--large'], utilsTheme['font-color--1']) } value="layers" /> </div> </div> </CardContent> </Card> </div> <div style={{ display: 'flex', flex: '1 1 60%', flexFlow: 'column' }} > <div style={{ display: 'flex', flex: '1 1 auto', flexFlow: 'column' }}> { bricksDetails && bricksDetails.length > 0 && bricksDetails.map((brickType, brickTypeIndex) => ( <div key={ brickTypeIndex } style={{ display: 'flex', flex: '1 0 auto', flewFlow: 'column' }} > <Card style={ brickTypeIndex > 0 ? { display: 'flex', flex: '1 1 auto', justifyContent: 'center', alignItems: 'stretch', marginTop: '10px' } : { display: 'flex', flex: '1 1 auto', justifyContent: 'center', alignItems: 'stretch' } } > <CardContent className={ utilsTheme['content-gutter--smaller'] } raw row > <div style={{ display: 'flex', flex: '1 1 30%' }} > <div className={ classNames(utilsTheme['title--default']) } > <FormattedMessage id={ `${brickType[0].type.toLowerCase()}-label` }/> </div> </div> <div style={{ display: 'flex', flex: '1 1 70%' }} > { brickType.length > 0 && brickType.map((brick, brickIndex) => ( <div key={ brickIndex } style={{ display: 'flex', flex: '1 1 auto', height: '70px', alignItems: 'center' }} > <Checkbox checked={ this.state.brickList[`brick${brickTypeIndex}-${brickIndex}`] !== undefined ? this.state.brickList[`brick${brickTypeIndex}-${brickIndex}`].checked : false } disabled={ submitting || isEmpty(this.state.brickList) } label={ <span style={{ display: 'flex', flex: '1 1 auto', flexFlow: 'row', alignItems: 'center' }}> { getBrickLogo(brick.name).image && <img src={ getBrickLogo(brick.name).image } style={{ width: '70px', height: '70px' }} /> } <span className={ utilsTheme['text-capitalize'] }> <FormattedMessage id={ `brick-${getBrickLogo(brick.name).name}-label` } /> <span className={ utilsTheme['text-normal']}>{ ` ${brick.version}` }</span> </span> </span> } onChange={ () => this.handleChangeBrick(`brick${brickTypeIndex}-${brickIndex}`,brick) } /> </div> )) } </div> </CardContent> </Card> </div> )) } </div> </div> </div> <div style={{ display: 'flex', flexFlow: 'row wrap', justifyContent: 'flex-end', marginTop: '10px' }}> <Button disabled={ submitting || size(filter(this.state.brickList, { 'checked': true })) <= 0 } label={ formatMessage({ id: 'create-label' }) } primary title={ formatMessage({ id: 'create-label' }) } type="submit" /> </div> </div> </CardContainer> </form> ) } } // ProjectConfigForm container const mapStateProps = (state) => ( { bricks: state.bricks, userId: state.context.user.id, organisation: state.context.organisation } ) const ProjectConfigFormContainer = compose( connect( mapStateProps, { createProjectConfig } ), injectIntl )(reduxForm( { form: 'projectForm', touchOnChange: true, validate } )(ProjectConfigForm)) export default ProjectConfigFormContainer
src/renderers/dom/client/ReactReconcileTransaction.js
gleborgne/react
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconcileTransaction * @typechecks static-only */ 'use strict'; var CallbackQueue = require('CallbackQueue'); var PooledClass = require('PooledClass'); var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter'); var ReactDOMFeatureFlags = require('ReactDOMFeatureFlags'); var ReactInputSelection = require('ReactInputSelection'); var Transaction = require('Transaction'); var assign = require('Object.assign'); /** * Ensures that, when possible, the selection range (currently selected text * input) is not disturbed by performing the transaction. */ var SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection.restoreSelection, }; /** * Suppresses events (blur/focus) that could be inadvertently dispatched due to * high level DOM manipulations (like temporarily removing a text input from the * DOM). */ var EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function() { var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); ReactBrowserEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occurred. `close` * restores the previous value. */ close: function(previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); }, }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function() { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function() { this.reactMountReady.notifyAll(); }, }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [ SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING, ]; /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction(forceHTML) { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.getPooled(null); this.useCreateElement = !forceHTML && ReactDOMFeatureFlags.useCreateElement; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap procedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function() { return this.reactMountReady; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function() { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; }, }; assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction;
net/NoDb/NoDb/Scripts/jquery-1.8.3.min.js
Breeze/breeze.js.samples
/*! jQuery v1.8.3 jquery.com | jquery.org/license */ (function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)v.event.add(t,n,u[n][r])}o.data&&(o.data=v.extend({},o.data))}function Ot(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),v.support.html5Clone&&e.innerHTML&&!v.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Et.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(v.expando)}function Mt(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function _t(e){Et.test(e.type)&&(e.defaultChecked=e.checked)}function Qt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Jt.length;while(i--){t=Jt[i]+n;if(t in e)return t}return r}function Gt(e,t){return e=t||e,v.css(e,"display")==="none"||!v.contains(e.ownerDocument,e)}function Yt(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=v._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&Gt(n)&&(i[s]=v._data(n,"olddisplay",nn(n.nodeName)))):(r=Dt(n,"display"),!i[s]&&r!=="none"&&v._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function Zt(e,t,n){var r=Rt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function en(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=v.css(e,n+$t[i],!0)),r?(n==="content"&&(s-=parseFloat(Dt(e,"padding"+$t[i]))||0),n!=="margin"&&(s-=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0)):(s+=parseFloat(Dt(e,"padding"+$t[i]))||0,n!=="padding"&&(s+=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0));return s}function tn(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=v.support.boxSizing&&v.css(e,"boxSizing")==="border-box";if(r<=0||r==null){r=Dt(e,t);if(r<0||r==null)r=e.style[t];if(Ut.test(r))return r;i=s&&(v.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+en(e,t,n||(s?"border":"content"),i)+"px"}function nn(e){if(Wt[e])return Wt[e];var t=v("<"+e+">").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write("<!doctype html><html><body>"),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function kn(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===Sn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=kn(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=kn(e,n,r,i,"*",o)),u}function Ln(e,n){var r,i,s=v.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&v.extend(!0,e,i)}function An(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function On(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function Fn(){try{return new e.XMLHttpRequest}catch(t){}}function In(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $n(){return setTimeout(function(){qn=t},0),qn=v.now()}function Jn(e,t){v.each(t,function(t,n){var r=(Vn[t]||[]).concat(Vn["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function Kn(e,t,n){var r,i=0,s=0,o=Xn.length,u=v.Deferred().always(function(){delete a.elem}),a=function(){var t=qn||$n(),n=Math.max(0,f.startTime+f.duration-t),r=n/f.duration||0,i=1-r,s=0,o=f.tweens.length;for(;s<o;s++)f.tweens[s].run(i);return u.notifyWith(e,[f,i,n]),i<1&&o?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:v.extend({},t),opts:v.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:qn||$n(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=v.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;Qn(l,f.opts.specialEasing);for(;i<o;i++){r=Xn[i].call(f,e,l,f.opts);if(r)return r}return Jn(f,l),v.isFunction(f.opts.start)&&f.opts.start.call(e,f),v.fx.timer(v.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function Qn(e,t){var n,r,i,s,o;for(n in e){r=v.camelCase(n),i=t[r],s=e[n],v.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=v.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function Gn(e,t,n){var r,i,s,o,u,a,f,l,c,h=this,p=e.style,d={},m=[],g=e.nodeType&&Gt(e);n.queue||(l=v._queueHooks(e,"fx"),l.unqueued==null&&(l.unqueued=0,c=l.empty.fire,l.empty.fire=function(){l.unqueued||c()}),l.unqueued++,h.always(function(){h.always(function(){l.unqueued--,v.queue(e,"fx").length||l.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],v.css(e,"display")==="inline"&&v.css(e,"float")==="none"&&(!v.support.inlineBlockNeedsLayout||nn(e.nodeName)==="inline"?p.display="inline-block":p.zoom=1)),n.overflow&&(p.overflow="hidden",v.support.shrinkWrapBlocks||h.done(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Un.exec(s)){delete t[r],a=a||s==="toggle";if(s===(g?"hide":"show"))continue;m.push(r)}}o=m.length;if(o){u=v._data(e,"fxshow")||v._data(e,"fxshow",{}),"hidden"in u&&(g=u.hidden),a&&(u.hidden=!g),g?v(e).show():h.done(function(){v(e).hide()}),h.done(function(){var t;v.removeData(e,"fxshow",!0);for(t in d)v.style(e,t,d[t])});for(r=0;r<o;r++)i=m[r],f=h.createTween(i,g?u[i]:0),d[i]=u[i]||v.style(e,i),i in u||(u[i]=f.start,g&&(f.end=f.start,f.start=i==="width"||i==="height"?1:0))}}function Yn(e,t,n,r,i){return new Yn.prototype.init(e,t,n,r,i)}function Zn(e,t){var n,r={height:e},i=0;t=t?1:0;for(;i<4;i+=2-t)n=$t[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function tr(e){return v.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var n,r,i=e.document,s=e.location,o=e.navigator,u=e.jQuery,a=e.$,f=Array.prototype.push,l=Array.prototype.slice,c=Array.prototype.indexOf,h=Object.prototype.toString,p=Object.prototype.hasOwnProperty,d=String.prototype.trim,v=function(e,t){return new v.fn.init(e,t,n)},m=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,g=/\S/,y=/\s+/,b=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,w=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(v.isPlainObject(i)||(s=v.isArray(i)))?(s?(s=!1,o=r&&v.isArray(r)?r:[]):o=r&&v.isPlainObject(r)?r:{},u[n]=v.extend(l,o,i)):i!==t&&(u[n]=i)}return u},v.extend({noConflict:function(t){return e.$===v&&(e.$=a),t&&e.jQuery===v&&(e.jQuery=u),v},isReady:!1,readyWait:1,holdReady:function(e){e?v.readyWait++:v.ready(!0)},ready:function(e){if(e===!0?--v.readyWait:v.isReady)return;if(!i.body)return setTimeout(v.ready,1);v.isReady=!0;if(e!==!0&&--v.readyWait>0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:d&&!d.call("\ufeff\u00a0")?function(e){return e==null?"":d.call(e)}:function(e){return e==null?"":(e+"").replace(b,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=v.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||v.isWindow(e)?f.call(r,e):v.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(c)return c.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof v||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),v.isFunction(e)?(i=l.call(arguments,2),s=function(){return e.apply(n,i.concat(l.call(arguments)))},s.guid=e.guid=e.guid||v.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)v.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&v.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(v(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),v.ready.promise=function(t){if(!r){r=v.Deferred();if(i.readyState==="complete")setTimeout(v.ready,1);else if(i.addEventListener)i.addEventListener("DOMContentLoaded",A,!1),e.addEventListener("load",v.ready,!1);else{i.attachEvent("onreadystatechange",A),e.attachEvent("onload",v.ready);var n=!1;try{n=e.frameElement==null&&i.documentElement}catch(s){}n&&n.doScroll&&function o(){if(!v.isReady){try{n.doScroll("left")}catch(e){return setTimeout(o,50)}v.ready()}}()}}return r.promise(t)},v.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){O["[object "+t+"]"]=t.toLowerCase()}),n=v(i);var M={};v.Callbacks=function(e){e=typeof e=="string"?M[e]||_(e):v.extend({},e);var n,r,i,s,o,u,a=[],f=!e.once&&[],l=function(t){n=e.memory&&t,r=!0,u=s||0,s=0,o=a.length,i=!0;for(;a&&u<o;u++)if(a[u].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}i=!1,a&&(f?f.length&&l(f.shift()):n?a=[]:c.disable())},c={add:function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this},remove:function(){return a&&v.each(arguments,function(e,t){var n;while((n=v.inArray(t,a,n))>-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&v.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),v.support=function(){var t,n,r,s,o,u,a,f,l,c,h,p=i.createElement("div");p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.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%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i<s;i++)delete r[t[i]];if(!(n?B:v.isEmptyObject)(r))return}}if(!n){delete u[a].data;if(!B(u[a]))return}o?v.cleanData([e],!0):v.support.deleteExpando||u!=u.window?delete u[a]:u[a]=null},_data:function(e,t,n){return v.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&v.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),v.fn.extend({data:function(e,n){var r,i,s,o,u,a=this[0],f=0,l=null;if(e===t){if(this.length){l=v.data(a);if(a.nodeType===1&&!v._data(a,"parsedAttrs")){s=a.attributes;for(u=s.length;f<u;f++)o=s[f].name,o.indexOf("data-")||(o=v.camelCase(o.substring(5)),H(a,o,l[o]));v._data(a,"parsedAttrs",!0)}}return l}return typeof e=="object"?this.each(function(){v.data(this,e)}):(r=e.split(".",2),r[1]=r[1]?"."+r[1]:"",i=r[1]+"!",v.access(this,function(n){if(n===t)return l=this.triggerHandler("getData"+i,[r[0]]),l===t&&a&&(l=v.data(a,e),l=H(a,e,l)),l===t&&r[1]?this.data(r[0]):l;r[1]=n,this.each(function(){var t=v(this);t.triggerHandler("setData"+i,r),v.data(this,e,n),t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?v.queue(this[0],e):n===t?this:this.each(function(){var t=v.queue(this,e,n);v._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&v.dequeue(this,e)})},dequeue:function(e){return this.each(function(){v.dequeue(this,e)})},delay:function(e,t){return e=v.fx?v.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,s=v.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)r=v._data(o[u],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var j,F,I,q=/[\t\r\n]/g,R=/\r/g,U=/^(?:button|input)$/i,z=/^(?:button|input|object|select|textarea)$/i,W=/^a(?:rea|)$/i,X=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,V=v.support.getSetAttribute;v.fn.extend({attr:function(e,t){return v.access(this,v.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)s.indexOf(" "+t[o]+" ")<0&&(s+=t[o]+" ");i.className=v.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(v.isFunction(e))return this.each(function(t){v(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(y);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(q," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(q," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a<u;a++){n=r[a];if((n.selected||a===i)&&(v.support.optDisabled?!n.disabled:n.getAttribute("disabled")===null)&&(!n.parentNode.disabled||!v.nodeName(n.parentNode,"optgroup"))){t=v(n).val();if(s)return t;o.push(t)}}return o},set:function(e,t){var n=v.makeArray(t);return v(e).find("option").each(function(){this.selected=v.inArray(v(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o<r.length;o++)i=r[o],i&&(n=v.propFix[i]||i,s=X.test(i),s||v.attr(e,i,""),e.removeAttribute(V?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(U.test(e.nodeName)&&e.parentNode)v.error("type property can't be changed");else if(!v.support.radioValue&&t==="radio"&&v.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return j&&v.nodeName(e,"button")?j.get(e,t):t in e?e.value:null},set:function(e,t,n){if(j&&v.nodeName(e,"button"))return j.set(e,t,n);e.value=t}}},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(e,n,r){var i,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!v.isXMLDoc(e),o&&(n=v.propFix[n]||n,s=v.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):z.test(e.nodeName)||W.test(e.nodeName)&&e.href?0:t}}}}),F={get:function(e,n){var r,i=v.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?v.removeAttr(e,n):(r=v.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},V||(I={name:!0,id:!0,coords:!0},j=v.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(I[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=i.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},v.each(["width","height"],function(e,t){v.attrHooks[t]=v.extend(v.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),v.attrHooks.contenteditable={get:j.get,set:function(e,t,n){t===""&&(t="false"),j.set(e,t,n)}}),v.support.hrefNormalized||v.each(["href","src","width","height"],function(e,n){v.attrHooks[n]=v.extend(v.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),v.support.style||(v.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),v.support.optSelected||(v.propHooks.selected=v.extend(v.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),v.support.enctype||(v.propFix.enctype="encoding"),v.support.checkOn||v.each(["radio","checkbox"],function(){v.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),v.each(["radio","checkbox"],function(){v.valHooks[this]=v.extend(v.valHooks[this],{set:function(e,t){if(v.isArray(t))return e.checked=v.inArray(v(e).val(),t)>=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f<n.length;f++){l=J.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),g=v.event.special[c]||{},c=(s?g.delegateType:g.bindType)||c,g=v.event.special[c]||{},p=v.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,needsContext:s&&v.expr.match.needsContext.test(s),namespace:h.join(".")},d),m=a[c];if(!m){m=a[c]=[],m.delegateCount=0;if(!g.setup||g.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}g.add&&(g.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?m.splice(m.delegateCount++,0,p):m.push(p),v.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,m,g=v.hasData(e)&&v._data(e);if(!g||!(h=g.events))return;t=v.trim(Z(t||"")).split(" ");for(s=0;s<t.length;s++){o=J.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)v.event.remove(e,u+t[s],n,r,!0);continue}p=v.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)m=d[c],(i||a===m.origType)&&(!n||n.guid===m.guid)&&(!f||f.test(m.namespace))&&(!r||r===m.selector||r==="**"&&m.selector)&&(d.splice(c--,1),m.selector&&d.delegateCount--,p.remove&&p.remove.call(e,m));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,g.handle)===!1)&&v.removeEvent(e,u,g.handle),delete h[u])}v.isEmptyObject(h)&&(delete g.handle,v.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,s,o){if(!s||s.nodeType!==3&&s.nodeType!==8){var u,a,f,l,c,h,p,d,m,g,y=n.type||n,b=[];if(Y.test(y+v.event.triggered))return;y.indexOf("!")>=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f<m.length&&!n.isPropagationStopped();f++)l=m[f][0],n.type=m[f][1],d=(v._data(l,"events")||{})[n.type]&&v._data(l,"handle"),d&&d.apply(l,r),d=h&&l[h],d&&v.acceptData(l)&&d.apply&&d.apply(l,r)===!1&&n.preventDefault();return n.type=y,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(s.ownerDocument,r)===!1)&&(y!=="click"||!v.nodeName(s,"a"))&&v.acceptData(s)&&h&&s[y]&&(y!=="focus"&&y!=="blur"||n.target.offsetWidth!==0)&&!v.isWindow(s)&&(c=s[h],c&&(s[h]=null),v.event.triggered=y,s[y](),v.event.triggered=t,c&&(s[h]=c)),n.result}return},dispatch:function(n){n=v.event.fix(n||e.event);var r,i,s,o,u,a,f,c,h,p,d=(v._data(this,"events")||{})[n.type]||[],m=d.delegateCount,g=l.call(arguments),y=!n.exclusive&&!n.namespace,b=v.event.special[n.type]||{},w=[];g[0]=n,n.delegateTarget=this;if(b.preDispatch&&b.preDispatch.call(this,n)===!1)return;if(m&&(!n.button||n.type!=="click"))for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){u={},f=[];for(r=0;r<m;r++)c=d[r],h=c.selector,u[h]===t&&(u[h]=c.needsContext?v(h,this).index(s)>=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r<w.length&&!n.isPropagationStopped();r++){a=w[r],n.currentTarget=a.elem;for(i=0;i<a.matches.length&&!n.isImmediatePropagationStopped();i++){c=a.matches[i];if(y||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))n.data=c.data,n.handleObj=c,o=((v.event.special[c.origType]||{}).handle||c.handler).apply(a.elem,g),o!==t&&(n.result=o,o===!1&&(n.preventDefault(),n.stopPropagation()))}}return b.postDispatch&&b.postDispatch.call(this,n),n.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(e,t){return e.which==null&&(e.which=t.charCode!=null?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,s,o,u=n.button,a=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||i,s=r.documentElement,o=r.body,e.pageX=n.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?n.toElement:a),!e.which&&u!==t&&(e.which=u&1?1:u&2?3:u&4?2:0),e}},fix:function(e){if(e[v.expando])return e;var t,n,r=e,s=v.event.fixHooks[e.type]||{},o=s.props?this.props.concat(s.props):this.props;e=v.Event(r);for(t=o.length;t;)n=o[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||i),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){v.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=v.extend(new v.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?v.event.trigger(i,null,t):v.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},v.event.handle=v.event.dispatch,v.removeEvent=i.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},v.Event=function(e,t){if(!(this instanceof v.Event))return new v.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?tt:et):this.type=e,t&&v.extend(this,t),this.timeStamp=e&&e.timeStamp||v.now(),this[v.expando]=!0},v.Event.prototype={preventDefault:function(){this.isDefaultPrevented=tt;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=tt;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=tt,this.stopPropagation()},isDefaultPrevented:et,isPropagationStopped:et,isImmediatePropagationStopped:et},v.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){v.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!v.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),v.support.submitBubbles||(v.event.special.submit={setup:function(){if(v.nodeName(this,"form"))return!1;v.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=v.nodeName(n,"input")||v.nodeName(n,"button")?n.form:t;r&&!v._data(r,"_submit_attached")&&(v.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),v._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&v.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(v.nodeName(this,"form"))return!1;v.event.remove(this,"._submit")}}),v.support.changeBubbles||(v.event.special.change={setup:function(){if($.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")v.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),v.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),v.event.simulate("change",this,e,!0)});return!1}v.event.add(this,"beforeactivate._change",function(e){var t=e.target;$.test(t.nodeName)&&!v._data(t,"_change_attached")&&(v.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&v.event.simulate("change",this.parentNode,e,!0)}),v._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return v.event.remove(this,"._change"),!$.test(this.nodeName)}}),v.support.focusinBubbles||v.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){v.event.simulate(t,e.target,v.event.fix(e),!0)};v.event.special[t]={setup:function(){n++===0&&i.addEventListener(e,r,!0)},teardown:function(){--n===0&&i.removeEventListener(e,r,!0)}}}),v.fn.extend({on:function(e,n,r,i,s){var o,u;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(u in e)this.on(u,n,r,e[u],s);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=et;else if(!i)return this;return s===1&&(o=i,i=function(e){return v().off(e),o.apply(this,arguments)},i.guid=o.guid||(o.guid=v.guid++)),this.each(function(){v.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,s;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,v(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(s in e)this.off(s,n,e[s]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=et),this.each(function(){v.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},live:function(e,t,n){return v(this.context).on(e,this.selector,t,n),this},die:function(e,t){return v(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length===1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){v.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return v.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||v.guid++,r=0,i=function(n){var i=(v._data(this,"lastToggle"+e.guid)||0)%r;return v._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),v.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){v.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u<a;u++)if(s=e[u])if(!n||n(s,r,i))o.push(s),f&&t.push(u);return o}function ct(e,t,n,r,i,s){return r&&!r[d]&&(r=ct(r)),i&&!i[d]&&(i=ct(i,s)),N(function(s,o,u,a){var f,l,c,h=[],p=[],d=o.length,v=s||dt(t||"*",u.nodeType?[u]:u,[]),m=e&&(s||!t)?lt(v,h,e,u,a):v,g=n?i||(s?e:d||r)?[]:o:m;n&&n(m,g,u,a);if(r){f=lt(g,p),r(f,[],u,a),l=f.length;while(l--)if(c=f[l])g[p[l]]=!(m[p[l]]=c)}if(s){if(i||e){if(i){f=[],l=g.length;while(l--)(c=g[l])&&f.push(m[l]=c);i(null,g=[],f,a)}l=g.length;while(l--)(c=g[l])&&(f=i?T.call(s,c):h[l])>-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a<s;a++)if(n=i.relative[e[a].type])h=[at(ft(h),n)];else{n=i.filter[e[a].type].apply(null,e[a].matches);if(n[d]){r=++a;for(;r<s;r++)if(i.relative[e[r].type])break;return ct(a>1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a<r&&ht(e.slice(a,r)),r<s&&ht(e=e.slice(r)),r<s&&e.join(""))}h.push(n)}return ft(h)}function pt(e,t){var r=t.length>0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r<i;r++)nt(e,t[r],n);return n}function vt(e,t,n,r,s){var o,u,f,l,c,h=ut(e),p=h.length;if(!r&&h.length===1){u=h[0]=h[0].slice(0);if(u.length>2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(this[t]===e)return t;return-1},N=function(e,t){return e[d]=t==null||t,e},C=function(){var e={},t=[];return N(function(n,r){return t.push(n)>i.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="<a name='"+d+"'></a><div name='"+d+"'></div>",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:st(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:st(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}},f=y.compareDocumentPosition?function(e,t){return e===t?(l=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:function(e,t){if(e===t)return l=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],s=[],o=e.parentNode,u=t.parentNode,a=o;if(o===u)return ot(e,t);if(!o)return-1;if(!u)return 1;while(a)i.unshift(a),a=a.parentNode;a=u;while(a)s.unshift(a),a=a.parentNode;n=i.length,r=s.length;for(var f=0;f<n&&f<r;f++)if(i[f]!==s[f])return ot(i[f],s[f]);return f===n?ot(e,s[f],-1):ot(i[f],t,1)},[0,0].sort(f),h=!l,nt.uniqueSort=function(e){var t,n=[],r=1,i=0;l=h,e.sort(f);if(l){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},nt.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},a=nt.compile=function(e,t){var n,r=[],i=[],s=A[d][e+" "];if(!s){t||(t=ut(e)),n=t.length;while(n--)s=ht(t[n]),s[d]?r.push(s):i.push(s);s=A(e,pt(i,r))}return s},g.querySelectorAll&&function(){var e,t=vt,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[":focus"],s=[":active"],u=y.matchesSelector||y.mozMatchesSelector||y.webkitMatchesSelector||y.oMatchesSelector||y.msMatchesSelector;K(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(v.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,v.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=v(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(v.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1),"not",e)},filter:function(e){return this.pushStack(ft(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?st.test(e)?v(e,this.context).index(this[0])>=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/<tbody/i,gt=/<|&#?\w+;/,yt=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,wt=new RegExp("<(?:"+ct+")[\\s/>]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Nt={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,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X<div>","</div>"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return ut(this[0])?this.length?this.pushStack(v(v.isFunction(e)?e():e),"replaceWith",e):this:v.isFunction(e)?this.each(function(t){var n=v(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=v(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;v(this).remove(),t?v(t).before(e):v(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],c=this.length;if(!v.support.checkClone&&c>1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a<c;a++)r.call(n&&v.nodeName(this[a],"table")?Lt(this[a],"tbody"):this[a],a===u?o:v.clone(o,!0,!0))}o=s=null,l.length&&v.each(l,function(e,t){t.src?v.ajax?v.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):v.error("no ajax"):v.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Tt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),v.buildFragment=function(e,n,r){var s,o,u,a=e[0];return n=n||i,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,e.length===1&&typeof a=="string"&&a.length<512&&n===i&&a.charAt(0)==="<"&&!bt.test(a)&&(v.support.checkClone||!St.test(a))&&(v.support.html5Clone||!wt.test(a))&&(o=!0,s=v.fragments[a],u=s!==t),s||(s=n.createDocumentFragment(),v.clean(e,n,s,r),o&&(v.fragments[a]=u&&s)),{fragment:s,cacheable:o}},v.fragments={},v.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){v.fn[e]=function(n){var r,i=0,s=[],o=v(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1></$2>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]==="<table>"&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("<div>").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[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","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],Vn[n]=Vn[n]||[],Vn[n].unshift(t)},prefilter:function(e,t){t?Xn.unshift(e):Xn.push(e)}}),v.Tween=Yn,Yn.prototype={constructor:Yn,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(v.cssNumber[n]?"":"px")},cur:function(){var e=Yn.propHooks[this.prop];return e&&e.get?e.get(this):Yn.propHooks._default.get(this)},run:function(e){var t,n=Yn.propHooks[this.prop];return this.options.duration?this.pos=t=v.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Yn.propHooks._default.set(this),this}},Yn.prototype.init.prototype=Yn.prototype,Yn.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=v.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){v.fx.step[e.prop]?v.fx.step[e.prop](e):e.elem.style&&(e.elem.style[v.cssProps[e.prop]]!=null||v.cssHooks[e.prop])?v.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Yn.propHooks.scrollTop=Yn.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},v.each(["toggle","show","hide"],function(e,t){var n=v.fn[t];v.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&v.isFunction(r)&&v.isFunction(i)?n.apply(this,arguments):this.animate(Zn(t,!0),r,i,s)}}),v.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Gt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=v.isEmptyObject(e),s=v.speed(t,n,r),o=function(){var t=Kn(this,v.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=v.timers,o=v._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Wn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&v.dequeue(this,e)})}}),v.each({slideDown:Zn("show"),slideUp:Zn("hide"),slideToggle:Zn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){v.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),v.speed=function(e,t,n){var r=e&&typeof e=="object"?v.extend({},e):{complete:n||!n&&t||v.isFunction(e)&&e,duration:e,easing:n&&t||t&&!v.isFunction(t)&&t};r.duration=v.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in v.fx.speeds?v.fx.speeds[r.duration]:v.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){v.isFunction(r.old)&&r.old.call(this),r.queue&&v.dequeue(this,r.queue)},r},v.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},v.timers=[],v.fx=Yn.prototype.init,v.fx.tick=function(){var e,n=v.timers,r=0;qn=v.now();for(;r<n.length;r++)e=n[r],!e()&&n[r]===e&&n.splice(r--,1);n.length||v.fx.stop(),qn=t},v.fx.timer=function(e){e()&&v.timers.push(e)&&!Rn&&(Rn=setInterval(v.fx.tick,v.fx.interval))},v.fx.interval=13,v.fx.stop=function(){clearInterval(Rn),Rn=null},v.fx.speeds={slow:600,fast:200,_default:400},v.fx.step={},v.expr&&v.expr.filters&&(v.expr.filters.animated=function(e){return v.grep(v.timers,function(t){return e===t.elem}).length});var er=/^(?:body|html)$/i;v.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){v.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f={top:0,left:0},l=this[0],c=l&&l.ownerDocument;if(!c)return;return(r=c.body)===l?v.offset.bodyOffset(l):(n=c.documentElement,v.contains(n,l)?(typeof l.getBoundingClientRect!="undefined"&&(f=l.getBoundingClientRect()),i=tr(c),s=n.clientTop||r.clientTop||0,o=n.clientLeft||r.clientLeft||0,u=i.pageYOffset||n.scrollTop,a=i.pageXOffset||n.scrollLeft,{top:f.top+u-s,left:f.left+a-o}):f)},v.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return v.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(v.css(e,"marginTop"))||0,n+=parseFloat(v.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=v.css(e,"position");r==="static"&&(e.style.position="relative");var i=v(e),s=i.offset(),o=v.css(e,"top"),u=v.css(e,"left"),a=(r==="absolute"||r==="fixed")&&v.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window);
test.js
jxnblk/axs
import test from 'ava' import React from 'react' import { create as render } from 'react-test-renderer' import Base, { Style } from './src' test.afterEach(() => { Base.reset() }) test('renders', t => { const a = render(<Base />).toJSON() t.snapshot(a) }) test('Style renders', t => { const a = render(<Style css='.tomato{color:tomato;}' />).toJSON() t.snapshot(a) }) test('renders with css prop', t => { const a = render(<Base css='color:tomato;' />).toJSON() t.snapshot(a) }) test('renders with decorated HTML element key', t => { const a = render(<Base.h2 css='color:tomato;' />).toJSON() t.snapshot(a) t.is(a[1].type, 'h2') }) test('caches results', t => { const a = render( <React.Fragment> <Base css='color:magenta;' /> <Base css='color:magenta;' /> </React.Fragment> ).toJSON() t.snapshot(a) }) test('Base.reset() clears cache', t => { const a = render(<Base css='color:magenta;' />).toJSON() Base.reset() const b = render(<Base css='color:magenta;' />).toJSON() t.snapshot(a) t.snapshot(b) t.deepEqual(a[0], b[0]) }) test('Updates styles on css change', t => { const base = render(<Base css='color:tomato;' />) const a = base.toJSON() base.update(<Base css='color:green;' />) const b = base.toJSON() t.is(a[1].props.className, 'x0') t.is(b[1].props.className, 'x1') t.snapshot(a) t.snapshot(b) }) test('Skips update when css is the same', t => { const base = render(<Base css='color:tomato;' />) const a = base.toJSON() base.update(<Base css='color:tomato;' />) const b = base.toJSON() t.is(a[1].props.className, 'x0') t.is(b[1].props.className, 'x0') t.deepEqual(a, b) t.snapshot(a) t.snapshot(b) }) test('Extends Axs components', t => { const A = props => ( <Base {...props} css={` color: tomato; ${props.css} `} /> ) const a = render(<Base is={A} css='font-size:32px;' />).toJSON() t.regex(a[0].props.dangerouslySetInnerHTML.__html, /color:tomato;font-size:32px/) t.snapshot(a) })
JS Web/ReactJS/Final Project/zoo-market/src/components/user/Login.js
mitaka00/SoftUni
import React, { Component } from 'react'; import { Link} from 'react-router-dom'; import requester from './../../utils/requester' import HomePage from './../common/HomePage' import './../../App.css'; class Login extends Component{ constructor(props){ super(props) this.state={ username:'', password:'', error:false, loading:false } this.dataColletor=(e)=>{ this.setState({[e.target.name]:e.target.value}) } this.Login=(e)=>{ e.preventDefault() this.setState({loading:true,error:false}) if(this.state.password.length<3 || this.state.username.length<3){ this.setState({error:true,loading:false}) return } this.setState({loading:true}) requester.login(this.state).then(res=>{ localStorage.setItem('token',res._kmd.authtoken) localStorage.setItem('username',res.username) localStorage.setItem('userId',res._id) this.setState({loading:false,error:false}) this.props.history.push('/home') }).catch((e)=>{ this.setState({loading:false,error:true}) this.props.history.push('/') }) } } render(){ return( <form className='authForm' id='loginForm' onSubmit={(e)=>{this.Login(e)}}> {this.state.error===true?<div className='error'>Failed to Login</div> : <div></div>} {this.state.loading===true?<div className='loading'>Loading...</div> : <div></div>} <h2>Login</h2> <div className='inputDiv'> <label>Username:</label> <input onChange={(e)=>this.dataColletor(e)} name='username' type='text'></input> </div> <div className='inputDiv'> <label>Password:</label> <input onChange={(e)=>this.dataColletor(e)} name='password' type='password'></input> </div> <input type='submit' value='Sign In' className='btnAuth'/> </form> ) } } export default Login
src/Stepper/Step.spec.js
mmrtnz/material-ui
/* eslint-env mocha */ import React from 'react'; import {shallow} from 'enzyme'; import {assert} from 'chai'; import Step from './Step'; import getMuiTheme from '../styles/getMuiTheme'; describe('<Step />', () => { const muiTheme = getMuiTheme(); const shallowWithContext = (node, context = {}) => { return shallow(node, { context: { muiTheme, stepper: {orientation: 'horizontal'}, ...context, }, }); }; it('merges styles and other props into the root node', () => { const wrapper = shallowWithContext( <Step style={{paddingRight: 200, color: 'purple', border: '1px solid tomato'}} role="hello" /> ); const {style, role} = wrapper.props(); assert.strictEqual(style.paddingRight, 200); assert.strictEqual(style.color, 'purple'); assert.strictEqual(style.border, '1px solid tomato'); assert.strictEqual(role, 'hello'); }); describe('rendering children', () => { it('renders children', () => { const children = <h1 className="hello-world">Hello World</h1>; const wrapper = shallowWithContext( <Step label="Step One">{children}</Step> ); assert.strictEqual(wrapper.find('.hello-world').length, 1); }); it('renders children with all props passed through', () => { const children = [ <h1 key={1} className="hello-world">Hello World</h1>, <p key={2} className="hay">How are you?</p>, ]; const wrapper = shallowWithContext( <Step active={false} completed={true} disabled={true} index={0} > {children} </Step> ); const child1 = wrapper.find('.hello-world'); const child2 = wrapper.find('.hay'); [child1, child2].forEach((child) => { assert.strictEqual(child.length, 1); assert.strictEqual(child.prop('active'), false); assert.strictEqual(child.prop('completed'), true); assert.strictEqual(child.prop('disabled'), true); assert.strictEqual(child.prop('icon'), 1); }); }); it('honours children overriding props passed through', () => { const children = ( <h1 active={false} className="hello-world">Hello World</h1> ); const wrapper = shallowWithContext( <Step active={true} label="Step One">{children}</Step> ); const childWrapper = wrapper.find('.hello-world'); assert.strictEqual(childWrapper.prop('active'), false); }); }); });
src/main/webapp/assets/vendors/jquery/jquery-1.11.1.js
noc06140728/gitbucket
/*! * jQuery JavaScript Library v1.11.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-05-01T17:42Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var deletedIds = []; var slice = deletedIds.slice; var concat = deletedIds.concat; var push = deletedIds.push; var indexOf = deletedIds.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var version = "1.11.1", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1, IE<9 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: deletedIds.sort, splice: deletedIds.splice }; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( support.ownLast ) { for ( key in obj ) { return hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, type: function( obj ) { if ( obj == null ) { return obj + ""; } return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Support: Android<4.1, IE<9 trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( indexOf ) { return indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; while ( j < len ) { first[ i++ ] = second[ j++ ]; } // Support: IE<9 // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) if ( len !== len ) { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: function() { return +( new Date() ); }, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v1.10.19 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-04-18 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== strundefined && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", function() { setDocument(); }, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", function() { setDocument(); }); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select msallowclip=''><option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowclip^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is no seed and only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // Use the correct document accordingly with window argument (sandbox) document = window.document, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); jQuery.fn.extend({ has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !(--remaining) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } }); /** * Clean-up method for dom ready events */ function detach() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } } /** * The ready event handler and self cleanup method */ function completed() { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; var strundefined = typeof undefined; // Support: IE<9 // Iteration over object's inherited properties before its own var i; for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Note: most support tests are defined in their respective modules. // false until the test is run support.inlineBlockNeedsLayout = false; // Execute ASAP in case we need to set body.style.zoom jQuery(function() { // Minified: var a,b,c,d var val, div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Return for frameset docs that don't have a body return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); if ( typeof div.style.zoom !== strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1"; support.inlineBlockNeedsLayout = val = div.offsetWidth === 3; if ( val ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); }); (function() { var div = document.createElement( "div" ); // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } // Null elements to avoid leaks in IE. div = null; })(); /** * Determines whether an object can have data */ jQuery.acceptData = function( elem ) { var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ], nodeType = +elem.nodeType || 1; // Do not set data on non-element DOM nodes because it will not be cleared (#8335). return nodeType !== 1 && nodeType !== 9 ? false : // Nodes accept data unless otherwise specified; rejection can be conditional !noData || noData !== true && elem.getAttribute("classid") === noData; }; var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } function internalData( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements (space-suffixed to avoid Object.prototype collisions) // throw uncatchable exceptions if you attempt to set expando properties noData: { "applet ": true, "embed ": true, // ...but Flash objects (which have this classid) *can* handle expandos "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[0], attrs = elem && elem.attributes; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { // Minified: var a,b,c var input = document.createElement( "input" ), div = document.createElement( "div" ), fragment = document.createDocumentFragment(); // Setup div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName( "tbody" ).length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) input.type = "checkbox"; input.checked = true; fragment.appendChild( input ); support.appendChecked = input.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE6-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; // #11217 - WebKit loses check when the name is after the checked attribute fragment.appendChild( div ); div.innerHTML = "<input type='radio' checked='checked' name='t'/>"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() support.noCloneEvent = true; if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } })(); (function() { var i, eventName, div = document.createElement( "div" ); // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event) for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; if ( !(support[ i + "Bubbles" ] = eventName in window) ) { // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) div.setAttribute( eventName, "t" ); support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false; } } // Null elements to avoid leaks in IE. div = null; })(); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: IE < 9, Android < 4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); jQuery._removeData( doc, fix ); } else { jQuery._data( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!support.noCloneEvent || !support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } deletedIds.push( id ); } } } } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( support.htmlSerialize || !rnoshimcache.test( value ) ) && ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF style.display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } (function() { var shrinkWrapBlocksVal; support.shrinkWrapBlocks = function() { if ( shrinkWrapBlocksVal != null ) { return shrinkWrapBlocksVal; } // Will be changed later if needed. shrinkWrapBlocksVal = false; // Minified: var b,c,d var div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); // Support: IE6 // Check if elements with layout shrink-wrap their children if ( typeof div.style.zoom !== strundefined ) { // Reset CSS: box-sizing; display; margin; border div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;" + "padding:1px;width:1px;zoom:1"; div.appendChild( document.createElement( "div" ) ).style.width = "5px"; shrinkWrapBlocksVal = div.offsetWidth !== 3; } body.removeChild( container ); return shrinkWrapBlocksVal; }; })(); var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles, curCSS, rposition = /^(top|right|bottom|left)$/; if ( window.getComputedStyle ) { getStyles = function( elem ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); }; curCSS = function( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + ""; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, computed ) { var left, rs, rsLeft, ret, style = elem.style; computed = computed || getStyles( elem ); ret = computed ? computed[ name ] : undefined; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + "" || "auto"; }; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { var condition = conditionFn(); if ( condition == null ) { // The test was not ready at this point; screw the hook this time // but check again when needed next time. return; } if ( condition ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { // Minified: var b,c,d,e,f,g, h,i var div, style, a, pixelPositionVal, boxSizingReliableVal, reliableHiddenOffsetsVal, reliableMarginRightVal; // Setup div = document.createElement( "div" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName( "a" )[ 0 ]; style = a && a.style; // Finish early in limited (non-browser) environments if ( !style ) { return; } style.cssText = "float:left;opacity:.5"; // Support: IE<9 // Make sure that element opacity exists (as opposed to filter) support.opacity = style.opacity === "0.5"; // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!style.cssFloat; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" || style.WebkitBoxSizing === ""; jQuery.extend(support, { reliableHiddenOffsets: function() { if ( reliableHiddenOffsetsVal == null ) { computeStyleTests(); } return reliableHiddenOffsetsVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computeStyleTests(); } return boxSizingReliableVal; }, pixelPosition: function() { if ( pixelPositionVal == null ) { computeStyleTests(); } return pixelPositionVal; }, // Support: Android 2.3 reliableMarginRight: function() { if ( reliableMarginRightVal == null ) { computeStyleTests(); } return reliableMarginRightVal; } }); function computeStyleTests() { // Minified: var b,c,d,j var div, body, container, contents; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" + "box-sizing:border-box;display:block;margin-top:1%;top:1%;" + "border:1px;padding:1px;width:4px;position:absolute"; // Support: IE<9 // Assume reasonable values in the absence of getComputedStyle pixelPositionVal = boxSizingReliableVal = false; reliableMarginRightVal = true; // Check for getComputedStyle so that this code is not run in IE<9. if ( window.getComputedStyle ) { pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; boxSizingReliableVal = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right contents = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding contents.style.cssText = div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;padding:0"; contents.style.marginRight = contents.style.width = "0"; div.style.width = "1px"; reliableMarginRightVal = !parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight ); } // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; contents = div.getElementsByTagName( "td" ); contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; if ( reliableHiddenOffsetsVal ) { contents[ 0 ].style.display = ""; contents[ 1 ].style.display = "none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; } body.removeChild( container ); } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set. See: #7116 if ( value == null || value !== value ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Support: IE // Swallow errors from 'invalid' CSS values (#5509) try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; } }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !support.shrinkWrapBlocks() ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); // Any non-fx value stops us from restoring the original display value } else { display = undefined; } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } // If this is a noop like .hide().hide(), restore an overwritten display value } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) { style.display = display; } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.timers = []; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }; (function() { // Minified: var a,b,c,d,e var input, div, select, a, opt; // Setup div = document.createElement( "div" ); div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName("a")[ 0 ]; // First batch of tests. select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE8 only // Check if we can trust getAttribute("value") input = document.createElement( "input" ); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; })(); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE10-11+ // option.text throws exceptions (#14686, #14858) jQuery.trim( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) { // Support: IE6 // When new option element is added to select box we need to // force reflow of newly added node in order to workaround delay // of initialization properties try { option.selected = optionSet = true; } catch ( _ ) { // Will be executed only in IE6 option.scrollHeight; } } else { option.selected = false; } } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return options; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = support.getSetAttribute, getSetInput = support.input; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hook for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; // Retrieve booleans specially jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; } : function( elem, name, isXML ) { if ( !isXML ) { return elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; } }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) if ( name === "value" || value === elem.getAttribute( name ) ) { return value; } } }; // Some attributes are constructed with empty-string values when not defined attrHandle.id = attrHandle.name = attrHandle.coords = function( elem, name, isXML ) { var ret; if ( !isXML ) { return (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; } }; // Fixing value retrieval on a button requires this module jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); if ( ret && ret.specified ) { return ret.value; } }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } if ( !support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } var rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } // Support: Safari, IE9+ // mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !support.enctype ) { jQuery.propFix.enctype = "encoding"; } var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); // Return jQuery for attributes-only inclusion jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var nonce = jQuery.now(); var rquery = (/\?/); var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g; jQuery.parseJSON = function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { // Support: Android 2.3 // Workaround failure to string-cast null input return window.JSON.parse( data + "" ); } var requireNonComma, depth = null, str = jQuery.trim( data + "" ); // Guard against invalid (and possibly dangerous) input by ensuring that nothing remains // after removing valid tokens return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) { // Force termination if we see a misplaced comma if ( requireNonComma && comma ) { depth = 0; } // Perform no more replacements after returning to outermost depth if ( depth === 0 ) { return token; } // Commas must not follow "[", "{", or "," requireNonComma = open || comma; // Determine new depth // array/object open ("[" or "{"): depth += true - false (increment) // array/object close ("]" or "}"): depth += false - true (decrement) // other cases ("," or primitive): depth += true - true (numeric cast) depth += !close - !open; // Remove this token return ""; }) ) ? ( Function( "return " + str ) )() : jQuery.error( "Invalid JSON: " + data ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType.charAt( 0 ) === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; }); jQuery._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!support.reliableHiddenOffsets() && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ? // Support: IE6+ function() { // XHR cannot access local files, always use ActiveX for that case return !this.isLocal && // Support: IE7-8 // oldIE XHR does not support non-RFC2616 methods (#13240) // See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx // and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9 // Although this check for six methods instead of eight // since IE also does not support "trace" and "connect" /^(get|post|head|put|delete|options)$/i.test( this.type ) && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; var xhrId = 0, xhrCallbacks = {}, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE<10 // Open requests must be manually aborted on unload (#5280) if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }); } // Determine support properties support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( options ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !options.crossDomain || support.cors ) { var callback; return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; // Open the socket xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { // Support: IE<9 // IE's ActiveXObject throws a 'Type Mismatch' exception when setting // request header to a null-value. // // To keep consistent with other XHR implementations, cast the value // to string and ignore `undefined`. if ( headers[ i ] !== undefined ) { xhr.setRequestHeader( i, headers[ i ] + "" ); } } // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( options.hasContent && options.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responses; // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Clean up delete xhrCallbacks[ id ]; callback = undefined; xhr.onreadystatechange = jQuery.noop; // Abort manually if needed if ( isAbort ) { if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; // Support: IE<10 // Accessing binary-data responseText throws an exception // (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && options.isLocal && !options.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, xhr.getAllResponseHeaders() ); } }; if ( !options.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { // Add to the list of active xhr callbacks xhr.onreadystatechange = xhrCallbacks[ id ] = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = jQuery.trim( url.slice( off, url.length ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -1; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; }));
packages/material-ui-icons/src/SignalCellular4BarSharp.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M2 22h20V2L2 22z" /> , 'SignalCellular4BarSharp');
client/tests/components/Header/Header.spec.js
jakebian/hera
import React from 'react' import { Header } from 'components/Header/Header' import { IndexLink, Link } from 'react-router' import { shallow } from 'enzyme' describe('(Component) Header', () => { let _wrapper beforeEach(() => { _wrapper = shallow(<Header />) }) it('Renders a welcome message', () => { const welcome = _wrapper.find('h1') expect(welcome).to.exist expect(welcome.text()).to.match(/React Redux Starter Kit/) }) describe('Navigation links...', () => { it('Should render a Link to Home route', () => { expect(_wrapper.contains( <IndexLink activeClassName='route--active' to='/'> Home </IndexLink> )).to.be.true }) it('Should render a Link to Counter route', () => { expect(_wrapper.contains( <Link activeClassName='route--active' to='/counter'> Counter </Link> )).to.be.true }) }) })
src/components/GitmojiList/hooks/__tests__/useLocalStorage.spec.js
carloscuesta/gitmoji
import React from 'react' import renderer from 'react-test-renderer' import useLocalStorage from '../useLocalStorage' import * as stubs from './stubs' const TestComponent = ({ storageKey, storageValue }) => { useLocalStorage(storageKey, storageValue) return null } Object.defineProperty(window, 'localStorage', { writable: true, value: { setItem: jest.fn(), getItem: jest.fn() }, }) describe('useLocalStorage', () => { describe('when value is not persisted', () => { beforeAll(() => { window.localStorage.getItem.mockReturnValue(null) }) it('should call localStorage.setItem', () => { const wrapper = renderer.create( <TestComponent storageKey={stubs.localStorageMock.key} storageValue={stubs.localStorageMock.value} /> ) wrapper.update() expect(window.localStorage.setItem).toHaveBeenCalledWith( stubs.localStorageMock.key, stubs.localStorageMock.value ) }) }) describe('when there is an error', () => { const consoleError = console.error beforeAll(() => { window.localStorage.getItem.mockReturnValue(new Error('Test')) Object.defineProperty(console, 'error', { writable: true, value: jest.fn(), }) }) afterAll(() => { Object.defineProperty(console, 'error', { writable: true, value: consoleError, }) }) it('should call console.error', () => { const wrapper = renderer.create( <TestComponent storageKey={stubs.localStorageMock.key} storageValue={stubs.localStorageMock.value} /> ) wrapper.update() expect(console.error).toHaveBeenCalledWith(expect.any(String)) }) }) })
src/components/header/index.js
datea/datea-webapp-react
import './header.scss'; import React from 'react'; import {observer, inject} from 'mobx-react'; import config from '../../config'; import MobileHeader from './mobile'; import NormalHeader from './normal'; @inject('store') @observer export default class Header extends React.Component { render() { const {ui} = this.props.store; if (ui.isMobile) return <MobileHeader /> return <NormalHeader /> } }
node_modules/recompose/es/Recompose.js
taforyou/testtesttest-yo
import React, { Component } from 'react'; import shallowEqual from 'fbjs/lib/shallowEqual'; import hoistNonReactStatics from 'hoist-non-react-statics'; import { createChangeEmitter } from 'change-emitter'; import $$observable from 'symbol-observable'; var setStatic = function setStatic(key, value) { return function (BaseComponent) { /* eslint-disable no-param-reassign */ BaseComponent[key] = value; /* eslint-enable no-param-reassign */ return BaseComponent; }; }; var setDisplayName = function setDisplayName(displayName) { return setStatic('displayName', displayName); }; var getDisplayName = function getDisplayName(Component$$1) { if (typeof Component$$1 === 'string') { return Component$$1; } if (!Component$$1) { return undefined; } return Component$$1.displayName || Component$$1.name || 'Component'; }; var wrapDisplayName = function wrapDisplayName(BaseComponent, hocName) { return hocName + '(' + getDisplayName(BaseComponent) + ')'; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; 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 createEagerElementUtil = function createEagerElementUtil(hasKey, isReferentiallyTransparent, type, props, children) { if (!hasKey && isReferentiallyTransparent) { if (children) { return type(_extends({}, props, { children: children })); } return type(props); } var Component$$1 = type; if (children) { return React.createElement( Component$$1, props, children ); } return React.createElement(Component$$1, props); }; var isClassComponent = function isClassComponent(Component$$1) { return Boolean(Component$$1 && Component$$1.prototype && _typeof(Component$$1.prototype.isReactComponent) === 'object'); }; var isReferentiallyTransparentFunctionComponent = function isReferentiallyTransparentFunctionComponent(Component$$1) { return Boolean(typeof Component$$1 === 'function' && !isClassComponent(Component$$1) && !Component$$1.defaultProps && !Component$$1.contextTypes && (process.env.NODE_ENV === 'production' || !Component$$1.propTypes)); }; var createFactory = function createFactory(type) { var isReferentiallyTransparent = isReferentiallyTransparentFunctionComponent(type); return function (p, c) { return createEagerElementUtil(false, isReferentiallyTransparent, type, p, c); }; }; var mapProps = function mapProps(propsMapper) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var MapProps = function MapProps(props) { return factory(propsMapper(props)); }; if (process.env.NODE_ENV !== 'production') { return setDisplayName(wrapDisplayName(BaseComponent, 'mapProps'))(MapProps); } return MapProps; }; }; var withProps = function withProps(input) { var hoc = mapProps(function (props) { return _extends({}, props, typeof input === 'function' ? input(props) : input); }); if (process.env.NODE_ENV !== 'production') { return function (BaseComponent) { return setDisplayName(wrapDisplayName(BaseComponent, 'withProps'))(hoc(BaseComponent)); }; } return hoc; }; var pick = function pick(obj, keys) { var result = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (obj.hasOwnProperty(key)) { result[key] = obj[key]; } } return result; }; var withPropsOnChange = function withPropsOnChange(shouldMapOrKeys, propsMapper) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var shouldMap = typeof shouldMapOrKeys === 'function' ? shouldMapOrKeys : function (props, nextProps) { return !shallowEqual(pick(props, shouldMapOrKeys), pick(nextProps, shouldMapOrKeys)); }; var WithPropsOnChange = function (_Component) { inherits(WithPropsOnChange, _Component); function WithPropsOnChange() { var _temp, _this, _ret; classCallCheck(this, WithPropsOnChange); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.computedProps = propsMapper(_this.props), _temp), possibleConstructorReturn(_this, _ret); } WithPropsOnChange.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (shouldMap(this.props, nextProps)) { this.computedProps = propsMapper(nextProps); } }; WithPropsOnChange.prototype.render = function render() { return factory(_extends({}, this.props, this.computedProps)); }; return WithPropsOnChange; }(Component); if (process.env.NODE_ENV !== 'production') { return setDisplayName(wrapDisplayName(BaseComponent, 'withPropsOnChange'))(WithPropsOnChange); } return WithPropsOnChange; }; }; var mapValues = function mapValues(obj, func) { var result = {}; /* eslint-disable no-restricted-syntax */ for (var key in obj) { if (obj.hasOwnProperty(key)) { result[key] = func(obj[key], key); } } /* eslint-enable no-restricted-syntax */ return result; }; /* eslint-disable no-console */ var withHandlers = function withHandlers(handlers) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var WithHandlers = function (_Component) { inherits(WithHandlers, _Component); function WithHandlers() { var _temp, _this, _ret; classCallCheck(this, WithHandlers); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _initialiseProps.call(_this), _temp), possibleConstructorReturn(_this, _ret); } WithHandlers.prototype.componentWillReceiveProps = function componentWillReceiveProps() { this.cachedHandlers = {}; }; WithHandlers.prototype.render = function render() { return factory(_extends({}, this.props, this.handlers)); }; return WithHandlers; }(Component); var _initialiseProps = function _initialiseProps() { var _this2 = this; this.cachedHandlers = {}; this.handlers = mapValues(typeof handlers === 'function' ? handlers(this.props) : handlers, function (createHandler, handlerName) { return function () { var cachedHandler = _this2.cachedHandlers[handlerName]; if (cachedHandler) { return cachedHandler.apply(undefined, arguments); } var handler = createHandler(_this2.props); _this2.cachedHandlers[handlerName] = handler; if (process.env.NODE_ENV !== 'production' && typeof handler !== 'function') { console.error( // eslint-disable-line no-console 'withHandlers(): Expected a map of higher-order functions. ' + 'Refer to the docs for more info.'); } return handler.apply(undefined, arguments); }; }); }; if (process.env.NODE_ENV !== 'production') { return setDisplayName(wrapDisplayName(BaseComponent, 'withHandlers'))(WithHandlers); } return WithHandlers; }; }; var defaultProps = function defaultProps(props) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var DefaultProps = function DefaultProps(ownerProps) { return factory(ownerProps); }; DefaultProps.defaultProps = props; if (process.env.NODE_ENV !== 'production') { return setDisplayName(wrapDisplayName(BaseComponent, 'defaultProps'))(DefaultProps); } return DefaultProps; }; }; var omit = function omit(obj, keys) { var rest = objectWithoutProperties(obj, []); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (rest.hasOwnProperty(key)) { delete rest[key]; } } return rest; }; var renameProp = function renameProp(oldName, newName) { var hoc = mapProps(function (props) { var _babelHelpers$extends; return _extends({}, omit(props, [oldName]), (_babelHelpers$extends = {}, _babelHelpers$extends[newName] = props[oldName], _babelHelpers$extends)); }); if (process.env.NODE_ENV !== 'production') { return function (BaseComponent) { return setDisplayName(wrapDisplayName(BaseComponent, 'renameProp'))(hoc(BaseComponent)); }; } return hoc; }; var keys = Object.keys; var mapKeys = function mapKeys(obj, func) { return keys(obj).reduce(function (result, key) { var val = obj[key]; /* eslint-disable no-param-reassign */ result[func(val, key)] = val; /* eslint-enable no-param-reassign */ return result; }, {}); }; var renameProps = function renameProps(nameMap) { var hoc = mapProps(function (props) { return _extends({}, omit(props, keys(nameMap)), mapKeys(pick(props, keys(nameMap)), function (_, oldName) { return nameMap[oldName]; })); }); if (process.env.NODE_ENV !== 'production') { return function (BaseComponent) { return setDisplayName(wrapDisplayName(BaseComponent, 'renameProps'))(hoc(BaseComponent)); }; } return hoc; }; var flattenProp = function flattenProp(propName) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var FlattenProp = function FlattenProp(props) { return factory(_extends({}, props, props[propName])); }; if (process.env.NODE_ENV !== 'production') { return setDisplayName(wrapDisplayName(BaseComponent, 'flattenProp'))(FlattenProp); } return FlattenProp; }; }; var withState = function withState(stateName, stateUpdaterName, initialState) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var WithState = function (_Component) { inherits(WithState, _Component); function WithState() { var _temp, _this, _ret; classCallCheck(this, WithState); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = { stateValue: typeof initialState === 'function' ? initialState(_this.props) : initialState }, _this.updateStateValue = function (updateFn, callback) { return _this.setState(function (_ref) { var stateValue = _ref.stateValue; return { stateValue: typeof updateFn === 'function' ? updateFn(stateValue) : updateFn }; }, callback); }, _temp), possibleConstructorReturn(_this, _ret); } WithState.prototype.render = function render() { var _babelHelpers$extends; return factory(_extends({}, this.props, (_babelHelpers$extends = {}, _babelHelpers$extends[stateName] = this.state.stateValue, _babelHelpers$extends[stateUpdaterName] = this.updateStateValue, _babelHelpers$extends))); }; return WithState; }(Component); if (process.env.NODE_ENV !== 'production') { return setDisplayName(wrapDisplayName(BaseComponent, 'withState'))(WithState); } return WithState; }; }; var withStateHandlers = function withStateHandlers(initialState, stateUpdaters) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var WithStateHandlers = function (_Component) { inherits(WithStateHandlers, _Component); function WithStateHandlers() { var _temp, _this, _ret; classCallCheck(this, WithStateHandlers); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _initialiseProps.call(_this), _temp), possibleConstructorReturn(_this, _ret); } WithStateHandlers.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) { var propsChanged = nextProps !== this.props; // the idea is to skip render if stateUpdater handler return undefined // this allows to create no state update handlers with access to state and props var stateChanged = !shallowEqual(nextState, this.state); return propsChanged || stateChanged; }; WithStateHandlers.prototype.render = function render() { return factory(_extends({}, this.props, this.state, this.stateUpdaters)); }; return WithStateHandlers; }(Component); var _initialiseProps = function _initialiseProps() { var _this2 = this; this.state = typeof initialState === 'function' ? initialState(this.props) : initialState; this.stateUpdaters = mapValues(stateUpdaters, function (handler) { return function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return _this2.setState(function (state, props) { return handler(state, props).apply(undefined, args); }); }; }); }; if (process.env.NODE_ENV !== 'production') { return setDisplayName(wrapDisplayName(BaseComponent, 'withStateHandlers'))(WithStateHandlers); } return WithStateHandlers; }; }; var withReducer = function withReducer(stateName, dispatchName, reducer, initialState) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var WithReducer = function (_Component) { inherits(WithReducer, _Component); function WithReducer() { var _temp, _this, _ret; classCallCheck(this, WithReducer); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = { stateValue: _this.initializeStateValue() }, _this.dispatch = function (action) { return _this.setState(function (_ref) { var stateValue = _ref.stateValue; return { stateValue: reducer(stateValue, action) }; }); }, _temp), possibleConstructorReturn(_this, _ret); } WithReducer.prototype.initializeStateValue = function initializeStateValue() { if (initialState !== undefined) { return typeof initialState === 'function' ? initialState(this.props) : initialState; } return reducer(undefined, { type: '@@recompose/INIT' }); }; WithReducer.prototype.render = function render() { var _babelHelpers$extends; return factory(_extends({}, this.props, (_babelHelpers$extends = {}, _babelHelpers$extends[stateName] = this.state.stateValue, _babelHelpers$extends[dispatchName] = this.dispatch, _babelHelpers$extends))); }; return WithReducer; }(Component); if (process.env.NODE_ENV !== 'production') { return setDisplayName(wrapDisplayName(BaseComponent, 'withReducer'))(WithReducer); } return WithReducer; }; }; var identity = function identity(Component$$1) { return Component$$1; }; var branch = function branch(test, left) { var right = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : identity; return function (BaseComponent) { var leftFactory = void 0; var rightFactory = void 0; var Branch = function Branch(props) { if (test(props)) { leftFactory = leftFactory || createFactory(left(BaseComponent)); return leftFactory(props); } rightFactory = rightFactory || createFactory(right(BaseComponent)); return rightFactory(props); }; if (process.env.NODE_ENV !== 'production') { return setDisplayName(wrapDisplayName(BaseComponent, 'branch'))(Branch); } return Branch; }; }; var renderComponent = function renderComponent(Component$$1) { return function (_) { var factory = createFactory(Component$$1); var RenderComponent = function RenderComponent(props) { return factory(props); }; if (process.env.NODE_ENV !== 'production') { RenderComponent.displayName = wrapDisplayName(Component$$1, 'renderComponent'); } return RenderComponent; }; }; var Nothing = function (_Component) { inherits(Nothing, _Component); function Nothing() { classCallCheck(this, Nothing); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } Nothing.prototype.render = function render() { return null; }; return Nothing; }(Component); var renderNothing = function renderNothing(_) { return Nothing; }; var shouldUpdate = function shouldUpdate(test) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var ShouldUpdate = function (_Component) { inherits(ShouldUpdate, _Component); function ShouldUpdate() { classCallCheck(this, ShouldUpdate); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } ShouldUpdate.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { return test(this.props, nextProps); }; ShouldUpdate.prototype.render = function render() { return factory(this.props); }; return ShouldUpdate; }(Component); if (process.env.NODE_ENV !== 'production') { return setDisplayName(wrapDisplayName(BaseComponent, 'shouldUpdate'))(ShouldUpdate); } return ShouldUpdate; }; }; var pure = function pure(BaseComponent) { var hoc = shouldUpdate(function (props, nextProps) { return !shallowEqual(props, nextProps); }); if (process.env.NODE_ENV !== 'production') { return setDisplayName(wrapDisplayName(BaseComponent, 'pure'))(hoc(BaseComponent)); } return hoc(BaseComponent); }; var onlyUpdateForKeys = function onlyUpdateForKeys(propKeys) { var hoc = shouldUpdate(function (props, nextProps) { return !shallowEqual(pick(nextProps, propKeys), pick(props, propKeys)); }); if (process.env.NODE_ENV !== 'production') { return function (BaseComponent) { return setDisplayName(wrapDisplayName(BaseComponent, 'onlyUpdateForKeys'))(hoc(BaseComponent)); }; } return hoc; }; var onlyUpdateForPropTypes = function onlyUpdateForPropTypes(BaseComponent) { var propTypes = BaseComponent.propTypes; if (process.env.NODE_ENV !== 'production') { if (!propTypes) { /* eslint-disable */ console.error('A component without any `propTypes` was passed to ' + '`onlyUpdateForPropTypes()`. Check the implementation of the ' + ('component with display name "' + getDisplayName(BaseComponent) + '".')); /* eslint-enable */ } } var propKeys = Object.keys(propTypes || {}); var OnlyUpdateForPropTypes = onlyUpdateForKeys(propKeys)(BaseComponent); if (process.env.NODE_ENV !== 'production') { return setDisplayName(wrapDisplayName(BaseComponent, 'onlyUpdateForPropTypes'))(OnlyUpdateForPropTypes); } return OnlyUpdateForPropTypes; }; var withContext = function withContext(childContextTypes, getChildContext) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var WithContext = function (_Component) { inherits(WithContext, _Component); function WithContext() { var _temp, _this, _ret; classCallCheck(this, WithContext); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.getChildContext = function () { return getChildContext(_this.props); }, _temp), possibleConstructorReturn(_this, _ret); } WithContext.prototype.render = function render() { return factory(this.props); }; return WithContext; }(Component); WithContext.childContextTypes = childContextTypes; if (process.env.NODE_ENV !== 'production') { return setDisplayName(wrapDisplayName(BaseComponent, 'withContext'))(WithContext); } return WithContext; }; }; var getContext = function getContext(contextTypes) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var GetContext = function GetContext(ownerProps, context) { return factory(_extends({}, ownerProps, context)); }; GetContext.contextTypes = contextTypes; if (process.env.NODE_ENV !== 'production') { return setDisplayName(wrapDisplayName(BaseComponent, 'getContext'))(GetContext); } return GetContext; }; }; /* eslint-disable no-console */ var lifecycle = function lifecycle(spec) { return function (BaseComponent) { var factory = createFactory(BaseComponent); if (process.env.NODE_ENV !== 'production' && spec.hasOwnProperty('render')) { console.error('lifecycle() does not support the render method; its behavior is to ' + 'pass all props and state to the base component.'); } var Lifecycle = function (_Component) { inherits(Lifecycle, _Component); function Lifecycle() { classCallCheck(this, Lifecycle); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } Lifecycle.prototype.render = function render() { return factory(_extends({}, this.props, this.state)); }; return Lifecycle; }(Component); Object.keys(spec).forEach(function (hook) { return Lifecycle.prototype[hook] = spec[hook]; }); if (process.env.NODE_ENV !== 'production') { return setDisplayName(wrapDisplayName(BaseComponent, 'lifecycle'))(Lifecycle); } return Lifecycle; }; }; var toClass = function toClass(baseComponent) { if (isClassComponent(baseComponent)) { return baseComponent; } var ToClass = function (_Component) { inherits(ToClass, _Component); function ToClass() { classCallCheck(this, ToClass); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } ToClass.prototype.render = function render() { if (typeof baseComponent === 'string') { return React.createElement(baseComponent, this.props); } return baseComponent(this.props, this.context); }; return ToClass; }(Component); ToClass.displayName = getDisplayName(baseComponent); ToClass.propTypes = baseComponent.propTypes; ToClass.contextTypes = baseComponent.contextTypes; ToClass.defaultProps = baseComponent.defaultProps; return ToClass; }; var setPropTypes = function setPropTypes(propTypes) { return setStatic('propTypes', propTypes); }; function compose() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } return funcs.reduce(function (a, b) { return function () { return a(b.apply(undefined, arguments)); }; }); } var createEagerElement = function createEagerElement(type, props, children) { var isReferentiallyTransparent = isReferentiallyTransparentFunctionComponent(type); /* eslint-disable */ var hasKey = props && props.hasOwnProperty('key'); /* eslint-enable */ return createEagerElementUtil(hasKey, isReferentiallyTransparent, type, props, children); }; var createSink = function createSink(callback) { return function (_Component) { inherits(Sink, _Component); function Sink() { classCallCheck(this, Sink); return possibleConstructorReturn(this, _Component.apply(this, arguments)); } Sink.prototype.componentWillMount = function componentWillMount() { callback(this.props); }; Sink.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { callback(nextProps); }; Sink.prototype.render = function render() { return null; }; return Sink; }(Component); }; var componentFromProp = function componentFromProp(propName) { var Component$$1 = function Component$$1(props) { return createEagerElement(props[propName], omit(props, [propName])); }; Component$$1.displayName = 'componentFromProp(' + propName + ')'; return Component$$1; }; var nest = function nest() { for (var _len = arguments.length, Components = Array(_len), _key = 0; _key < _len; _key++) { Components[_key] = arguments[_key]; } var factories = Components.map(createFactory); var Nest = function Nest(_ref) { var props = objectWithoutProperties(_ref, []), children = _ref.children; return factories.reduceRight(function (child, factory) { return factory(props, child); }, children); }; if (process.env.NODE_ENV !== 'production') { var displayNames = Components.map(getDisplayName); Nest.displayName = 'nest(' + displayNames.join(', ') + ')'; } return Nest; }; var hoistStatics = function hoistStatics(higherOrderComponent) { return function (BaseComponent) { var NewComponent = higherOrderComponent(BaseComponent); hoistNonReactStatics(NewComponent, BaseComponent); return NewComponent; }; }; var _config = { fromESObservable: null, toESObservable: null }; var configureObservable = function configureObservable(c) { _config = c; }; var config = { fromESObservable: function fromESObservable(observable) { return typeof _config.fromESObservable === 'function' ? _config.fromESObservable(observable) : observable; }, toESObservable: function toESObservable(stream) { return typeof _config.toESObservable === 'function' ? _config.toESObservable(stream) : stream; } }; var componentFromStreamWithConfig = function componentFromStreamWithConfig(config$$1) { return function (propsToVdom) { return function (_Component) { inherits(ComponentFromStream, _Component); function ComponentFromStream() { var _config$fromESObserva; var _temp, _this, _ret; classCallCheck(this, ComponentFromStream); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = { vdom: null }, _this.propsEmitter = createChangeEmitter(), _this.props$ = config$$1.fromESObservable((_config$fromESObserva = { subscribe: function subscribe(observer) { var unsubscribe = _this.propsEmitter.listen(function (props) { if (props) { observer.next(props); } else { observer.complete(); } }); return { unsubscribe: unsubscribe }; } }, _config$fromESObserva[$$observable] = function () { return this; }, _config$fromESObserva)), _this.vdom$ = config$$1.toESObservable(propsToVdom(_this.props$)), _temp), possibleConstructorReturn(_this, _ret); } // Stream of props // Stream of vdom ComponentFromStream.prototype.componentWillMount = function componentWillMount() { var _this2 = this; // Subscribe to child prop changes so we know when to re-render this.subscription = this.vdom$.subscribe({ next: function next(vdom) { _this2.setState({ vdom: vdom }); } }); this.propsEmitter.emit(this.props); }; ComponentFromStream.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { // Receive new props from the owner this.propsEmitter.emit(nextProps); }; ComponentFromStream.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) { return nextState.vdom !== this.state.vdom; }; ComponentFromStream.prototype.componentWillUnmount = function componentWillUnmount() { // Call without arguments to complete stream this.propsEmitter.emit(); // Clean-up subscription before un-mounting this.subscription.unsubscribe(); }; ComponentFromStream.prototype.render = function render() { return this.state.vdom; }; return ComponentFromStream; }(Component); }; }; var componentFromStream = function componentFromStream(propsToVdom) { return componentFromStreamWithConfig(config)(propsToVdom); }; var identity$1 = function identity(t) { return t; }; var mapPropsStreamWithConfig = function mapPropsStreamWithConfig(config$$1) { var componentFromStream = componentFromStreamWithConfig({ fromESObservable: identity$1, toESObservable: identity$1 }); return function (transform) { return function (BaseComponent) { var factory = createFactory(BaseComponent); var fromESObservable = config$$1.fromESObservable, toESObservable = config$$1.toESObservable; return componentFromStream(function (props$) { var _ref; return _ref = { subscribe: function subscribe(observer) { var subscription = toESObservable(transform(fromESObservable(props$))).subscribe({ next: function next(childProps) { return observer.next(factory(childProps)); } }); return { unsubscribe: function unsubscribe() { return subscription.unsubscribe(); } }; } }, _ref[$$observable] = function () { return this; }, _ref; }); }; }; }; var mapPropsStream = function mapPropsStream(transform) { var hoc = mapPropsStreamWithConfig(config)(transform); if (process.env.NODE_ENV !== 'production') { return function (BaseComponent) { return setDisplayName(wrapDisplayName(BaseComponent, 'mapPropsStream'))(hoc(BaseComponent)); }; } return hoc; }; var createEventHandlerWithConfig = function createEventHandlerWithConfig(config$$1) { return function () { var _config$fromESObserva; var emitter = createChangeEmitter(); var stream = config$$1.fromESObservable((_config$fromESObserva = { subscribe: function subscribe(observer) { var unsubscribe = emitter.listen(function (value) { return observer.next(value); }); return { unsubscribe: unsubscribe }; } }, _config$fromESObserva[$$observable] = function () { return this; }, _config$fromESObserva)); return { handler: emitter.emit, stream: stream }; }; }; var createEventHandler = createEventHandlerWithConfig(config); // Higher-order component helpers export { mapProps, withProps, withPropsOnChange, withHandlers, defaultProps, renameProp, renameProps, flattenProp, withState, withStateHandlers, withReducer, branch, renderComponent, renderNothing, shouldUpdate, pure, onlyUpdateForKeys, onlyUpdateForPropTypes, withContext, getContext, lifecycle, toClass, setStatic, setPropTypes, setDisplayName, compose, getDisplayName, wrapDisplayName, shallowEqual, isClassComponent, createEagerElement, createFactory as createEagerFactory, createSink, componentFromProp, nest, hoistStatics, componentFromStream, componentFromStreamWithConfig, mapPropsStream, mapPropsStreamWithConfig, createEventHandler, configureObservable as setObservableConfig };
ajax/libs/analytics.js/2.3.17/analytics.js
SpencerCDixon/cdnjs
(function outer(modules, cache, entries){ /** * Global */ var global = (function(){ return this; })(); /** * Require `name`. * * @param {String} name * @param {Boolean} jumped * @api public */ function require(name, jumped){ if (cache[name]) return cache[name].exports; if (modules[name]) return call(name, require); throw new Error('cannot find module "' + name + '"'); } /** * Call module `id` and cache it. * * @param {Number} id * @param {Function} require * @return {Function} * @api private */ function call(id, require){ var m = cache[id] = { exports: {} }; var mod = modules[id]; var name = mod[2]; var fn = mod[0]; fn.call(m.exports, function(req){ var dep = modules[id][1][req]; return require(dep ? dep : req); }, m, m.exports, outer, modules, cache, entries); // expose as `name`. if (name) cache[name] = cache[id]; return cache[id].exports; } /** * Require all entries exposing them on global if needed. */ for (var id in entries) { if (entries[id]) { global[entries[id]] = require(id); } else { require(id); } } /** * Duo flag. */ require.duo = true; /** * Expose cache. */ require.cache = cache; /** * Expose modules */ require.modules = modules; /** * Return newest require. */ return require; })({ 1: [function(require, module, exports) { /** * Analytics.js * * (C) 2013 Segment.io Inc. */ var Integrations = require('analytics.js-integrations'); var Analytics = require('./analytics'); var each = require('each'); /** * Expose the `analytics` singleton. */ var analytics = module.exports = exports = new Analytics(); /** * Expose require */ analytics.require = require; /** * Expose `VERSION`. */ exports.VERSION = require('./version'); /** * Add integrations. */ each(Integrations, function (name, Integration) { analytics.use(Integration); }); }, {"analytics.js-integrations":2,"./analytics":3,"each":4,"./version":5}], 2: [function(require, module, exports) { /** * Module dependencies. */ var each = require('each'); var plugins = require('./integrations.js'); /** * Expose the integrations, using their own `name` from their `prototype`. */ each(plugins, function(plugin){ var name = (plugin.Integration || plugin).prototype.name; exports[name] = plugin; }); }, {"each":4,"./integrations.js":6}], 4: [function(require, module, exports) { /** * Module dependencies. */ var type = require('type'); /** * HOP reference. */ var has = Object.prototype.hasOwnProperty; /** * Iterate the given `obj` and invoke `fn(val, i)`. * * @param {String|Array|Object} obj * @param {Function} fn * @api public */ module.exports = function(obj, fn){ switch (type(obj)) { case 'array': return array(obj, fn); case 'object': if ('number' == typeof obj.length) return array(obj, fn); return object(obj, fn); case 'string': return string(obj, fn); } }; /** * Iterate string chars. * * @param {String} obj * @param {Function} fn * @api private */ function string(obj, fn) { for (var i = 0; i < obj.length; ++i) { fn(obj.charAt(i), i); } } /** * Iterate object keys. * * @param {Object} obj * @param {Function} fn * @api private */ function object(obj, fn) { for (var key in obj) { if (has.call(obj, key)) { fn(key, obj[key]); } } } /** * Iterate array-ish. * * @param {Array|Object} obj * @param {Function} fn * @api private */ function array(obj, fn) { for (var i = 0; i < obj.length; ++i) { fn(obj[i], i); } } }, {"type":7}], 7: [function(require, module, exports) { /** * toString ref. */ var toString = Object.prototype.toString; /** * Return the type of `val`. * * @param {Mixed} val * @return {String} * @api public */ module.exports = function(val){ switch (toString.call(val)) { case '[object Function]': return 'function'; case '[object Date]': return 'date'; case '[object RegExp]': return 'regexp'; case '[object Arguments]': return 'arguments'; case '[object Array]': return 'array'; case '[object String]': return 'string'; } if (val === null) return 'null'; if (val === undefined) return 'undefined'; if (val && val.nodeType === 1) return 'element'; if (val === Object(val)) return 'object'; return typeof val; }; }, {}], 6: [function(require, module, exports) { /** * DON'T EDIT THIS FILE. It's automatically generated! */ module.exports = [ require('./lib/adroll'), require('./lib/adwords'), require('./lib/alexa'), require('./lib/amplitude'), require('./lib/appcues'), require('./lib/awesm'), require('./lib/awesomatic'), require('./lib/bing-ads'), require('./lib/bronto'), require('./lib/bugherd'), require('./lib/bugsnag'), require('./lib/chartbeat'), require('./lib/churnbee'), require('./lib/clicktale'), require('./lib/clicky'), require('./lib/comscore'), require('./lib/crazy-egg'), require('./lib/curebit'), require('./lib/customerio'), require('./lib/drip'), require('./lib/errorception'), require('./lib/evergage'), require('./lib/facebook-conversion-tracking'), require('./lib/foxmetrics'), require('./lib/frontleaf'), require('./lib/gauges'), require('./lib/get-satisfaction'), require('./lib/google-analytics'), require('./lib/google-tag-manager'), require('./lib/gosquared'), require('./lib/heap'), require('./lib/hellobar'), require('./lib/hittail'), require('./lib/hublo'), require('./lib/hubspot'), require('./lib/improvely'), require('./lib/insidevault'), require('./lib/inspectlet'), require('./lib/intercom'), require('./lib/keen-io'), require('./lib/kenshoo'), require('./lib/kissmetrics'), require('./lib/klaviyo'), require('./lib/leadlander'), require('./lib/livechat'), require('./lib/lucky-orange'), require('./lib/lytics'), require('./lib/mixpanel'), require('./lib/mojn'), require('./lib/mouseflow'), require('./lib/mousestats'), require('./lib/navilytics'), require('./lib/olark'), require('./lib/optimizely'), require('./lib/perfect-audience'), require('./lib/pingdom'), require('./lib/piwik'), require('./lib/preact'), require('./lib/qualaroo'), require('./lib/quantcast'), require('./lib/rollbar'), require('./lib/saasquatch'), require('./lib/sentry'), require('./lib/snapengage'), require('./lib/spinnakr'), require('./lib/tapstream'), require('./lib/trakio'), require('./lib/twitter-ads'), require('./lib/usercycle'), require('./lib/uservoice'), require('./lib/vero'), require('./lib/visual-website-optimizer'), require('./lib/webengage'), require('./lib/woopra'), require('./lib/yandex-metrica') ]; }, {"./lib/adroll":8,"./lib/adwords":9,"./lib/alexa":10,"./lib/amplitude":11,"./lib/appcues":12,"./lib/awesm":13,"./lib/awesomatic":14,"./lib/bing-ads":15,"./lib/bronto":16,"./lib/bugherd":17,"./lib/bugsnag":18,"./lib/chartbeat":19,"./lib/churnbee":20,"./lib/clicktale":21,"./lib/clicky":22,"./lib/comscore":23,"./lib/crazy-egg":24,"./lib/curebit":25,"./lib/customerio":26,"./lib/drip":27,"./lib/errorception":28,"./lib/evergage":29,"./lib/facebook-conversion-tracking":30,"./lib/foxmetrics":31,"./lib/frontleaf":32,"./lib/gauges":33,"./lib/get-satisfaction":34,"./lib/google-analytics":35,"./lib/google-tag-manager":36,"./lib/gosquared":37,"./lib/heap":38,"./lib/hellobar":39,"./lib/hittail":40,"./lib/hublo":41,"./lib/hubspot":42,"./lib/improvely":43,"./lib/insidevault":44,"./lib/inspectlet":45,"./lib/intercom":46,"./lib/keen-io":47,"./lib/kenshoo":48,"./lib/kissmetrics":49,"./lib/klaviyo":50,"./lib/leadlander":51,"./lib/livechat":52,"./lib/lucky-orange":53,"./lib/lytics":54,"./lib/mixpanel":55,"./lib/mojn":56,"./lib/mouseflow":57,"./lib/mousestats":58,"./lib/navilytics":59,"./lib/olark":60,"./lib/optimizely":61,"./lib/perfect-audience":62,"./lib/pingdom":63,"./lib/piwik":64,"./lib/preact":65,"./lib/qualaroo":66,"./lib/quantcast":67,"./lib/rollbar":68,"./lib/saasquatch":69,"./lib/sentry":70,"./lib/snapengage":71,"./lib/spinnakr":72,"./lib/tapstream":73,"./lib/trakio":74,"./lib/twitter-ads":75,"./lib/usercycle":76,"./lib/uservoice":77,"./lib/vero":78,"./lib/visual-website-optimizer":79,"./lib/webengage":80,"./lib/woopra":81,"./lib/yandex-metrica":82}], 8: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var snake = require('to-snake-case'); var useHttps = require('use-https'); var each = require('each'); var is = require('is'); /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `AdRoll` integration. */ var AdRoll = module.exports = integration('AdRoll') .assumesPageview() .global('__adroll_loaded') .global('adroll_adv_id') .global('adroll_pix_id') .global('adroll_custom_data') .option('advId', '') .option('pixId', '') .tag('http', '<script src="http://a.adroll.com/j/roundtrip.js">') .tag('https', '<script src="https://s.adroll.com/j/roundtrip.js">') .mapping('events'); /** * Initialize. * * http://support.adroll.com/getting-started-in-4-easy-steps/#step-one * http://support.adroll.com/enhanced-conversion-tracking/ * * @param {Object} page */ AdRoll.prototype.initialize = function(page){ window.adroll_adv_id = this.options.advId; window.adroll_pix_id = this.options.pixId; window.__adroll_loaded = true; var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ AdRoll.prototype.loaded = function(){ return window.__adroll; }; /** * Page. * * http://support.adroll.com/segmenting-clicks/ * * @param {Page} page */ AdRoll.prototype.page = function(page){ var name = page.fullName(); this.track(page.track(name)); }; /** * Track. * * @param {Track} track */ AdRoll.prototype.track = function(track){ var event = track.event(); var user = this.analytics.user(); var events = this.events(event); var total = track.revenue() || track.total() || 0; var orderId = track.orderId() || 0; each(events, function(event){ var data = {}; if (user.id()) data.user_id = user.id(); data.adroll_conversion_value_in_dollars = total; data.order_id = orderId; // the adroll interface only allows for // segment names which are snake cased. data.adroll_segments = snake(event); window.__adroll.record_user(data); }); // no events found if (!events.length) { var data = {}; if (user.id()) data.user_id = user.id(); data.adroll_segments = snake(event); window.__adroll.record_user(data); } }; }, {"analytics.js-integration":83,"to-snake-case":84,"use-https":85,"each":4,"is":86}], 83: [function(require, module, exports) { /** * Module dependencies. */ var bind = require('bind'); var callback = require('callback'); var clone = require('clone'); var debug = require('debug'); var defaults = require('defaults'); var protos = require('./protos'); var slug = require('slug'); var statics = require('./statics'); /** * Expose `createIntegration`. */ module.exports = createIntegration; /** * Create a new `Integration` constructor. * * @param {String} name * @return {Function} Integration */ function createIntegration(name){ /** * Initialize a new `Integration`. * * @param {Object} options */ function Integration(options){ if (options && options.addIntegration) { // plugin return options.addIntegration(Integration); } this.debug = debug('analytics:integration:' + slug(name)); this.options = defaults(clone(options) || {}, this.defaults); this._queue = []; this.once('ready', bind(this, this.flush)); Integration.emit('construct', this); this.ready = bind(this, this.ready); this._wrapInitialize(); this._wrapPage(); this._wrapTrack(); } Integration.prototype.defaults = {}; Integration.prototype.globals = []; Integration.prototype.templates = {}; Integration.prototype.name = name; for (var key in statics) Integration[key] = statics[key]; for (var key in protos) Integration.prototype[key] = protos[key]; return Integration; } }, {"bind":87,"callback":88,"clone":89,"debug":90,"defaults":91,"./protos":92,"slug":93,"./statics":94}], 87: [function(require, module, exports) { var bind = require('bind') , bindAll = require('bind-all'); /** * Expose `bind`. */ module.exports = exports = bind; /** * Expose `bindAll`. */ exports.all = bindAll; /** * Expose `bindMethods`. */ exports.methods = bindMethods; /** * Bind `methods` on `obj` to always be called with the `obj` as context. * * @param {Object} obj * @param {String} methods... */ function bindMethods (obj, methods) { methods = [].slice.call(arguments, 1); for (var i = 0, method; method = methods[i]; i++) { obj[method] = bind(obj, obj[method]); } return obj; } }, {"bind":95,"bind-all":96}], 95: [function(require, module, exports) { /** * Slice reference. */ var slice = [].slice; /** * Bind `obj` to `fn`. * * @param {Object} obj * @param {Function|String} fn or string * @return {Function} * @api public */ module.exports = function(obj, fn){ if ('string' == typeof fn) fn = obj[fn]; if ('function' != typeof fn) throw new Error('bind() requires a function'); var args = slice.call(arguments, 2); return function(){ return fn.apply(obj, args.concat(slice.call(arguments))); } }; }, {}], 96: [function(require, module, exports) { try { var bind = require('bind'); var type = require('type'); } catch (e) { var bind = require('bind-component'); var type = require('type-component'); } module.exports = function (obj) { for (var key in obj) { var val = obj[key]; if (type(val) === 'function') obj[key] = bind(obj, obj[key]); } return obj; }; }, {"bind":95,"type":7}], 88: [function(require, module, exports) { var next = require('next-tick'); /** * Expose `callback`. */ module.exports = callback; /** * Call an `fn` back synchronously if it exists. * * @param {Function} fn */ function callback (fn) { if ('function' === typeof fn) fn(); } /** * Call an `fn` back asynchronously if it exists. If `wait` is ommitted, the * `fn` will be called on next tick. * * @param {Function} fn * @param {Number} wait (optional) */ callback.async = function (fn, wait) { if ('function' !== typeof fn) return; if (!wait) return next(fn); setTimeout(fn, wait); }; /** * Symmetry. */ callback.sync = callback; }, {"next-tick":97}], 97: [function(require, module, exports) { "use strict" if (typeof setImmediate == 'function') { module.exports = function(f){ setImmediate(f) } } // legacy node.js else if (typeof process != 'undefined' && typeof process.nextTick == 'function') { module.exports = process.nextTick } // fallback for other environments / postMessage behaves badly on IE8 else if (typeof window == 'undefined' || window.ActiveXObject || !window.postMessage) { module.exports = function(f){ setTimeout(f) }; } else { var q = []; window.addEventListener('message', function(){ var i = 0; while (i < q.length) { try { q[i++](); } catch (e) { q = q.slice(i); window.postMessage('tic!', '*'); throw e; } } q.length = 0; }, true); module.exports = function(fn){ if (!q.length) window.postMessage('tic!', '*'); q.push(fn); } } }, {}], 89: [function(require, module, exports) { /** * Module dependencies. */ var type; try { type = require('type'); } catch(e){ type = require('type-component'); } /** * Module exports. */ module.exports = clone; /** * Clones objects. * * @param {Mixed} any object * @api public */ function clone(obj){ switch (type(obj)) { case 'object': var copy = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { copy[key] = clone(obj[key]); } } return copy; case 'array': var copy = new Array(obj.length); for (var i = 0, l = obj.length; i < l; i++) { copy[i] = clone(obj[i]); } return copy; case 'regexp': // from millermedeiros/amd-utils - MIT var flags = ''; flags += obj.multiline ? 'm' : ''; flags += obj.global ? 'g' : ''; flags += obj.ignoreCase ? 'i' : ''; return new RegExp(obj.source, flags); case 'date': return new Date(obj.getTime()); default: // string, number, boolean, … return obj; } } }, {"type":7}], 90: [function(require, module, exports) { if ('undefined' == typeof window) { module.exports = require('./lib/debug'); } else { module.exports = require('./debug'); } }, {"./lib/debug":98,"./debug":99}], 98: [function(require, module, exports) { /** * Module dependencies. */ var tty = require('tty'); /** * Expose `debug()` as the module. */ module.exports = debug; /** * Enabled debuggers. */ var names = [] , skips = []; (process.env.DEBUG || '') .split(/[\s,]+/) .forEach(function(name){ name = name.replace('*', '.*?'); if (name[0] === '-') { skips.push(new RegExp('^' + name.substr(1) + '$')); } else { names.push(new RegExp('^' + name + '$')); } }); /** * Colors. */ var colors = [6, 2, 3, 4, 5, 1]; /** * Previous debug() call. */ var prev = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Is stdout a TTY? Colored output is disabled when `true`. */ var isatty = tty.isatty(2); /** * Select a color. * * @return {Number} * @api private */ function color() { return colors[prevColor++ % colors.length]; } /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ function humanize(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; } /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { function disabled(){} disabled.enabled = false; var match = skips.some(function(re){ return re.test(name); }); if (match) return disabled; match = names.some(function(re){ return re.test(name); }); if (!match) return disabled; var c = color(); function colored(fmt) { fmt = coerce(fmt); var curr = new Date; var ms = curr - (prev[name] || curr); prev[name] = curr; fmt = ' \u001b[9' + c + 'm' + name + ' ' + '\u001b[3' + c + 'm\u001b[90m' + fmt + '\u001b[3' + c + 'm' + ' +' + humanize(ms) + '\u001b[0m'; console.error.apply(this, arguments); } function plain(fmt) { fmt = coerce(fmt); fmt = new Date().toUTCString() + ' ' + name + ' ' + fmt; console.error.apply(this, arguments); } colored.enabled = plain.enabled = true; return isatty || process.env.DEBUG_COLORS ? colored : plain; } /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } }, {}], 99: [function(require, module, exports) { /** * Expose `debug()` as the module. */ module.exports = debug; /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { if (!debug.enabled(name)) return function(){}; return function(fmt){ fmt = coerce(fmt); var curr = new Date; var ms = curr - (debug[name] || curr); debug[name] = curr; fmt = name + ' ' + fmt + ' +' + debug.humanize(ms); // This hackery is required for IE8 // where `console.log` doesn't have 'apply' window.console && console.log && Function.prototype.apply.call(console.log, console, arguments); } } /** * The currently active debug mode names. */ debug.names = []; debug.skips = []; /** * Enables a debug mode by name. This can include modes * separated by a colon and wildcards. * * @param {String} name * @api public */ debug.enable = function(name) { try { localStorage.debug = name; } catch(e){} var split = (name || '').split(/[\s,]+/) , len = split.length; for (var i = 0; i < len; i++) { name = split[i].replace('*', '.*?'); if (name[0] === '-') { debug.skips.push(new RegExp('^' + name.substr(1) + '$')); } else { debug.names.push(new RegExp('^' + name + '$')); } } }; /** * Disable debug output. * * @api public */ debug.disable = function(){ debug.enable(''); }; /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ debug.humanize = function(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; }; /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ debug.enabled = function(name) { for (var i = 0, len = debug.skips.length; i < len; i++) { if (debug.skips[i].test(name)) { return false; } } for (var i = 0, len = debug.names.length; i < len; i++) { if (debug.names[i].test(name)) { return true; } } return false; }; /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } // persist try { if (window.localStorage) debug.enable(localStorage.debug); } catch(e){} }, {}], 91: [function(require, module, exports) { 'use strict'; /** * Merge default values. * * @param {Object} dest * @param {Object} defaults * @return {Object} * @api public */ var defaults = function (dest, src, recursive) { for (var prop in src) { if (recursive && dest[prop] instanceof Object && src[prop] instanceof Object) { dest[prop] = defaults(dest[prop], src[prop], true); } else if (! (prop in dest)) { dest[prop] = src[prop]; } } return dest; }; /** * Expose `defaults`. */ module.exports = defaults; }, {}], 92: [function(require, module, exports) { /** * Module dependencies. */ var loadScript = require('segmentio/load-script'); var normalize = require('to-no-case'); var callback = require('callback'); var Emitter = require('emitter'); var events = require('./events'); var tick = require('next-tick'); var assert = require('assert'); var after = require('after'); var each = require('component/each'); var type = require('type'); var fmt = require('yields/fmt'); /** * Window defaults. */ var setTimeout = window.setTimeout; var setInterval = window.setInterval; var onerror = null; var onload = null; /** * Mixin emitter. */ Emitter(exports); /** * Initialize. */ exports.initialize = function(){ var ready = this.ready; tick(ready); }; /** * Loaded? * * @return {Boolean} * @api private */ exports.loaded = function(){ return false; }; /** * Load. * * @param {Function} cb */ exports.load = function(cb){ callback.async(cb); }; /** * Page. * * @param {Page} page */ exports.page = function(page){}; /** * Track. * * @param {Track} track */ exports.track = function(track){}; /** * Get events that match `str`. * * Examples: * * events = { my_event: 'a4991b88' } * .map(events, 'My Event'); * // => ["a4991b88"] * .map(events, 'whatever'); * // => [] * * events = [{ key: 'my event', value: '9b5eb1fa' }] * .map(events, 'my_event'); * // => ["9b5eb1fa"] * .map(events, 'whatever'); * // => [] * * @param {String} str * @return {Array} * @api public */ exports.map = function(obj, str){ var a = normalize(str); var ret = []; // noop if (!obj) return ret; // object if ('object' == type(obj)) { for (var k in obj) { var item = obj[k]; var b = normalize(k); if (b == a) ret.push(item); } } // array if ('array' == type(obj)) { if (!obj.length) return ret; if (!obj[0].key) return ret; for (var i = 0; i < obj.length; ++i) { var item = obj[i]; var b = normalize(item.key); if (b == a) ret.push(item.value); } } return ret; }; /** * Invoke a `method` that may or may not exist on the prototype with `args`, * queueing or not depending on whether the integration is "ready". Don't * trust the method call, since it contains integration party code. * * @param {String} method * @param {Mixed} args... * @api private */ exports.invoke = function(method){ if (!this[method]) return; var args = [].slice.call(arguments, 1); if (!this._ready) return this.queue(method, args); var ret; try { this.debug('%s with %o', method, args); ret = this[method].apply(this, args); } catch (e) { this.debug('error %o calling %s with %o', e, method, args); } return ret; }; /** * Queue a `method` with `args`. If the integration assumes an initial * pageview, then let the first call to `page` pass through. * * @param {String} method * @param {Array} args * @api private */ exports.queue = function(method, args){ if ('page' == method && this._assumesPageview && !this._initialized) { return this.page.apply(this, args); } this._queue.push({ method: method, args: args }); }; /** * Flush the internal queue. * * @api private */ exports.flush = function(){ this._ready = true; var call; while (call = this._queue.shift()) this[call.method].apply(this, call.args); }; /** * Reset the integration, removing its global variables. * * @api private */ exports.reset = function(){ for (var i = 0, key; key = this.globals[i]; i++) window[key] = undefined; window.setTimeout = setTimeout; window.setInterval = setInterval; window.onerror = onerror; window.onload = onload; }; /** * Load a tag by `name`. * * @param {String} name * @param {Function} [fn] */ exports.load = function(name, locals, fn){ if ('function' == typeof name) fn = name, locals = null, name = null; if (name && 'object' == typeof name) fn = locals, locals = name, name = null; if ('function' == typeof locals) fn = locals, locals = null; name = name || 'library'; locals = locals || {}; locals = this.locals(locals); var template = this.templates[name]; assert(template, fmt('Template "%s" not defined.', name)); var attrs = render(template, locals); var el; switch (template.type) { case 'img': attrs.width = 1; attrs.height = 1; el = loadImage(attrs, fn); break; case 'script': el = loadScript(attrs, fn); // TODO: hack until refactoring load-script delete attrs.src; each(attrs, function(key, val){ el.setAttribute(key, val); }); break; case 'iframe': el = loadIframe(attrs, fn); break; } return el; }; /** * Locals for tag templates. * * By default it includes a cache buster, * and all of the options. * * @param {Object} [locals] * @return {Object} */ exports.locals = function(locals){ locals = locals || {}; var cache = Math.floor(new Date().getTime() / 3600000); if (!locals.hasOwnProperty('cache')) locals.cache = cache; each(this.options, function(key, val){ if (!locals.hasOwnProperty(key)) locals[key] = val; }); return locals; }; /** * Simple way to emit ready. */ exports.ready = function(){ this.emit('ready'); }; /** * Wrap the initialize method in an exists check, so we don't have to do it for * every single integration. * * @api private */ exports._wrapInitialize = function(){ var initialize = this.initialize; this.initialize = function(){ this.debug('initialize'); this._initialized = true; var ret = initialize.apply(this, arguments); this.emit('initialize'); return ret; }; if (this._assumesPageview) this.initialize = after(2, this.initialize); }; /** * Wrap the page method to call `initialize` instead if the integration assumes * a pageview. * * @api private */ exports._wrapPage = function(){ var page = this.page; this.page = function(){ if (this._assumesPageview && !this._initialized) { return this.initialize.apply(this, arguments); } return page.apply(this, arguments); }; }; /** * Wrap the track method to call other ecommerce methods if * available depending on the `track.event()`. * * @api private */ exports._wrapTrack = function(){ var t = this.track; this.track = function(track){ var event = track.event(); var called; var ret; for (var method in events) { var regexp = events[method]; if (!this[method]) continue; if (!regexp.test(event)) continue; ret = this[method].apply(this, arguments); called = true; break; } if (!called) ret = t.apply(this, arguments); return ret; }; }; function loadImage(attrs, fn) { fn = fn || function(){}; var img = new Image; img.onerror = error(fn, 'failed to load pixel', img); img.onload = function(){ fn(); }; img.src = attrs.src; img.width = 1; img.height = 1; return img; } function error(fn, message, img){ return function(e){ e = e || window.event; var err = new Error(message); err.event = e; err.source = img; fn(err); }; } /** * Render template + locals into an `attrs` object. * * @param {Object} template * @param {Object} locals * @return {Object} */ function render(template, locals) { var attrs = {}; each(template.attrs, function(key, val){ attrs[key] = val.replace(/\{\{\ *(\w+)\ *\}\}/g, function(_, $1){ return locals[$1]; }); }); return attrs; } }, {"segmentio/load-script":100,"to-no-case":101,"callback":88,"emitter":102,"./events":103,"next-tick":97,"assert":104,"after":105,"component/each":106,"type":7,"yields/fmt":107}], 100: [function(require, module, exports) { /** * Module dependencies. */ var onload = require('script-onload'); var tick = require('next-tick'); var type = require('type'); /** * Expose `loadScript`. * * @param {Object} options * @param {Function} fn * @api public */ module.exports = function loadScript(options, fn){ if (!options) throw new Error('Cant load nothing...'); // Allow for the simplest case, just passing a `src` string. if ('string' == type(options)) options = { src : options }; var https = document.location.protocol === 'https:' || document.location.protocol === 'chrome-extension:'; // If you use protocol relative URLs, third-party scripts like Google // Analytics break when testing with `file:` so this fixes that. if (options.src && options.src.indexOf('//') === 0) { options.src = https ? 'https:' + options.src : 'http:' + options.src; } // Allow them to pass in different URLs depending on the protocol. if (https && options.https) options.src = options.https; else if (!https && options.http) options.src = options.http; // Make the `<script>` element and insert it before the first script on the // page, which is guaranteed to exist since this Javascript is running. var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = options.src; // If we have a fn, attach event handlers, even in IE. Based off of // the Third-Party Javascript script loading example: // https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html if ('function' == type(fn)) { onload(script, fn); } tick(function(){ // Append after event listeners are attached for IE. var firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(script, firstScript); }); // Return the script element in case they want to do anything special, like // give it an ID or attributes. return script; }; }, {"script-onload":108,"next-tick":97,"type":7}], 108: [function(require, module, exports) { // https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html /** * Invoke `fn(err)` when the given `el` script loads. * * @param {Element} el * @param {Function} fn * @api public */ module.exports = function(el, fn){ return el.addEventListener ? add(el, fn) : attach(el, fn); }; /** * Add event listener to `el`, `fn()`. * * @param {Element} el * @param {Function} fn * @api private */ function add(el, fn){ el.addEventListener('load', function(_, e){ fn(null, e); }, false); el.addEventListener('error', function(e){ var err = new Error('failed to load the script "' + el.src + '"'); err.event = e; fn(err); }, false); } /** * Attach evnet. * * @param {Element} el * @param {Function} fn * @api private */ function attach(el, fn){ el.attachEvent('onreadystatechange', function(e){ if (!/complete|loaded/.test(el.readyState)) return; fn(null, e); }); } }, {}], 101: [function(require, module, exports) { /** * Expose `toNoCase`. */ module.exports = toNoCase; /** * Test whether a string is camel-case. */ var hasSpace = /\s/; var hasSeparator = /[\W_]/; /** * Remove any starting case from a `string`, like camel or snake, but keep * spaces and punctuation that may be important otherwise. * * @param {String} string * @return {String} */ function toNoCase (string) { if (hasSpace.test(string)) return string.toLowerCase(); if (hasSeparator.test(string)) return unseparate(string).toLowerCase(); return uncamelize(string).toLowerCase(); } /** * Separator splitter. */ var separatorSplitter = /[\W_]+(.|$)/g; /** * Un-separate a `string`. * * @param {String} string * @return {String} */ function unseparate (string) { return string.replace(separatorSplitter, function (m, next) { return next ? ' ' + next : ''; }); } /** * Camelcase splitter. */ var camelSplitter = /(.)([A-Z]+)/g; /** * Un-camelcase a `string`. * * @param {String} string * @return {String} */ function uncamelize (string) { return string.replace(camelSplitter, function (m, previous, uppers) { return previous + ' ' + uppers.toLowerCase().split('').join(' '); }); } }, {}], 102: [function(require, module, exports) { /** * Module dependencies. */ var index = require('indexof'); /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } fn._off = on; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var i = index(callbacks, fn._off || fn); if (~i) callbacks.splice(i, 1); return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; }, {"indexof":109}], 109: [function(require, module, exports) { module.exports = function(arr, obj){ if (arr.indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; }, {}], 103: [function(require, module, exports) { /** * Expose `events`. */ module.exports = { removedProduct: /removed[ _]?product/i, viewedProduct: /viewed[ _]?product/i, addedProduct: /added[ _]?product/i, completedOrder: /completed[ _]?order/i }; }, {}], 104: [function(require, module, exports) { /** * Module dependencies. */ var equals = require('equals'); var fmt = require('fmt'); var stack = require('stack'); /** * Assert `expr` with optional failure `msg`. * * @param {Mixed} expr * @param {String} [msg] * @api public */ module.exports = exports = function (expr, msg) { if (expr) return; throw new Error(msg || message()); }; /** * Assert `actual` is weak equal to `expected`. * * @param {Mixed} actual * @param {Mixed} expected * @param {String} [msg] * @api public */ exports.equal = function (actual, expected, msg) { if (actual == expected) return; throw new Error(msg || fmt('Expected %o to equal %o.', actual, expected)); }; /** * Assert `actual` is not weak equal to `expected`. * * @param {Mixed} actual * @param {Mixed} expected * @param {String} [msg] * @api public */ exports.notEqual = function (actual, expected, msg) { if (actual != expected) return; throw new Error(msg || fmt('Expected %o not to equal %o.', actual, expected)); }; /** * Assert `actual` is deep equal to `expected`. * * @param {Mixed} actual * @param {Mixed} expected * @param {String} [msg] * @api public */ exports.deepEqual = function (actual, expected, msg) { if (equals(actual, expected)) return; throw new Error(msg || fmt('Expected %o to deeply equal %o.', actual, expected)); }; /** * Assert `actual` is not deep equal to `expected`. * * @param {Mixed} actual * @param {Mixed} expected * @param {String} [msg] * @api public */ exports.notDeepEqual = function (actual, expected, msg) { if (!equals(actual, expected)) return; throw new Error(msg || fmt('Expected %o not to deeply equal %o.', actual, expected)); }; /** * Assert `actual` is strict equal to `expected`. * * @param {Mixed} actual * @param {Mixed} expected * @param {String} [msg] * @api public */ exports.strictEqual = function (actual, expected, msg) { if (actual === expected) return; throw new Error(msg || fmt('Expected %o to strictly equal %o.', actual, expected)); }; /** * Assert `actual` is not strict equal to `expected`. * * @param {Mixed} actual * @param {Mixed} expected * @param {String} [msg] * @api public */ exports.notStrictEqual = function (actual, expected, msg) { if (actual !== expected) return; throw new Error(msg || fmt('Expected %o not to strictly equal %o.', actual, expected)); }; /** * Assert `block` throws an `error`. * * @param {Function} block * @param {Function} [error] * @param {String} [msg] * @api public */ exports.throws = function (block, error, msg) { var err; try { block(); } catch (e) { err = e; } if (!err) throw new Error(msg || fmt('Expected %s to throw an error.', block.toString())); if (error && !(err instanceof error)) { throw new Error(msg || fmt('Expected %s to throw an %o.', block.toString(), error)); } }; /** * Assert `block` doesn't throw an `error`. * * @param {Function} block * @param {Function} [error] * @param {String} [msg] * @api public */ exports.doesNotThrow = function (block, error, msg) { var err; try { block(); } catch (e) { err = e; } if (err) throw new Error(msg || fmt('Expected %s not to throw an error.', block.toString())); if (error && (err instanceof error)) { throw new Error(msg || fmt('Expected %s not to throw an %o.', block.toString(), error)); } }; /** * Create a message from the call stack. * * @return {String} * @api private */ function message() { if (!Error.captureStackTrace) return 'assertion failed'; var callsite = stack()[2]; var fn = callsite.getFunctionName(); var file = callsite.getFileName(); var line = callsite.getLineNumber() - 1; var col = callsite.getColumnNumber() - 1; var src = get(file); line = src.split('\n')[line].slice(col); var m = line.match(/assert\((.*)\)/); return m && m[1].trim(); } /** * Load contents of `script`. * * @param {String} script * @return {String} * @api private */ function get(script) { var xhr = new XMLHttpRequest; xhr.open('GET', script, false); xhr.send(null); return xhr.responseText; } }, {"equals":110,"fmt":107,"stack":111}], 110: [function(require, module, exports) { var type = require('type') /** * expose equals */ module.exports = equals equals.compare = compare /** * assert all values are equal * * @param {Any} [...] * @return {Boolean} */ function equals(){ var i = arguments.length - 1 while (i > 0) { if (!compare(arguments[i], arguments[--i])) return false } return true } // (any, any, [array]) -> boolean function compare(a, b, memos){ // All identical values are equivalent if (a === b) return true var fnA = types[type(a)] var fnB = types[type(b)] return fnA && fnA === fnB ? fnA(a, b, memos) : false } var types = {} // (Number) -> boolean types.number = function(a){ // NaN check return a !== a } // (function, function, array) -> boolean types['function'] = function(a, b, memos){ return a.toString() === b.toString() // Functions can act as objects && types.object(a, b, memos) && compare(a.prototype, b.prototype) } // (date, date) -> boolean types.date = function(a, b){ return +a === +b } // (regexp, regexp) -> boolean types.regexp = function(a, b){ return a.toString() === b.toString() } // (DOMElement, DOMElement) -> boolean types.element = function(a, b){ return a.outerHTML === b.outerHTML } // (textnode, textnode) -> boolean types.textnode = function(a, b){ return a.textContent === b.textContent } // decorate `fn` to prevent it re-checking objects // (function) -> function function memoGaurd(fn){ return function(a, b, memos){ if (!memos) return fn(a, b, []) var i = memos.length, memo while (memo = memos[--i]) { if (memo[0] === a && memo[1] === b) return true } return fn(a, b, memos) } } types['arguments'] = types.array = memoGaurd(compareArrays) // (array, array, array) -> boolean function compareArrays(a, b, memos){ var i = a.length if (i !== b.length) return false memos.push([a, b]) while (i--) { if (!compare(a[i], b[i], memos)) return false } return true } types.object = memoGaurd(compareObjects) // (object, object, array) -> boolean function compareObjects(a, b, memos) { var ka = getEnumerableProperties(a) var kb = getEnumerableProperties(b) var i = ka.length // same number of properties if (i !== kb.length) return false // although not necessarily the same order ka.sort() kb.sort() // cheap key test while (i--) if (ka[i] !== kb[i]) return false // remember memos.push([a, b]) // iterate again this time doing a thorough check i = ka.length while (i--) { var key = ka[i] if (!compare(a[key], b[key], memos)) return false } return true } // (object) -> array function getEnumerableProperties (object) { var result = [] for (var k in object) if (k !== 'constructor') { result.push(k) } return result } }, {"type":112}], 112: [function(require, module, exports) { var toString = {}.toString var DomNode = typeof window != 'undefined' ? window.Node : Function /** * Return the type of `val`. * * @param {Mixed} val * @return {String} * @api public */ module.exports = exports = function(x){ var type = typeof x if (type != 'object') return type type = types[toString.call(x)] if (type) return type if (x instanceof DomNode) switch (x.nodeType) { case 1: return 'element' case 3: return 'text-node' case 9: return 'document' case 11: return 'document-fragment' default: return 'dom-node' } } var types = exports.types = { '[object Function]': 'function', '[object Date]': 'date', '[object RegExp]': 'regexp', '[object Arguments]': 'arguments', '[object Array]': 'array', '[object String]': 'string', '[object Null]': 'null', '[object Undefined]': 'undefined', '[object Number]': 'number', '[object Boolean]': 'boolean', '[object Object]': 'object', '[object Text]': 'text-node', '[object Uint8Array]': 'bit-array', '[object Uint16Array]': 'bit-array', '[object Uint32Array]': 'bit-array', '[object Uint8ClampedArray]': 'bit-array', '[object Error]': 'error', '[object FormData]': 'form-data', '[object File]': 'file', '[object Blob]': 'blob' } }, {}], 107: [function(require, module, exports) { /** * Export `fmt` */ module.exports = fmt; /** * Formatters */ fmt.o = JSON.stringify; fmt.s = String; fmt.d = parseInt; /** * Format the given `str`. * * @param {String} str * @param {...} args * @return {String} * @api public */ function fmt(str){ var args = [].slice.call(arguments, 1); var j = 0; return str.replace(/%([a-z])/gi, function(_, f){ return fmt[f] ? fmt[f](args[j++]) : _ + f; }); } }, {}], 111: [function(require, module, exports) { /** * Expose `stack()`. */ module.exports = stack; /** * Return the stack. * * @return {Array} * @api public */ function stack() { var orig = Error.prepareStackTrace; Error.prepareStackTrace = function(_, stack){ return stack; }; var err = new Error; Error.captureStackTrace(err, arguments.callee); var stack = err.stack; Error.prepareStackTrace = orig; return stack; } }, {}], 105: [function(require, module, exports) { module.exports = function after (times, func) { // After 0, really? if (times <= 0) return func(); // That's more like it. return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; }, {}], 106: [function(require, module, exports) { /** * Module dependencies. */ try { var type = require('type'); } catch (err) { var type = require('component-type'); } var toFunction = require('to-function'); /** * HOP reference. */ var has = Object.prototype.hasOwnProperty; /** * Iterate the given `obj` and invoke `fn(val, i)` * in optional context `ctx`. * * @param {String|Array|Object} obj * @param {Function} fn * @param {Object} [ctx] * @api public */ module.exports = function(obj, fn, ctx){ fn = toFunction(fn); ctx = ctx || this; switch (type(obj)) { case 'array': return array(obj, fn, ctx); case 'object': if ('number' == typeof obj.length) return array(obj, fn, ctx); return object(obj, fn, ctx); case 'string': return string(obj, fn, ctx); } }; /** * Iterate string chars. * * @param {String} obj * @param {Function} fn * @param {Object} ctx * @api private */ function string(obj, fn, ctx) { for (var i = 0; i < obj.length; ++i) { fn.call(ctx, obj.charAt(i), i); } } /** * Iterate object keys. * * @param {Object} obj * @param {Function} fn * @param {Object} ctx * @api private */ function object(obj, fn, ctx) { for (var key in obj) { if (has.call(obj, key)) { fn.call(ctx, key, obj[key]); } } } /** * Iterate array-ish. * * @param {Array|Object} obj * @param {Function} fn * @param {Object} ctx * @api private */ function array(obj, fn, ctx) { for (var i = 0; i < obj.length; ++i) { fn.call(ctx, obj[i], i); } } }, {"type":7,"component-type":7,"to-function":113}], 113: [function(require, module, exports) { /** * Module Dependencies */ var expr; try { expr = require('props'); } catch(e) { expr = require('component-props'); } /** * Expose `toFunction()`. */ module.exports = toFunction; /** * Convert `obj` to a `Function`. * * @param {Mixed} obj * @return {Function} * @api private */ function toFunction(obj) { switch ({}.toString.call(obj)) { case '[object Object]': return objectToFunction(obj); case '[object Function]': return obj; case '[object String]': return stringToFunction(obj); case '[object RegExp]': return regexpToFunction(obj); default: return defaultToFunction(obj); } } /** * Default to strict equality. * * @param {Mixed} val * @return {Function} * @api private */ function defaultToFunction(val) { return function(obj){ return val === obj; }; } /** * Convert `re` to a function. * * @param {RegExp} re * @return {Function} * @api private */ function regexpToFunction(re) { return function(obj){ return re.test(obj); }; } /** * Convert property `str` to a function. * * @param {String} str * @return {Function} * @api private */ function stringToFunction(str) { // immediate such as "> 20" if (/^ *\W+/.test(str)) return new Function('_', 'return _ ' + str); // properties such as "name.first" or "age > 18" or "age > 18 && age < 36" return new Function('_', 'return ' + get(str)); } /** * Convert `object` to a function. * * @param {Object} object * @return {Function} * @api private */ function objectToFunction(obj) { var match = {}; for (var key in obj) { match[key] = typeof obj[key] === 'string' ? defaultToFunction(obj[key]) : toFunction(obj[key]); } return function(val){ if (typeof val !== 'object') return false; for (var key in match) { if (!(key in val)) return false; if (!match[key](val[key])) return false; } return true; }; } /** * Built the getter function. Supports getter style functions * * @param {String} str * @return {String} * @api private */ function get(str) { var props = expr(str); if (!props.length) return '_.' + str; var val, i, prop; for (i = 0; i < props.length; i++) { prop = props[i]; val = '_.' + prop; val = "('function' == typeof " + val + " ? " + val + "() : " + val + ")"; // mimic negative lookbehind to avoid problems with nested properties str = stripNested(prop, str, val); } return str; } /** * Mimic negative lookbehind to avoid problems with nested properties. * * See: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript * * @param {String} prop * @param {String} str * @param {String} val * @return {String} * @api private */ function stripNested (prop, str, val) { return str.replace(new RegExp('(\\.)?' + prop, 'g'), function($0, $1) { return $1 ? $0 : val; }); } }, {"props":114,"component-props":114}], 114: [function(require, module, exports) { /** * Global Names */ var globals = /\b(this|Array|Date|Object|Math|JSON)\b/g; /** * Return immediate identifiers parsed from `str`. * * @param {String} str * @param {String|Function} map function or prefix * @return {Array} * @api public */ module.exports = function(str, fn){ var p = unique(props(str)); if (fn && 'string' == typeof fn) fn = prefixed(fn); if (fn) return map(str, p, fn); return p; }; /** * Return immediate identifiers in `str`. * * @param {String} str * @return {Array} * @api private */ function props(str) { return str .replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g, '') .replace(globals, '') .match(/[$a-zA-Z_]\w*/g) || []; } /** * Return `str` with `props` mapped with `fn`. * * @param {String} str * @param {Array} props * @param {Function} fn * @return {String} * @api private */ function map(str, props, fn) { var re = /\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g; return str.replace(re, function(_){ if ('(' == _[_.length - 1]) return fn(_); if (!~props.indexOf(_)) return _; return fn(_); }); } /** * Return unique array. * * @param {Array} arr * @return {Array} * @api private */ function unique(arr) { var ret = []; for (var i = 0; i < arr.length; i++) { if (~ret.indexOf(arr[i])) continue; ret.push(arr[i]); } return ret; } /** * Map with prefix `str`. */ function prefixed(str) { return function(_){ return str + _; }; } }, {}], 93: [function(require, module, exports) { /** * Generate a slug from the given `str`. * * example: * * generate('foo bar'); * // > foo-bar * * @param {String} str * @param {Object} options * @config {String|RegExp} [replace] characters to replace, defaulted to `/[^a-z0-9]/g` * @config {String} [separator] separator to insert, defaulted to `-` * @return {String} */ module.exports = function (str, options) { options || (options = {}); return str.toLowerCase() .replace(options.replace || /[^a-z0-9]/g, ' ') .replace(/^ +| +$/g, '') .replace(/ +/g, options.separator || '-') }; }, {}], 94: [function(require, module, exports) { /** * Module dependencies. */ var after = require('after'); var domify = require('component/domify'); var each = require('component/each'); var Emitter = require('emitter'); /** * Mixin emitter. */ Emitter(exports); /** * Add a new option to the integration by `key` with default `value`. * * @param {String} key * @param {Mixed} value * @return {Integration} */ exports.option = function(key, value){ this.prototype.defaults[key] = value; return this; }; /** * Add a new mapping option. * * This will create a method `name` that will return a mapping * for you to use. * * Example: * * Integration('My Integration') * .mapping('events'); * * new MyIntegration().track('My Event'); * * .track = function(track){ * var events = this.events(track.event()); * each(events, send); * }; * * @param {String} name * @return {Integration} */ exports.mapping = function(name){ this.option(name, []); this.prototype[name] = function(str){ return this.map(this.options[name], str); }; return this; }; /** * Register a new global variable `key` owned by the integration, which will be * used to test whether the integration is already on the page. * * @param {String} global * @return {Integration} */ exports.global = function(key){ this.prototype.globals.push(key); return this; }; /** * Mark the integration as assuming an initial pageview, so to defer loading * the script until the first `page` call, noop the first `initialize`. * * @return {Integration} */ exports.assumesPageview = function(){ this.prototype._assumesPageview = true; return this; }; /** * Mark the integration as being "ready" once `load` is called. * * @return {Integration} */ exports.readyOnLoad = function(){ this.prototype._readyOnLoad = true; return this; }; /** * Mark the integration as being "ready" once `initialize` is called. * * @return {Integration} */ exports.readyOnInitialize = function(){ this.prototype._readyOnInitialize = true; return this; }; /** * Define a tag to be loaded. * * @param {String} str DOM tag as string or URL * @return {Integration} */ exports.tag = function(name, str){ if (null == str) { str = name; name = 'library'; } this.prototype.templates[name] = objectify(str); return this; }; /** * Given a string, give back DOM attributes. * * Do it in a way where the browser doesn't load images or iframes. * It turns out, domify will load images/iframes, because * whenever you construct those DOM elements, * the browser immediately loads them. * * @param {String} str * @return {Object} */ function objectify(str) { // replace `src` with `data-src` to prevent image loading str = str.replace(' src="', ' data-src="'); var el = domify(str); var attrs = {}; each(el.attributes, function(attr){ // then replace it back var name = 'data-src' == attr.name ? 'src' : attr.name; attrs[name] = attr.value; }); return { type: el.tagName.toLowerCase(), attrs: attrs }; } }, {"after":105,"component/domify":115,"component/each":106,"emitter":102}], 115: [function(require, module, exports) { /** * Expose `parse`. */ module.exports = parse; /** * Tests for browser support. */ var div = document.createElement('div'); // Setup div.innerHTML = ' <link/><table></table><a href="/a">a</a><input type="checkbox"/>'; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE var innerHTMLBug = !div.getElementsByTagName('link').length; div = undefined; /** * Wrap map from jquery. */ var map = { legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], // for script/link/style tags to work in IE6-8, you have to wrap // in a div with a non-whitespace character in front, ha! _default: innerHTMLBug ? [1, 'X<div>', '</div>'] : [0, '', ''] }; map.td = map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>']; map.option = map.optgroup = [1, '<select multiple="multiple">', '</select>']; map.thead = map.tbody = map.colgroup = map.caption = map.tfoot = [1, '<table>', '</table>']; map.text = map.circle = map.ellipse = map.line = map.path = map.polygon = map.polyline = map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>']; /** * Parse `html` and return a DOM Node instance, which could be a TextNode, * HTML DOM Node of some kind (<div> for example), or a DocumentFragment * instance, depending on the contents of the `html` string. * * @param {String} html - HTML string to "domify" * @param {Document} doc - The `document` instance to create the Node for * @return {DOMNode} the TextNode, DOM Node, or DocumentFragment instance * @api private */ function parse(html, doc) { if ('string' != typeof html) throw new TypeError('String expected'); // default to the global `document` object if (!doc) doc = document; // tag name var m = /<([\w:]+)/.exec(html); if (!m) return doc.createTextNode(html); html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace var tag = m[1]; // body support if (tag == 'body') { var el = doc.createElement('html'); el.innerHTML = html; return el.removeChild(el.lastChild); } // wrap map var wrap = map[tag] || map._default; var depth = wrap[0]; var prefix = wrap[1]; var suffix = wrap[2]; var el = doc.createElement('div'); el.innerHTML = prefix + html + suffix; while (depth--) el = el.lastChild; // one element if (el.firstChild == el.lastChild) { return el.removeChild(el.firstChild); } // several elements var fragment = doc.createDocumentFragment(); while (el.firstChild) { fragment.appendChild(el.removeChild(el.firstChild)); } return fragment; } }, {}], 84: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toSnakeCase`. */ module.exports = toSnakeCase; /** * Convert a `string` to snake case. * * @param {String} string * @return {String} */ function toSnakeCase (string) { return toSpace(string).replace(/\s/g, '_'); } }, {"to-space-case":116}], 116: [function(require, module, exports) { var clean = require('to-no-case'); /** * Expose `toSpaceCase`. */ module.exports = toSpaceCase; /** * Convert a `string` to space case. * * @param {String} string * @return {String} */ function toSpaceCase (string) { return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) { return match ? ' ' + match : ''; }); } }, {"to-no-case":117}], 117: [function(require, module, exports) { /** * Expose `toNoCase`. */ module.exports = toNoCase; /** * Test whether a string is camel-case. */ var hasSpace = /\s/; var hasCamel = /[a-z][A-Z]/; var hasSeparator = /[\W_]/; /** * Remove any starting case from a `string`, like camel or snake, but keep * spaces and punctuation that may be important otherwise. * * @param {String} string * @return {String} */ function toNoCase (string) { if (hasSpace.test(string)) return string.toLowerCase(); if (hasSeparator.test(string)) string = unseparate(string); if (hasCamel.test(string)) string = uncamelize(string); return string.toLowerCase(); } /** * Separator splitter. */ var separatorSplitter = /[\W_]+(.|$)/g; /** * Un-separate a `string`. * * @param {String} string * @return {String} */ function unseparate (string) { return string.replace(separatorSplitter, function (m, next) { return next ? ' ' + next : ''; }); } /** * Camelcase splitter. */ var camelSplitter = /(.)([A-Z]+)/g; /** * Un-camelcase a `string`. * * @param {String} string * @return {String} */ function uncamelize (string) { return string.replace(camelSplitter, function (m, previous, uppers) { return previous + ' ' + uppers.toLowerCase().split('').join(' '); }); } }, {}], 85: [function(require, module, exports) { /** * Protocol. */ module.exports = function (url) { switch (arguments.length) { case 0: return check(); case 1: return transform(url); } }; /** * Transform a protocol-relative `url` to the use the proper protocol. * * @param {String} url * @return {String} */ function transform (url) { return check() ? 'https:' + url : 'http:' + url; } /** * Check whether `https:` be used for loading scripts. * * @return {Boolean} */ function check () { return ( location.protocol == 'https:' || location.protocol == 'chrome-extension:' ); } }, {}], 86: [function(require, module, exports) { var isEmpty = require('is-empty'); try { var typeOf = require('type'); } catch (e) { var typeOf = require('component-type'); } /** * Types. */ var types = [ 'arguments', 'array', 'boolean', 'date', 'element', 'function', 'null', 'number', 'object', 'regexp', 'string', 'undefined' ]; /** * Expose type checkers. * * @param {Mixed} value * @return {Boolean} */ for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type); /** * Add alias for `function` for old browsers. */ exports.fn = exports['function']; /** * Expose `empty` check. */ exports.empty = isEmpty; /** * Expose `nan` check. */ exports.nan = function (val) { return exports.number(val) && val != val; }; /** * Generate a type checker. * * @param {String} type * @return {Function} */ function generate (type) { return function (value) { return type === typeOf(value); }; } }, {"is-empty":118,"type":7,"component-type":7}], 118: [function(require, module, exports) { /** * Expose `isEmpty`. */ module.exports = isEmpty; /** * Has. */ var has = Object.prototype.hasOwnProperty; /** * Test whether a value is "empty". * * @param {Mixed} val * @return {Boolean} */ function isEmpty (val) { if (null == val) return true; if ('number' == typeof val) return 0 === val; if (undefined !== val.length) return 0 === val.length; for (var key in val) if (has.call(val, key)) return false; return true; } }, {}], 9: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var domify = require('domify'); var each = require('each'); /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `AdWords`. */ var AdWords = module.exports = integration('AdWords') .option('conversionId', '') .option('remarketing', false) .tag('<script src="//www.googleadservices.com/pagead/conversion_async.js">') .mapping('events'); /** * Load. * * @param {Function} fn * @api public */ AdWords.prototype.initialize = function(){ this.load(this.ready); }; /** * Loaded. * * @return {Boolean} * @api public */ AdWords.prototype.loaded = function(){ return !! document.body; }; /** * Page. * * https://support.google.com/adwords/answer/3111920#standard_parameters * https://support.google.com/adwords/answer/3103357 * https://developers.google.com/adwords-remarketing-tag/asynchronous/ * https://developers.google.com/adwords-remarketing-tag/parameters * * @param {Page} page */ AdWords.prototype.page = function(page){ var remarketing = !!this.options.remarketing; var id = this.options.conversionId; var props = {}; window.google_trackConversion({ google_conversion_id: id, google_custom_params: props, google_remarketing_only: remarketing }); }; /** * Track. * * @param {Track} * @api public */ AdWords.prototype.track = function(track){ var id = this.options.conversionId; var events = this.events(track.event()); var revenue = track.revenue() || 0; each(events, function(label){ var props = track.properties(); window.google_trackConversion({ google_conversion_id: id, // TODO // google_custom_params: props, google_conversion_language: 'en', google_conversion_format: '3', google_conversion_color: 'ffffff', google_conversion_label: label, google_conversion_value: revenue, google_remarketing_only: false }); }); }; }, {"analytics.js-integration":83,"domify":119,"each":4}], 119: [function(require, module, exports) { /** * Expose `parse`. */ module.exports = parse; /** * Wrap map from jquery. */ var map = { legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], _default: [0, '', ''] }; map.td = map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>']; map.option = map.optgroup = [1, '<select multiple="multiple">', '</select>']; map.thead = map.tbody = map.colgroup = map.caption = map.tfoot = [1, '<table>', '</table>']; map.text = map.circle = map.ellipse = map.line = map.path = map.polygon = map.polyline = map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>']; /** * Parse `html` and return the children. * * @param {String} html * @return {Array} * @api private */ function parse(html) { if ('string' != typeof html) throw new TypeError('String expected'); html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace // tag name var m = /<([\w:]+)/.exec(html); if (!m) return document.createTextNode(html); var tag = m[1]; // body support if (tag == 'body') { var el = document.createElement('html'); el.innerHTML = html; return el.removeChild(el.lastChild); } // wrap map var wrap = map[tag] || map._default; var depth = wrap[0]; var prefix = wrap[1]; var suffix = wrap[2]; var el = document.createElement('div'); el.innerHTML = prefix + html + suffix; while (depth--) el = el.lastChild; // one element if (el.firstChild == el.lastChild) { return el.removeChild(el.firstChild); } // several elements var fragment = document.createDocumentFragment(); while (el.firstChild) { fragment.appendChild(el.removeChild(el.firstChild)); } return fragment; } }, {}], 10: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose Alexa integration. */ var Alexa = module.exports = integration('Alexa') .assumesPageview() .global('_atrk_opts') .option('account', null) .option('domain', '') .option('dynamic', true) .tag('<script src="//d31qbv1cthcecs.cloudfront.net/atrk.js">'); /** * Initialize. * * @param {Object} page */ Alexa.prototype.initialize = function(page){ var self = this; window._atrk_opts = { atrk_acct: this.options.account, domain: this.options.domain, dynamic: this.options.dynamic }; this.load(function(){ window.atrk(); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Alexa.prototype.loaded = function(){ return !! window.atrk; }; }, {"analytics.js-integration":83}], 11: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `Amplitude` integration. */ var Amplitude = module.exports = integration('Amplitude') .global('amplitude') .option('apiKey', '') .option('trackAllPages', false) .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.1-min.js">'); /** * Initialize. * * https://github.com/amplitude/Amplitude-Javascript * * @param {Object} page */ Amplitude.prototype.initialize = function(page){ (function(e,t){var r=e.amplitude||{}; r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)));};} var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName","setDomain"]; for (var c=0;c<s.length;c++){i(s[c]);}e.amplitude=r;})(window,document); window.amplitude.init(this.options.apiKey); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Amplitude.prototype.loaded = function(){ return !! (window.amplitude && window.amplitude.options); }; /** * Page. * * @param {Page} page */ Amplitude.prototype.page = function(page){ var properties = page.properties(); var category = page.category(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Identify. * * @param {Facade} identify */ Amplitude.prototype.identify = function(identify){ var id = identify.userId(); var traits = identify.traits(); if (id) window.amplitude.setUserId(id); if (traits) window.amplitude.setGlobalUserProperties(traits); }; /** * Track. * * @param {Track} event */ Amplitude.prototype.track = function(track){ var props = track.properties(); var event = track.event(); window.amplitude.logEvent(event, props); }; }, {"analytics.js-integration":83}], 12: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var load = require('load-script'); var is = require('is'); /** * Expose plugin. */ module.exports = exports = function (analytics) { analytics.addIntegration(Appcues); }; /** * Expose `Appcues` integration. */ var Appcues = exports.Integration = integration('Appcues') .assumesPageview() .global('Appcues') .global('AppcuesIdentity') .option('appcuesId', '') .option('userId', '') .option('userEmail', ''); /** * Initialize. * * http://appcues.com/docs/ * * @param {Object} */ Appcues.prototype.initialize = function(){ this.load(function() { window.Appcues.init(); }); }; /** * Loaded? * * @return {Boolean} */ Appcues.prototype.loaded = function(){ return is.object(window.Appcues); }; /** * Load the Appcues library. * * @param {Function} callback */ Appcues.prototype.load = function(callback){ var script = load('//d2dubfq97s02eu.cloudfront.net/appcues-bundle.min.js', callback); script.setAttribute('data-appcues-id', this.options.appcuesId); script.setAttribute('data-user-id', this.options.userId); script.setAttribute('data-user-email', this.options.userEmail); }; /** * Identify. * * http://appcues.com/docs#identify * * @param {Identify} identify */ Appcues.prototype.identify = function(identify){ window.Appcues.identify(identify.traits()); }; }, {"analytics.js-integration":83,"load-script":120,"is":86}], 120: [function(require, module, exports) { /** * Module dependencies. */ var onload = require('script-onload'); var tick = require('next-tick'); var type = require('type'); /** * Expose `loadScript`. * * @param {Object} options * @param {Function} fn * @api public */ module.exports = function loadScript(options, fn){ if (!options) throw new Error('Cant load nothing...'); // Allow for the simplest case, just passing a `src` string. if ('string' == type(options)) options = { src : options }; var https = document.location.protocol === 'https:' || document.location.protocol === 'chrome-extension:'; // If you use protocol relative URLs, third-party scripts like Google // Analytics break when testing with `file:` so this fixes that. if (options.src && options.src.indexOf('//') === 0) { options.src = https ? 'https:' + options.src : 'http:' + options.src; } // Allow them to pass in different URLs depending on the protocol. if (https && options.https) options.src = options.https; else if (!https && options.http) options.src = options.http; // Make the `<script>` element and insert it before the first script on the // page, which is guaranteed to exist since this Javascript is running. var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = options.src; // If we have a fn, attach event handlers, even in IE. Based off of // the Third-Party Javascript script loading example: // https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html if ('function' == type(fn)) { onload(script, fn); } tick(function(){ // Append after event listeners are attached for IE. var firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(script, firstScript); }); // Return the script element in case they want to do anything special, like // give it an ID or attributes. return script; }; }, {"script-onload":108,"next-tick":97,"type":7}], 13: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var each = require('each'); /** * Expose `Awesm` integration. */ var Awesm = module.exports = integration('awe.sm') .assumesPageview() .global('AWESM') .option('apiKey', '') .tag('<script src="//widgets.awe.sm/v3/widgets.js?key={{ apiKey }}&async=true">') .mapping('events'); /** * Initialize. * * http://developers.awe.sm/guides/javascript/ * * @param {Object} page */ Awesm.prototype.initialize = function(page){ window.AWESM = { api_key: this.options.apiKey }; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Awesm.prototype.loaded = function(){ return !! (window.AWESM && window.AWESM._exists); }; /** * Track. * * @param {Track} track */ Awesm.prototype.track = function(track){ var user = this.analytics.user(); var goals = this.events(track.event()); each(goals, function(goal){ window.AWESM.convert(goal, track.cents(), null, user.id()); }); }; }, {"analytics.js-integration":83,"each":4}], 14: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var is = require('is'); var noop = function(){}; var onBody = require('on-body'); /** * Expose `Awesomatic` integration. */ var Awesomatic = module.exports = integration('Awesomatic') .assumesPageview() .global('Awesomatic') .global('AwesomaticSettings') .global('AwsmSetup') .global('AwsmTmp') .option('appId', '') .tag('<script src="https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js">'); /** * Initialize. * * @param {Object} page */ Awesomatic.prototype.initialize = function(page){ var self = this; var user = this.analytics.user(); var id = user.id(); var options = user.traits(); options.appId = this.options.appId; if (id) options.user_id = id; this.load(function(){ window.Awesomatic.initialize(options, function(){ self.ready(); // need to wait for initialize to callback }); }); }; /** * Loaded? * * @return {Boolean} */ Awesomatic.prototype.loaded = function(){ return is.object(window.Awesomatic); }; }, {"analytics.js-integration":83,"is":86,"on-body":121}], 121: [function(require, module, exports) { var each = require('each'); /** * Cache whether `<body>` exists. */ var body = false; /** * Callbacks to call when the body exists. */ var callbacks = []; /** * Export a way to add handlers to be invoked once the body exists. * * @param {Function} callback A function to call when the body exists. */ module.exports = function onBody (callback) { if (body) { call(callback); } else { callbacks.push(callback); } }; /** * Set an interval to check for `document.body`. */ var interval = setInterval(function () { if (!document.body) return; body = true; each(callbacks, call); clearInterval(interval); }, 5); /** * Call a callback, passing it the body. * * @param {Function} callback The callback to call. */ function call (callback) { callback(document.body); } }, {"each":106}], 15: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var onbody = require('on-body'); var domify = require('domify'); var extend = require('extend'); var bind = require('bind'); var when = require('when'); var each = require('each'); /** * HOP. */ var has = Object.prototype.hasOwnProperty; /** * Noop. */ var noop = function(){}; /** * Expose `Bing`. * * https://bingads.microsoft.com/campaign/signup */ var Bing = module.exports = integration('Bing Ads') .option('siteId', '') .option('domainId', '') .tag('<script id="mstag_tops" src="//flex.msn.com/mstag/site/{{ siteId }}/mstag.js">') .mapping('events'); /** * Initialize. * * http://msdn.microsoft.com/en-us/library/bing-ads-campaign-management-campaign-analytics-scripts.aspx * * @param {Object} page */ Bing.prototype.initialize = function(page){ if (!window.mstag) { window.mstag = { loadTag: noop, time: (new Date()).getTime(), // they use document.write, which doesn't work when loaded async. // they provide a way to override it. // the first time it is called, load the script, // and only when that script is done, is "loading" done. _write: writeToAppend }; }; var self = this; onbody(function(){ self.load(function(){ var loaded = bind(self, self.loaded); // poll until this.loaded() is true. // have to do a weird hack like this because // the first script loads a second script, // and only after the second script is it actually loaded. when(loaded, self.ready); }); }); }; /** * Loaded? * * @return {Boolean} */ Bing.prototype.loaded = function(){ return !! (window.mstag && window.mstag.loadTag !== noop); }; /** * Track. * * @param {Track} track */ Bing.prototype.track = function(track){ var events = this.events(track.event()); var revenue = track.revenue() || 0; var self = this; each(events, function(goal){ window.mstag.loadTag('analytics', { domainId: self.options.domainId, revenue: revenue, dedup: '1', type: '1', actionid: goal }); }); }; /** * Convert `document.write` to `document.appendChild`. * * TODO: make into a component. * * @param {String} str */ function writeToAppend(str) { var first = document.getElementsByTagName('script')[0]; var el = domify(str); // https://github.com/component/domify/issues/14 if ('script' == el.tagName.toLowerCase() && el.getAttribute('src')) { var tmp = document.createElement('script'); tmp.src = el.getAttribute('src'); tmp.async = true; el = tmp; } document.body.appendChild(el); } }, {"analytics.js-integration":83,"on-body":121,"domify":119,"extend":122,"bind":95,"when":123,"each":4}], 122: [function(require, module, exports) { module.exports = function extend (object) { // Takes an unlimited number of extenders. var args = Array.prototype.slice.call(arguments, 1); // For each extender, copy their properties on our object. for (var i = 0, source; source = args[i]; i++) { if (!source) continue; for (var property in source) { object[property] = source[property]; } } return object; }; }, {}], 123: [function(require, module, exports) { var callback = require('callback'); /** * Expose `when`. */ module.exports = when; /** * Loop on a short interval until `condition()` is true, then call `fn`. * * @param {Function} condition * @param {Function} fn * @param {Number} interval (optional) */ function when (condition, fn, interval) { if (condition()) return callback.async(fn); var ref = setInterval(function () { if (!condition()) return; callback(fn); clearInterval(ref); }, interval || 10); } }, {"callback":88}], 16: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var Identify = require('facade').Identify; var Track = require('facade').Track; var pixel = require('load-pixel')('http://app.bronto.com/public/'); var qs = require('querystring'); var each = require('each'); /** * Expose `Bronto` integration. */ var Bronto = module.exports = integration('Bronto') .global('__bta') .option('siteId', '') .option('host', '') .tag('<script src="//p.bm23.com/bta.js">'); /** * Initialize. * * http://app.bronto.com/mail/help/help_view/?k=mail:home:api_tracking:tracking_data_store_js#addingjavascriptconversiontrackingtoyoursite * http://bronto.com/product-blog/features/using-conversion-tracking-private-domain#.Ut_Vk2T8KqB * http://bronto.com/product-blog/features/javascript-conversion-tracking-setup-and-reporting#.Ut_VhmT8KqB * * @param {Object} page */ Bronto.prototype.initialize = function(page){ var self = this; var params = qs.parse(window.location.search); if (!params._bta_tid && !params._bta_c) { this.debug('missing tracking URL parameters `_bta_tid` and `_bta_c`.'); } this.load(function(){ var opts = self.options; self.bta = new window.__bta(opts.siteId); if (opts.host) self.bta.setHost(opts.host); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Bronto.prototype.loaded = function(){ return this.bta; }; /** * Completed order. * * The cookie is used to link the order being processed back to the delivery, * message, and contact which makes it a conversion. * Passing in just the email ensures that the order itself * gets linked to the contact record in Bronto even if the user * does not have a tracking cookie. * * @param {Track} track * @api private */ Bronto.prototype.completedOrder = function(track){ var user = this.analytics.user(); var products = track.products(); var props = track.properties(); var items = []; var identify = new Identify({ userId: user.id(), traits: user.traits() }); var email = identify.email(); // items each(products, function(product){ var track = new Track({ properties: product }); items.push({ item_id: track.id() || track.sku(), desc: product.description || track.name(), quantity: track.quantity(), amount: track.price(), }); }); // add conversion this.bta.addOrder({ order_id: track.orderId(), email: email, // they recommend not putting in a date // because it needs to be formatted correctly // YYYY-MM-DDTHH:MM:SS items: items }); }; }, {"analytics.js-integration":83,"facade":124,"load-pixel":125,"querystring":126,"each":4}], 124: [function(require, module, exports) { var Facade = require('./facade'); /** * Expose `Facade` facade. */ module.exports = Facade; /** * Expose specific-method facades. */ Facade.Alias = require('./alias'); Facade.Group = require('./group'); Facade.Identify = require('./identify'); Facade.Track = require('./track'); Facade.Page = require('./page'); Facade.Screen = require('./screen'); }, {"./facade":127,"./alias":128,"./group":129,"./identify":130,"./track":131,"./page":132,"./screen":133}], 127: [function(require, module, exports) { var traverse = require('isodate-traverse'); var isEnabled = require('./is-enabled'); var clone = require('./utils').clone; var type = require('./utils').type; var address = require('./address'); var objCase = require('obj-case'); var newDate = require('new-date'); /** * Expose `Facade`. */ module.exports = Facade; /** * Initialize a new `Facade` with an `obj` of arguments. * * @param {Object} obj */ function Facade (obj) { if (!obj.hasOwnProperty('timestamp')) obj.timestamp = new Date(); else obj.timestamp = newDate(obj.timestamp); traverse(obj); this.obj = obj; } /** * Mixin address traits. */ address(Facade.prototype); /** * Return a proxy function for a `field` that will attempt to first use methods, * and fallback to accessing the underlying object directly. You can specify * deeply nested fields too like: * * this.proxy('options.Librato'); * * @param {String} field */ Facade.prototype.proxy = function (field) { var fields = field.split('.'); field = fields.shift(); // Call a function at the beginning to take advantage of facaded fields var obj = this[field] || this.field(field); if (!obj) return obj; if (typeof obj === 'function') obj = obj.call(this) || {}; if (fields.length === 0) return transform(obj); obj = objCase(obj, fields.join('.')); return transform(obj); }; /** * Directly access a specific `field` from the underlying object, returning a * clone so outsiders don't mess with stuff. * * @param {String} field * @return {Mixed} */ Facade.prototype.field = function (field) { var obj = this.obj[field]; return transform(obj); }; /** * Utility method to always proxy a particular `field`. You can specify deeply * nested fields too like: * * Facade.proxy('options.Librato'); * * @param {String} field * @return {Function} */ Facade.proxy = function (field) { return function () { return this.proxy(field); }; }; /** * Utility method to directly access a `field`. * * @param {String} field * @return {Function} */ Facade.field = function (field) { return function () { return this.field(field); }; }; /** * Proxy multiple `path`. * * @param {String} path * @return {Array} */ Facade.multi = function(path){ return function(){ var multi = this.proxy(path + 's'); if ('array' == type(multi)) return multi; var one = this.proxy(path); if (one) one = [clone(one)]; return one || []; }; }; /** * Proxy one `path`. * * @param {String} path * @return {Mixed} */ Facade.one = function(path){ return function(){ var one = this.proxy(path); if (one) return one; var multi = this.proxy(path + 's'); if ('array' == type(multi)) return multi[0]; }; }; /** * Get the basic json object of this facade. * * @return {Object} */ Facade.prototype.json = function () { var ret = clone(this.obj); if (this.type) ret.type = this.type(); return ret; }; /** * Get the options of a call (formerly called "context"). If you pass an * integration name, it will get the options for that specific integration, or * undefined if the integration is not enabled. * * @param {String} integration (optional) * @return {Object or Null} */ Facade.prototype.context = Facade.prototype.options = function (integration) { var options = clone(this.obj.options || this.obj.context) || {}; if (!integration) return clone(options); if (!this.enabled(integration)) return; var integrations = this.integrations(); var value = integrations[integration] || objCase(integrations, integration); if ('boolean' == typeof value) value = {}; return value || {}; }; /** * Check whether an integration is enabled. * * @param {String} integration * @return {Boolean} */ Facade.prototype.enabled = function (integration) { var allEnabled = this.proxy('options.providers.all'); if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('options.all'); if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('integrations.all'); if (typeof allEnabled !== 'boolean') allEnabled = true; var enabled = allEnabled && isEnabled(integration); var options = this.integrations(); // If the integration is explicitly enabled or disabled, use that // First, check options.providers for backwards compatibility if (options.providers && options.providers.hasOwnProperty(integration)) { enabled = options.providers[integration]; } // Next, check for the integration's existence in 'options' to enable it. // If the settings are a boolean, use that, otherwise it should be enabled. if (options.hasOwnProperty(integration)) { var settings = options[integration]; if (typeof settings === 'boolean') { enabled = settings; } else { enabled = true; } } return enabled ? true : false; }; /** * Get all `integration` options. * * @param {String} integration * @return {Object} * @api private */ Facade.prototype.integrations = function(){ return this.obj.integrations || this.proxy('options.providers') || this.options(); }; /** * Check whether the user is active. * * @return {Boolean} */ Facade.prototype.active = function () { var active = this.proxy('options.active'); if (active === null || active === undefined) active = true; return active; }; /** * Get `sessionId / anonymousId`. * * @return {Mixed} * @api public */ Facade.prototype.sessionId = Facade.prototype.anonymousId = function(){ return this.field('anonymousId') || this.field('sessionId'); }; /** * Get `groupId` from `context.groupId`. * * @return {String} * @api public */ Facade.prototype.groupId = Facade.proxy('options.groupId'); /** * Get the call's "super properties" which are just traits that have been * passed in as if from an identify call. * * @param {Object} aliases * @return {Object} */ Facade.prototype.traits = function (aliases) { var ret = this.proxy('options.traits') || {}; var id = this.userId(); aliases = aliases || {}; if (id) ret.id = id; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('options.traits.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Add a convenient way to get the library name and version */ Facade.prototype.library = function(){ var library = this.proxy('options.library'); if (!library) return { name: 'unknown', version: null }; if (typeof library === 'string') return { name: library, version: null }; return library; }; /** * Setup some basic proxies. */ Facade.prototype.userId = Facade.field('userId'); Facade.prototype.channel = Facade.field('channel'); Facade.prototype.timestamp = Facade.field('timestamp'); Facade.prototype.userAgent = Facade.proxy('options.userAgent'); Facade.prototype.ip = Facade.proxy('options.ip'); /** * Return the cloned and traversed object * * @param {Mixed} obj * @return {Mixed} */ function transform(obj){ var cloned = clone(obj); return cloned; } }, {"isodate-traverse":134,"./is-enabled":135,"./utils":136,"./address":137,"obj-case":138,"new-date":139}], 134: [function(require, module, exports) { var is = require('is'); var isodate = require('isodate'); var each; try { each = require('each'); } catch (err) { each = require('each-component'); } /** * Expose `traverse`. */ module.exports = traverse; /** * Traverse an object or array, and return a clone with all ISO strings parsed * into Date objects. * * @param {Object} obj * @return {Object} */ function traverse (input, strict) { if (strict === undefined) strict = true; if (is.object(input)) return object(input, strict); if (is.array(input)) return array(input, strict); return input; } /** * Object traverser. * * @param {Object} obj * @param {Boolean} strict * @return {Object} */ function object (obj, strict) { each(obj, function (key, val) { if (isodate.is(val, strict)) { obj[key] = isodate.parse(val); } else if (is.object(val) || is.array(val)) { traverse(val, strict); } }); return obj; } /** * Array traverser. * * @param {Array} arr * @param {Boolean} strict * @return {Array} */ function array (arr, strict) { each(arr, function (val, x) { if (is.object(val)) { traverse(val, strict); } else if (isodate.is(val, strict)) { arr[x] = isodate.parse(val); } }); return arr; } }, {"is":140,"isodate":141,"each":4}], 140: [function(require, module, exports) { var isEmpty = require('is-empty'); try { var typeOf = require('type'); } catch (e) { var typeOf = require('component-type'); } /** * Types. */ var types = [ 'arguments', 'array', 'boolean', 'date', 'element', 'function', 'null', 'number', 'object', 'regexp', 'string', 'undefined' ]; /** * Expose type checkers. * * @param {Mixed} value * @return {Boolean} */ for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type); /** * Add alias for `function` for old browsers. */ exports.fn = exports['function']; /** * Expose `empty` check. */ exports.empty = isEmpty; /** * Expose `nan` check. */ exports.nan = function (val) { return exports.number(val) && val != val; }; /** * Generate a type checker. * * @param {String} type * @return {Function} */ function generate (type) { return function (value) { return type === typeOf(value); }; } }, {"is-empty":118,"type":7,"component-type":7}], 141: [function(require, module, exports) { /** * Matcher, slightly modified from: * * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js */ var matcher = /^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/; /** * Convert an ISO date string to a date. Fallback to native `Date.parse`. * * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js * * @param {String} iso * @return {Date} */ exports.parse = function (iso) { var numericKeys = [1, 5, 6, 7, 11, 12]; var arr = matcher.exec(iso); var offset = 0; // fallback to native parsing if (!arr) return new Date(iso); // remove undefined values for (var i = 0, val; val = numericKeys[i]; i++) { arr[val] = parseInt(arr[val], 10) || 0; } // allow undefined days and months arr[2] = parseInt(arr[2], 10) || 1; arr[3] = parseInt(arr[3], 10) || 1; // month is 0-11 arr[2]--; // allow abitrary sub-second precision arr[8] = arr[8] ? (arr[8] + '00').substring(0, 3) : 0; // apply timezone if one exists if (arr[4] == ' ') { offset = new Date().getTimezoneOffset(); } else if (arr[9] !== 'Z' && arr[10]) { offset = arr[11] * 60 + arr[12]; if ('+' == arr[10]) offset = 0 - offset; } var millis = Date.UTC(arr[1], arr[2], arr[3], arr[5], arr[6] + offset, arr[7], arr[8]); return new Date(millis); }; /** * Checks whether a `string` is an ISO date string. `strict` mode requires that * the date string at least have a year, month and date. * * @param {String} string * @param {Boolean} strict * @return {Boolean} */ exports.is = function (string, strict) { if (strict && false === /^\d{4}-\d{2}-\d{2}/.test(string)) return false; return matcher.test(string); }; }, {}], 135: [function(require, module, exports) { /** * A few integrations are disabled by default. They must be explicitly * enabled by setting options[Provider] = true. */ var disabled = { Salesforce: true }; /** * Check whether an integration should be enabled by default. * * @param {String} integration * @return {Boolean} */ module.exports = function (integration) { return ! disabled[integration]; }; }, {}], 136: [function(require, module, exports) { /** * TODO: use component symlink, everywhere ? */ try { exports.inherit = require('inherit'); exports.clone = require('clone'); exports.type = require('type'); } catch (e) { exports.inherit = require('inherit-component'); exports.clone = require('clone-component'); exports.type = require('type-component'); } }, {"inherit":142,"clone":143,"type":7}], 142: [function(require, module, exports) { module.exports = function(a, b){ var fn = function(){}; fn.prototype = b.prototype; a.prototype = new fn; a.prototype.constructor = a; }; }, {}], 143: [function(require, module, exports) { /** * Module dependencies. */ var type; try { type = require('component-type'); } catch (_) { type = require('type'); } /** * Module exports. */ module.exports = clone; /** * Clones objects. * * @param {Mixed} any object * @api public */ function clone(obj){ switch (type(obj)) { case 'object': var copy = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { copy[key] = clone(obj[key]); } } return copy; case 'array': var copy = new Array(obj.length); for (var i = 0, l = obj.length; i < l; i++) { copy[i] = clone(obj[i]); } return copy; case 'regexp': // from millermedeiros/amd-utils - MIT var flags = ''; flags += obj.multiline ? 'm' : ''; flags += obj.global ? 'g' : ''; flags += obj.ignoreCase ? 'i' : ''; return new RegExp(obj.source, flags); case 'date': return new Date(obj.getTime()); default: // string, number, boolean, … return obj; } } }, {"component-type":7,"type":7}], 137: [function(require, module, exports) { /** * Module dependencies. */ var get = require('obj-case'); /** * Add address getters to `proto`. * * @param {Function} proto */ module.exports = function(proto){ proto.zip = trait('postalCode', 'zip'); proto.country = trait('country'); proto.street = trait('street'); proto.state = trait('state'); proto.city = trait('city'); function trait(a, b){ return function(){ var traits = this.traits(); return get(traits, 'address.' + a) || get(traits, a) || (b ? get(traits, 'address.' + b) : null) || (b ? get(traits, b) : null); }; } }; }, {"obj-case":138}], 138: [function(require, module, exports) { var Case = require('case'); var identity = function(_){ return _; }; /** * Cases */ var cases = [ identity, Case.upper, Case.lower, Case.snake, Case.pascal, Case.camel, Case.constant, Case.title, Case.capital, Case.sentence ]; /** * Module exports, export */ module.exports = module.exports.find = multiple(find); /** * Export the replacement function, return the modified object */ module.exports.replace = function (obj, key, val) { multiple(replace).apply(this, arguments); return obj; }; /** * Export the delete function, return the modified object */ module.exports.del = function (obj, key) { multiple(del).apply(this, arguments); return obj; }; /** * Compose applying the function to a nested key */ function multiple (fn) { return function (obj, key, val) { var keys = key.split('.'); if (keys.length === 0) return; while (keys.length > 1) { key = keys.shift(); obj = find(obj, key); if (obj === null || obj === undefined) return; } key = keys.shift(); return fn(obj, key, val); }; } /** * Find an object by its key * * find({ first_name : 'Calvin' }, 'firstName') */ function find (obj, key) { for (var i = 0; i < cases.length; i++) { var cased = cases[i](key); if (obj.hasOwnProperty(cased)) return obj[cased]; } } /** * Delete a value for a given key * * del({ a : 'b', x : 'y' }, 'X' }) -> { a : 'b' } */ function del (obj, key) { for (var i = 0; i < cases.length; i++) { var cased = cases[i](key); if (obj.hasOwnProperty(cased)) delete obj[cased]; } return obj; } /** * Replace an objects existing value with a new one * * replace({ a : 'b' }, 'a', 'c') -> { a : 'c' } */ function replace (obj, key, val) { for (var i = 0; i < cases.length; i++) { var cased = cases[i](key); if (obj.hasOwnProperty(cased)) obj[cased] = val; } return obj; } }, {"case":144}], 144: [function(require, module, exports) { var cases = require('./cases'); /** * Expose `determineCase`. */ module.exports = exports = determineCase; /** * Determine the case of a `string`. * * @param {String} string * @return {String|Null} */ function determineCase (string) { for (var key in cases) { if (key == 'none') continue; var convert = cases[key]; if (convert(string) == string) return key; } return null; } /** * Define a case by `name` with a `convert` function. * * @param {String} name * @param {Object} convert */ exports.add = function (name, convert) { exports[name] = cases[name] = convert; }; /** * Add all the `cases`. */ for (var key in cases) { exports.add(key, cases[key]); } }, {"./cases":145}], 145: [function(require, module, exports) { var camel = require('to-camel-case') , capital = require('to-capital-case') , constant = require('to-constant-case') , dot = require('to-dot-case') , none = require('to-no-case') , pascal = require('to-pascal-case') , sentence = require('to-sentence-case') , slug = require('to-slug-case') , snake = require('to-snake-case') , space = require('to-space-case') , title = require('to-title-case'); /** * Camel. */ exports.camel = camel; /** * Pascal. */ exports.pascal = pascal; /** * Dot. Should precede lowercase. */ exports.dot = dot; /** * Slug. Should precede lowercase. */ exports.slug = slug; /** * Snake. Should precede lowercase. */ exports.snake = snake; /** * Space. Should precede lowercase. */ exports.space = space; /** * Constant. Should precede uppercase. */ exports.constant = constant; /** * Capital. Should precede sentence and title. */ exports.capital = capital; /** * Title. */ exports.title = title; /** * Sentence. */ exports.sentence = sentence; /** * Convert a `string` to lower case from camel, slug, etc. Different that the * usual `toLowerCase` in that it will try to break apart the input first. * * @param {String} string * @return {String} */ exports.lower = function (string) { return none(string).toLowerCase(); }; /** * Convert a `string` to upper case from camel, slug, etc. Different that the * usual `toUpperCase` in that it will try to break apart the input first. * * @param {String} string * @return {String} */ exports.upper = function (string) { return none(string).toUpperCase(); }; /** * Invert each character in a `string` from upper to lower and vice versa. * * @param {String} string * @return {String} */ exports.inverse = function (string) { for (var i = 0, char; char = string[i]; i++) { if (!/[a-z]/i.test(char)) continue; var upper = char.toUpperCase(); var lower = char.toLowerCase(); string[i] = char == upper ? lower : upper; } return string; }; /** * None. */ exports.none = none; }, {"to-camel-case":146,"to-capital-case":147,"to-constant-case":148,"to-dot-case":149,"to-no-case":117,"to-pascal-case":150,"to-sentence-case":151,"to-slug-case":152,"to-snake-case":153,"to-space-case":154,"to-title-case":155}], 146: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toCamelCase`. */ module.exports = toCamelCase; /** * Convert a `string` to camel case. * * @param {String} string * @return {String} */ function toCamelCase (string) { return toSpace(string).replace(/\s(\w)/g, function (matches, letter) { return letter.toUpperCase(); }); } }, {"to-space-case":154}], 154: [function(require, module, exports) { var clean = require('to-no-case'); /** * Expose `toSpaceCase`. */ module.exports = toSpaceCase; /** * Convert a `string` to space case. * * @param {String} string * @return {String} */ function toSpaceCase (string) { return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) { return match ? ' ' + match : ''; }); } }, {"to-no-case":117}], 147: [function(require, module, exports) { var clean = require('to-no-case'); /** * Expose `toCapitalCase`. */ module.exports = toCapitalCase; /** * Convert a `string` to capital case. * * @param {String} string * @return {String} */ function toCapitalCase (string) { return clean(string).replace(/(^|\s)(\w)/g, function (matches, previous, letter) { return previous + letter.toUpperCase(); }); } }, {"to-no-case":117}], 148: [function(require, module, exports) { var snake = require('to-snake-case'); /** * Expose `toConstantCase`. */ module.exports = toConstantCase; /** * Convert a `string` to constant case. * * @param {String} string * @return {String} */ function toConstantCase (string) { return snake(string).toUpperCase(); } }, {"to-snake-case":153}], 153: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toSnakeCase`. */ module.exports = toSnakeCase; /** * Convert a `string` to snake case. * * @param {String} string * @return {String} */ function toSnakeCase (string) { return toSpace(string).replace(/\s/g, '_'); } }, {"to-space-case":154}], 149: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toDotCase`. */ module.exports = toDotCase; /** * Convert a `string` to slug case. * * @param {String} string * @return {String} */ function toDotCase (string) { return toSpace(string).replace(/\s/g, '.'); } }, {"to-space-case":154}], 150: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toPascalCase`. */ module.exports = toPascalCase; /** * Convert a `string` to pascal case. * * @param {String} string * @return {String} */ function toPascalCase (string) { return toSpace(string).replace(/(?:^|\s)(\w)/g, function (matches, letter) { return letter.toUpperCase(); }); } }, {"to-space-case":154}], 151: [function(require, module, exports) { var clean = require('to-no-case'); /** * Expose `toSentenceCase`. */ module.exports = toSentenceCase; /** * Convert a `string` to camel case. * * @param {String} string * @return {String} */ function toSentenceCase (string) { return clean(string).replace(/[a-z]/i, function (letter) { return letter.toUpperCase(); }); } }, {"to-no-case":117}], 152: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toSlugCase`. */ module.exports = toSlugCase; /** * Convert a `string` to slug case. * * @param {String} string * @return {String} */ function toSlugCase (string) { return toSpace(string).replace(/\s/g, '-'); } }, {"to-space-case":154}], 155: [function(require, module, exports) { var capital = require('to-capital-case') , escape = require('escape-regexp') , map = require('map') , minors = require('title-case-minors'); /** * Expose `toTitleCase`. */ module.exports = toTitleCase; /** * Minors. */ var escaped = map(minors, escape); var minorMatcher = new RegExp('[^^]\\b(' + escaped.join('|') + ')\\b', 'ig'); var colonMatcher = /:\s*(\w)/g; /** * Convert a `string` to camel case. * * @param {String} string * @return {String} */ function toTitleCase (string) { return capital(string) .replace(minorMatcher, function (minor) { return minor.toLowerCase(); }) .replace(colonMatcher, function (letter) { return letter.toUpperCase(); }); } }, {"to-capital-case":147,"escape-regexp":156,"map":157,"title-case-minors":158}], 156: [function(require, module, exports) { /** * Escape regexp special characters in `str`. * * @param {String} str * @return {String} * @api public */ module.exports = function(str){ return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g, '\\$1'); }; }, {}], 157: [function(require, module, exports) { var each = require('each'); /** * Map an array or object. * * @param {Array|Object} obj * @param {Function} iterator * @return {Mixed} */ module.exports = function map (obj, iterator) { var arr = []; each(obj, function (o) { arr.push(iterator.apply(null, arguments)); }); return arr; }; }, {"each":106}], 158: [function(require, module, exports) { module.exports = [ 'a', 'an', 'and', 'as', 'at', 'but', 'by', 'en', 'for', 'from', 'how', 'if', 'in', 'neither', 'nor', 'of', 'on', 'only', 'onto', 'out', 'or', 'per', 'so', 'than', 'that', 'the', 'to', 'until', 'up', 'upon', 'v', 'v.', 'versus', 'vs', 'vs.', 'via', 'when', 'with', 'without', 'yet' ]; }, {}], 139: [function(require, module, exports) { var is = require('is'); var isodate = require('isodate'); var milliseconds = require('./milliseconds'); var seconds = require('./seconds'); /** * Returns a new Javascript Date object, allowing a variety of extra input types * over the native Date constructor. * * @param {Date|String|Number} val */ module.exports = function newDate (val) { if (is.date(val)) return val; if (is.number(val)) return new Date(toMs(val)); // date strings if (isodate.is(val)) return isodate.parse(val); if (milliseconds.is(val)) return milliseconds.parse(val); if (seconds.is(val)) return seconds.parse(val); // fallback to Date.parse return new Date(val); }; /** * If the number passed val is seconds from the epoch, turn it into milliseconds. * Milliseconds would be greater than 31557600000 (December 31, 1970). * * @param {Number} num */ function toMs (num) { if (num < 31557600000) return num * 1000; return num; } }, {"is":159,"isodate":141,"./milliseconds":160,"./seconds":161}], 159: [function(require, module, exports) { var isEmpty = require('is-empty') , typeOf = require('type'); /** * Types. */ var types = [ 'arguments', 'array', 'boolean', 'date', 'element', 'function', 'null', 'number', 'object', 'regexp', 'string', 'undefined' ]; /** * Expose type checkers. * * @param {Mixed} value * @return {Boolean} */ for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type); /** * Add alias for `function` for old browsers. */ exports.fn = exports['function']; /** * Expose `empty` check. */ exports.empty = isEmpty; /** * Expose `nan` check. */ exports.nan = function (val) { return exports.number(val) && val != val; }; /** * Generate a type checker. * * @param {String} type * @return {Function} */ function generate (type) { return function (value) { return type === typeOf(value); }; } }, {"is-empty":118,"type":7}], 160: [function(require, module, exports) { /** * Matcher. */ var matcher = /\d{13}/; /** * Check whether a string is a millisecond date string. * * @param {String} string * @return {Boolean} */ exports.is = function (string) { return matcher.test(string); }; /** * Convert a millisecond string to a date. * * @param {String} millis * @return {Date} */ exports.parse = function (millis) { millis = parseInt(millis, 10); return new Date(millis); }; }, {}], 161: [function(require, module, exports) { /** * Matcher. */ var matcher = /\d{10}/; /** * Check whether a string is a second date string. * * @param {String} string * @return {Boolean} */ exports.is = function (string) { return matcher.test(string); }; /** * Convert a second string to a date. * * @param {String} seconds * @return {Date} */ exports.parse = function (seconds) { var millis = parseInt(seconds, 10) * 1000; return new Date(millis); }; }, {}], 128: [function(require, module, exports) { /** * Module dependencies. */ var inherit = require('./utils').inherit; var Facade = require('./facade'); /** * Expose `Alias` facade. */ module.exports = Alias; /** * Initialize a new `Alias` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @property {String} from * @property {String} to * @property {Object} options */ function Alias (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Alias, Facade); /** * Return type of facade. * * @return {String} */ Alias.prototype.type = Alias.prototype.action = function () { return 'alias'; }; /** * Get `previousId`. * * @return {Mixed} * @api public */ Alias.prototype.from = Alias.prototype.previousId = function(){ return this.field('previousId') || this.field('from'); }; /** * Get `userId`. * * @return {String} * @api public */ Alias.prototype.to = Alias.prototype.userId = function(){ return this.field('userId') || this.field('to'); }; }, {"./utils":136,"./facade":127}], 129: [function(require, module, exports) { /** * Module dependencies. */ var inherit = require('./utils').inherit; var address = require('./address'); var isEmail = require('is-email'); var newDate = require('new-date'); var Facade = require('./facade'); /** * Expose `Group` facade. */ module.exports = Group; /** * Initialize a new `Group` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @param {String} userId * @param {String} groupId * @param {Object} properties * @param {Object} options */ function Group (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade` */ inherit(Group, Facade); /** * Get the facade's action. */ Group.prototype.type = Group.prototype.action = function () { return 'group'; }; /** * Setup some basic proxies. */ Group.prototype.groupId = Facade.field('groupId'); /** * Get created or createdAt. * * @return {Date} */ Group.prototype.created = function(){ var created = this.proxy('traits.createdAt') || this.proxy('traits.created') || this.proxy('properties.createdAt') || this.proxy('properties.created'); if (created) return newDate(created); }; /** * Get the group's email, falling back to the group ID if it's a valid email. * * @return {String} */ Group.prototype.email = function () { var email = this.proxy('traits.email'); if (email) return email; var groupId = this.groupId(); if (isEmail(groupId)) return groupId; }; /** * Get the group's traits. * * @param {Object} aliases * @return {Object} */ Group.prototype.traits = function (aliases) { var ret = this.properties(); var id = this.groupId(); aliases = aliases || {}; if (id) ret.id = id; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('traits.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Special traits. */ Group.prototype.name = Facade.proxy('traits.name'); Group.prototype.industry = Facade.proxy('traits.industry'); Group.prototype.employees = Facade.proxy('traits.employees'); /** * Get traits or properties. * * TODO: remove me * * @return {Object} */ Group.prototype.properties = function(){ return this.field('traits') || this.field('properties') || {}; }; }, {"./utils":136,"./address":137,"is-email":162,"new-date":139,"./facade":127}], 162: [function(require, module, exports) { /** * Expose `isEmail`. */ module.exports = isEmail; /** * Email address matcher. */ var matcher = /.+\@.+\..+/; /** * Loosely validate an email address. * * @param {String} string * @return {Boolean} */ function isEmail (string) { return matcher.test(string); } }, {}], 130: [function(require, module, exports) { var address = require('./address'); var Facade = require('./facade'); var isEmail = require('is-email'); var newDate = require('new-date'); var utils = require('./utils'); var get = require('obj-case'); var trim = require('trim'); var inherit = utils.inherit; var clone = utils.clone; var type = utils.type; /** * Expose `Idenfity` facade. */ module.exports = Identify; /** * Initialize a new `Identify` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @param {String} userId * @param {String} sessionId * @param {Object} traits * @param {Object} options */ function Identify (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Identify, Facade); /** * Get the facade's action. */ Identify.prototype.type = Identify.prototype.action = function () { return 'identify'; }; /** * Get the user's traits. * * @param {Object} aliases * @return {Object} */ Identify.prototype.traits = function (aliases) { var ret = this.field('traits') || {}; var id = this.userId(); aliases = aliases || {}; if (id) ret.id = id; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('traits.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; if (alias !== aliases[alias]) delete ret[alias]; } return ret; }; /** * Get the user's email, falling back to their user ID if it's a valid email. * * @return {String} */ Identify.prototype.email = function () { var email = this.proxy('traits.email'); if (email) return email; var userId = this.userId(); if (isEmail(userId)) return userId; }; /** * Get the user's created date, optionally looking for `createdAt` since lots of * people do that instead. * * @return {Date or Undefined} */ Identify.prototype.created = function () { var created = this.proxy('traits.created') || this.proxy('traits.createdAt'); if (created) return newDate(created); }; /** * Get the company created date. * * @return {Date or undefined} */ Identify.prototype.companyCreated = function(){ var created = this.proxy('traits.company.created') || this.proxy('traits.company.createdAt'); if (created) return newDate(created); }; /** * Get the user's name, optionally combining a first and last name if that's all * that was provided. * * @return {String or Undefined} */ Identify.prototype.name = function () { var name = this.proxy('traits.name'); if (typeof name === 'string') return trim(name); var firstName = this.firstName(); var lastName = this.lastName(); if (firstName && lastName) return trim(firstName + ' ' + lastName); }; /** * Get the user's first name, optionally splitting it out of a single name if * that's all that was provided. * * @return {String or Undefined} */ Identify.prototype.firstName = function () { var firstName = this.proxy('traits.firstName'); if (typeof firstName === 'string') return trim(firstName); var name = this.proxy('traits.name'); if (typeof name === 'string') return trim(name).split(' ')[0]; }; /** * Get the user's last name, optionally splitting it out of a single name if * that's all that was provided. * * @return {String or Undefined} */ Identify.prototype.lastName = function () { var lastName = this.proxy('traits.lastName'); if (typeof lastName === 'string') return trim(lastName); var name = this.proxy('traits.name'); if (typeof name !== 'string') return; var space = trim(name).indexOf(' '); if (space === -1) return; return trim(name.substr(space + 1)); }; /** * Get the user's unique id. * * @return {String or undefined} */ Identify.prototype.uid = function(){ return this.userId() || this.username() || this.email(); }; /** * Get description. * * @return {String} */ Identify.prototype.description = function(){ return this.proxy('traits.description') || this.proxy('traits.background'); }; /** * Get the age. * * If the age is not explicitly set * the method will compute it from `.birthday()` * if possible. * * @return {Number} */ Identify.prototype.age = function(){ var date = this.birthday(); var age = get(this.traits(), 'age'); if (null != age) return age; if ('date' != type(date)) return; var now = new Date; return now.getFullYear() - date.getFullYear(); }; /** * Get the avatar. * * .photoUrl needed because help-scout * implementation uses `.avatar || .photoUrl`. * * .avatarUrl needed because trakio uses it. * * @return {Mixed} */ Identify.prototype.avatar = function(){ var traits = this.traits(); return get(traits, 'avatar') || get(traits, 'photoUrl') || get(traits, 'avatarUrl'); }; /** * Get the position. * * .jobTitle needed because some integrations use it. * * @return {Mixed} */ Identify.prototype.position = function(){ var traits = this.traits(); return get(traits, 'position') || get(traits, 'jobTitle'); }; /** * Setup sme basic "special" trait proxies. */ Identify.prototype.username = Facade.proxy('traits.username'); Identify.prototype.website = Facade.one('traits.website'); Identify.prototype.websites = Facade.multi('traits.website'); Identify.prototype.phone = Facade.one('traits.phone'); Identify.prototype.phones = Facade.multi('traits.phone'); Identify.prototype.address = Facade.proxy('traits.address'); Identify.prototype.gender = Facade.proxy('traits.gender'); Identify.prototype.birthday = Facade.proxy('traits.birthday'); }, {"./address":137,"./facade":127,"is-email":162,"new-date":139,"./utils":136,"obj-case":138,"trim":163}], 163: [function(require, module, exports) { exports = module.exports = trim; function trim(str){ if (str.trim) return str.trim(); return str.replace(/^\s*|\s*$/g, ''); } exports.left = function(str){ if (str.trimLeft) return str.trimLeft(); return str.replace(/^\s*/, ''); }; exports.right = function(str){ if (str.trimRight) return str.trimRight(); return str.replace(/\s*$/, ''); }; }, {}], 131: [function(require, module, exports) { var inherit = require('./utils').inherit; var clone = require('./utils').clone; var type = require('./utils').type; var Facade = require('./facade'); var Identify = require('./identify'); var isEmail = require('is-email'); var get = require('obj-case'); /** * Expose `Track` facade. */ module.exports = Track; /** * Initialize a new `Track` facade with a `dictionary` of arguments. * * @param {object} dictionary * @property {String} event * @property {String} userId * @property {String} sessionId * @property {Object} properties * @property {Object} options */ function Track (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Track, Facade); /** * Return the facade's action. * * @return {String} */ Track.prototype.type = Track.prototype.action = function () { return 'track'; }; /** * Setup some basic proxies. */ Track.prototype.event = Facade.field('event'); Track.prototype.value = Facade.proxy('properties.value'); /** * Misc */ Track.prototype.category = Facade.proxy('properties.category'); Track.prototype.country = Facade.proxy('properties.country'); Track.prototype.state = Facade.proxy('properties.state'); Track.prototype.city = Facade.proxy('properties.city'); Track.prototype.zip = Facade.proxy('properties.zip'); /** * Ecommerce */ Track.prototype.id = Facade.proxy('properties.id'); Track.prototype.sku = Facade.proxy('properties.sku'); Track.prototype.tax = Facade.proxy('properties.tax'); Track.prototype.name = Facade.proxy('properties.name'); Track.prototype.price = Facade.proxy('properties.price'); Track.prototype.total = Facade.proxy('properties.total'); Track.prototype.coupon = Facade.proxy('properties.coupon'); Track.prototype.shipping = Facade.proxy('properties.shipping'); /** * Description */ Track.prototype.description = Facade.proxy('properties.description'); /** * Plan */ Track.prototype.plan = Facade.proxy('properties.plan'); /** * Order id. * * @return {String} * @api public */ Track.prototype.orderId = function(){ return this.proxy('properties.id') || this.proxy('properties.orderId'); }; /** * Get subtotal. * * @return {Number} */ Track.prototype.subtotal = function(){ var subtotal = get(this.properties(), 'subtotal'); var total = this.total(); var n; if (subtotal) return subtotal; if (!total) return 0; if (n = this.tax()) total -= n; if (n = this.shipping()) total -= n; return total; }; /** * Get products. * * @return {Array} */ Track.prototype.products = function(){ var props = this.properties(); var products = get(props, 'products'); return 'array' == type(products) ? products : []; }; /** * Get quantity. * * @return {Number} */ Track.prototype.quantity = function(){ var props = this.obj.properties || {}; return props.quantity || 1; }; /** * Get currency. * * @return {String} */ Track.prototype.currency = function(){ var props = this.obj.properties || {}; return props.currency || 'USD'; }; /** * BACKWARDS COMPATIBILITY: should probably re-examine where these come from. */ Track.prototype.referrer = Facade.proxy('properties.referrer'); Track.prototype.query = Facade.proxy('options.query'); /** * Get the call's properties. * * @param {Object} aliases * @return {Object} */ Track.prototype.properties = function (aliases) { var ret = this.field('properties') || {}; aliases = aliases || {}; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('properties.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Get the call's username. * * @return {String or Undefined} */ Track.prototype.username = function () { return this.proxy('traits.username') || this.proxy('properties.username') || this.userId() || this.sessionId(); }; /** * Get the call's email, using an the user ID if it's a valid email. * * @return {String or Undefined} */ Track.prototype.email = function () { var email = this.proxy('traits.email'); email = email || this.proxy('properties.email'); if (email) return email; var userId = this.userId(); if (isEmail(userId)) return userId; }; /** * Get the call's revenue, parsing it from a string with an optional leading * dollar sign. * * For products/services that don't have shipping and are not directly taxed, * they only care about tracking `revenue`. These are things like * SaaS companies, who sell monthly subscriptions. The subscriptions aren't * taxed directly, and since it's a digital product, it has no shipping. * * The only case where there's a difference between `revenue` and `total` * (in the context of analytics) is on ecommerce platforms, where they want * the `revenue` function to actually return the `total` (which includes * tax and shipping, total = subtotal + tax + shipping). This is probably * because on their backend they assume tax and shipping has been applied to * the value, and so can get the revenue on their own. * * @return {Number} */ Track.prototype.revenue = function () { var revenue = this.proxy('properties.revenue'); var event = this.event(); // it's always revenue, unless it's called during an order completion. if (!revenue && event && event.match(/completed ?order/i)) { revenue = this.proxy('properties.total'); } return currency(revenue); }; /** * Get cents. * * @return {Number} */ Track.prototype.cents = function(){ var revenue = this.revenue(); return 'number' != typeof revenue ? this.value() || 0 : revenue * 100; }; /** * A utility to turn the pieces of a track call into an identify. Used for * integrations with super properties or rate limits. * * TODO: remove me. * * @return {Facade} */ Track.prototype.identify = function () { var json = this.json(); json.traits = this.traits(); return new Identify(json); }; /** * Get float from currency value. * * @param {Mixed} val * @return {Number} */ function currency(val) { if (!val) return; if (typeof val === 'number') return val; if (typeof val !== 'string') return; val = val.replace(/\$/g, ''); val = parseFloat(val); if (!isNaN(val)) return val; } }, {"./utils":136,"./facade":127,"./identify":130,"is-email":162,"obj-case":138}], 132: [function(require, module, exports) { var inherit = require('./utils').inherit; var Facade = require('./facade'); var Track = require('./track'); /** * Expose `Page` facade */ module.exports = Page; /** * Initialize new `Page` facade with `dictionary`. * * @param {Object} dictionary * @param {String} category * @param {String} name * @param {Object} traits * @param {Object} options */ function Page(dictionary){ Facade.call(this, dictionary); } /** * Inherit from `Facade` */ inherit(Page, Facade); /** * Get the facade's action. * * @return {String} */ Page.prototype.type = Page.prototype.action = function(){ return 'page'; }; /** * Fields */ Page.prototype.category = Facade.field('category'); Page.prototype.name = Facade.field('name'); /** * Proxies. */ Page.prototype.title = Facade.proxy('properties.title'); Page.prototype.path = Facade.proxy('properties.path'); Page.prototype.url = Facade.proxy('properties.url'); /** * Get the page properties mixing `category` and `name`. * * @return {Object} */ Page.prototype.properties = function(){ var props = this.field('properties') || {}; var category = this.category(); var name = this.name(); if (category) props.category = category; if (name) props.name = name; return props; }; /** * Get the page fullName. * * @return {String} */ Page.prototype.fullName = function(){ var category = this.category(); var name = this.name(); return name && category ? category + ' ' + name : name; }; /** * Get event with `name`. * * @return {String} */ Page.prototype.event = function(name){ return name ? 'Viewed ' + name + ' Page' : 'Loaded a Page'; }; /** * Convert this Page to a Track facade with `name`. * * @param {String} name * @return {Track} */ Page.prototype.track = function(name){ var props = this.properties(); return new Track({ event: this.event(name), timestamp: this.timestamp(), context: this.context(), properties: props }); }; }, {"./utils":136,"./facade":127,"./track":131}], 133: [function(require, module, exports) { var inherit = require('./utils').inherit; var Page = require('./page'); var Track = require('./track'); /** * Expose `Screen` facade */ module.exports = Screen; /** * Initialize new `Screen` facade with `dictionary`. * * @param {Object} dictionary * @param {String} category * @param {String} name * @param {Object} traits * @param {Object} options */ function Screen(dictionary){ Page.call(this, dictionary); } /** * Inherit from `Page` */ inherit(Screen, Page); /** * Get the facade's action. * * @return {String} * @api public */ Screen.prototype.type = Screen.prototype.action = function(){ return 'screen'; }; /** * Get event with `name`. * * @param {String} name * @return {String} * @api public */ Screen.prototype.event = function(name){ return name ? 'Viewed ' + name + ' Screen' : 'Loaded a Screen'; }; /** * Convert this Screen. * * @param {String} name * @return {Track} * @api public */ Screen.prototype.track = function(name){ var props = this.properties(); return new Track({ event: this.event(name), timestamp: this.timestamp(), context: this.context(), properties: props }); }; }, {"./utils":136,"./page":132,"./track":131}], 125: [function(require, module, exports) { /** * Module dependencies. */ var stringify = require('querystring').stringify; var sub = require('substitute'); /** * Factory function to create a pixel loader. * * @param {String} path * @return {Function} * @api public */ module.exports = function(path){ return function(query, obj, fn){ if ('function' == typeof obj) fn = obj, obj = {}; obj = obj || {}; fn = fn || function(){}; var url = sub(path, obj); var img = new Image; img.onerror = error(fn, 'failed to load pixel', img); img.onload = function(){ fn(); }; query = stringify(query); if (query) query = '?' + query; img.src = url + query; img.width = 1; img.height = 1; return img; }; }; /** * Create an error handler. * * @param {Fucntion} fn * @param {String} message * @param {Image} img * @return {Function} * @api private */ function error(fn, message, img){ return function(e){ e = e || window.event; var err = new Error(message); err.event = e; err.source = img; fn(err); }; } }, {"querystring":126,"substitute":164}], 126: [function(require, module, exports) { /** * Module dependencies. */ var encode = encodeURIComponent; var decode = decodeURIComponent; var trim = require('trim'); var type = require('type'); /** * Parse the given query `str`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(str){ if ('string' != typeof str) return {}; str = trim(str); if ('' == str) return {}; if ('?' == str.charAt(0)) str = str.slice(1); var obj = {}; var pairs = str.split('&'); for (var i = 0; i < pairs.length; i++) { var parts = pairs[i].split('='); var key = decode(parts[0]); var m; if (m = /(\w+)\[(\d+)\]/.exec(key)) { obj[m[1]] = obj[m[1]] || []; obj[m[1]][m[2]] = decode(parts[1]); continue; } obj[parts[0]] = null == parts[1] ? '' : decode(parts[1]); } return obj; }; /** * Stringify the given `obj`. * * @param {Object} obj * @return {String} * @api public */ exports.stringify = function(obj){ if (!obj) return ''; var pairs = []; for (var key in obj) { var value = obj[key]; if ('array' == type(value)) { for (var i = 0; i < value.length; ++i) { pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i])); } continue; } pairs.push(encode(key) + '=' + encode(obj[key])); } return pairs.join('&'); }; }, {"trim":163,"type":7}], 164: [function(require, module, exports) { /** * Expose `substitute` */ module.exports = substitute; /** * Type. */ var type = Object.prototype.toString; /** * Substitute `:prop` with the given `obj` in `str` * * @param {String} str * @param {Object or Array} obj * @param {RegExp} expr * @return {String} * @api public */ function substitute(str, obj, expr){ if (!obj) throw new TypeError('expected an object'); expr = expr || /:(\w+)/g; return str.replace(expr, function(_, prop){ switch (type.call(obj)) { case '[object Object]': return null != obj[prop] ? obj[prop] : _; case '[object Array]': var val = obj.shift(); return null != val ? val : _; } }); } }, {}], 17: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var tick = require('next-tick'); /** * Expose `BugHerd` integration. */ var BugHerd = module.exports = integration('BugHerd') .assumesPageview() .global('BugHerdConfig') .global('_bugHerd') .option('apiKey', '') .option('showFeedbackTab', true) .tag('<script src="//www.bugherd.com/sidebarv2.js?apikey={{ apiKey }}">'); /** * Initialize. * * http://support.bugherd.com/home * * @param {Object} page */ BugHerd.prototype.initialize = function(page){ window.BugHerdConfig = { feedback: { hide: !this.options.showFeedbackTab }}; var ready = this.ready; this.load(function(){ tick(ready); }); }; /** * Loaded? * * @return {Boolean} */ BugHerd.prototype.loaded = function(){ return !! window._bugHerd; }; }, {"analytics.js-integration":83,"next-tick":97}], 18: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var is = require('is'); var extend = require('extend'); var onError = require('on-error'); /** * Expose `Bugsnag` integration. */ var Bugsnag = module.exports = integration('Bugsnag') .global('Bugsnag') .option('apiKey', '') .tag('<script src="//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js">'); /** * Initialize. * * https://bugsnag.com/docs/notifiers/js * * @param {Object} page */ Bugsnag.prototype.initialize = function(page){ var self = this; this.load(function(){ window.Bugsnag.apiKey = self.options.apiKey; self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Bugsnag.prototype.loaded = function(){ return is.object(window.Bugsnag); }; /** * Identify. * * @param {Identify} identify */ Bugsnag.prototype.identify = function(identify){ window.Bugsnag.metaData = window.Bugsnag.metaData || {}; extend(window.Bugsnag.metaData, identify.traits()); }; }, {"analytics.js-integration":83,"is":86,"extend":122,"on-error":165}], 165: [function(require, module, exports) { /** * Expose `onError`. */ module.exports = onError; /** * Callbacks. */ var callbacks = []; /** * Preserve existing handler. */ if ('function' == typeof window.onerror) callbacks.push(window.onerror); /** * Bind to `window.onerror`. */ window.onerror = handler; /** * Error handler. */ function handler () { for (var i = 0, fn; fn = callbacks[i]; i++) fn.apply(this, arguments); } /** * Call a `fn` on `window.onerror`. * * @param {Function} fn */ function onError (fn) { callbacks.push(fn); if (window.onerror != handler) { callbacks.push(window.onerror); window.onerror = handler; } } }, {}], 19: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var defaults = require('defaults'); var onBody = require('on-body'); /** * Expose `Chartbeat` integration. */ var Chartbeat = module.exports = integration('Chartbeat') .assumesPageview() .global('_sf_async_config') .global('_sf_endpt') .global('pSUPERFLY') .option('domain', '') .option('uid', null) .tag('<script src="//static.chartbeat.com/js/chartbeat.js">'); /** * Initialize. * * http://chartbeat.com/docs/configuration_variables/ * * @param {Object} page */ Chartbeat.prototype.initialize = function(page){ var self = this; window._sf_async_config = window._sf_async_config || {}; window._sf_async_config.useCanonical = true; defaults(window._sf_async_config, this.options); onBody(function(){ window._sf_endpt = new Date().getTime(); // Note: Chartbeat depends on document.body existing so the script does // not load until that is confirmed. Otherwise it may trigger errors. self.load(self.ready); }); }; /** * Loaded? * * @return {Boolean} */ Chartbeat.prototype.loaded = function(){ return !! window.pSUPERFLY; }; /** * Page. * * http://chartbeat.com/docs/handling_virtual_page_changes/ * * @param {Page} page */ Chartbeat.prototype.page = function(page){ var props = page.properties(); var name = page.fullName(); window.pSUPERFLY.virtualPage(props.path, name || props.title); }; }, {"analytics.js-integration":83,"defaults":166,"on-body":121}], 166: [function(require, module, exports) { /** * Expose `defaults`. */ module.exports = defaults; function defaults (dest, defaults) { for (var prop in defaults) { if (! (prop in dest)) { dest[prop] = defaults[prop]; } } return dest; }; }, {}], 20: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_cbq'); var each = require('each'); /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Supported events */ var supported = { activation: true, changePlan: true, register: true, refund: true, charge: true, cancel: true, login: true }; /** * Expose `ChurnBee` integration. */ var ChurnBee = module.exports = integration('ChurnBee') .global('_cbq') .global('ChurnBee') .option('apiKey', '') .tag('<script src="//api.churnbee.com/cb.js">') .mapping('events'); /** * Initialize. * * https://churnbee.com/docs * * @param {Object} page */ ChurnBee.prototype.initialize = function(page){ push('_setApiKey', this.options.apiKey); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ ChurnBee.prototype.loaded = function(){ return !! window.ChurnBee; }; /** * Track. * * @param {Track} event */ ChurnBee.prototype.track = function(track){ var event = track.event(); var events = this.events(event); events.push(event); each(events, function(event){ if (true != supported[event]) return; push(event, track.properties({ revenue: 'amount' })); }); }; }, {"analytics.js-integration":83,"global-queue":167,"each":4}], 167: [function(require, module, exports) { /** * Expose `generate`. */ module.exports = generate; /** * Generate a global queue pushing method with `name`. * * @param {String} name * @param {Object} options * @property {Boolean} wrap * @return {Function} */ function generate (name, options) { options = options || {}; return function (args) { args = [].slice.call(arguments); window[name] || (window[name] = []); options.wrap === false ? window[name].push.apply(window[name], args) : window[name].push(args); }; } }, {}], 21: [function(require, module, exports) { /** * Module dependencies. */ var date = require('load-date'); var domify = require('domify'); var each = require('each'); var integration = require('analytics.js-integration'); var is = require('is'); var useHttps = require('use-https'); var onBody = require('on-body'); /** * Expose `ClickTale` integration. */ var ClickTale = module.exports = integration('ClickTale') .assumesPageview() .global('WRInitTime') .global('ClickTale') .global('ClickTaleSetUID') .global('ClickTaleField') .global('ClickTaleEvent') .option('httpCdnUrl', 'http://s.clicktale.net/WRe0.js') .option('httpsCdnUrl', '') .option('projectId', '') .option('recordingRatio', 0.01) .option('partitionId', '') .tag('<script src="{{src}}">'); /** * Initialize. * * http://wiki.clicktale.com/Article/JavaScript_API * * @param {Object} page */ ClickTale.prototype.initialize = function(page){ var self = this; window.WRInitTime = date.getTime(); onBody(function(body){ body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">')); }); var http = this.options.httpCdnUrl; var https = this.options.httpsCdnUrl; if (useHttps() && !https) return this.debug('https option required'); var src = useHttps() ? https : http; this.load({ src: src }, function(){ window.ClickTale( self.options.projectId, self.options.recordingRatio, self.options.partitionId ); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ ClickTale.prototype.loaded = function(){ return is.fn(window.ClickTale); }; /** * Identify. * * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleSetUID * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleField * * @param {Identify} identify */ ClickTale.prototype.identify = function(identify){ var id = identify.userId(); window.ClickTaleSetUID(id); each(identify.traits(), function(key, value){ window.ClickTaleField(key, value); }); }; /** * Track. * * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleEvent * * @param {Track} track */ ClickTale.prototype.track = function(track){ window.ClickTaleEvent(track.event()); }; }, {"load-date":168,"domify":119,"each":4,"analytics.js-integration":83,"is":86,"use-https":85,"on-body":121}], 168: [function(require, module, exports) { /* * Load date. * * For reference: http://www.html5rocks.com/en/tutorials/webperformance/basics/ */ var time = new Date() , perf = window.performance; if (perf && perf.timing && perf.timing.responseEnd) { time = new Date(perf.timing.responseEnd); } module.exports = time; }, {}], 22: [function(require, module, exports) { /** * Module dependencies. */ var Identify = require('facade').Identify; var extend = require('extend'); var integration = require('analytics.js-integration'); var is = require('is'); /** * Expose `Clicky` integration. */ var Clicky = module.exports = integration('Clicky') .assumesPageview() .global('clicky') .global('clicky_site_ids') .global('clicky_custom') .option('siteId', null) .tag('<script src="//static.getclicky.com/js"></script>'); /** * Initialize. * * http://clicky.com/help/customization * * @param {Object} page */ Clicky.prototype.initialize = function(page){ var user = this.analytics.user(); window.clicky_site_ids = window.clicky_site_ids || [this.options.siteId]; this.identify(new Identify({ userId: user.id(), traits: user.traits() })); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Clicky.prototype.loaded = function(){ return is.object(window.clicky); }; /** * Page. * * http://clicky.com/help/customization#/help/custom/manual * * @param {Page} page */ Clicky.prototype.page = function(page){ var properties = page.properties(); var category = page.category(); var name = page.fullName(); window.clicky.log(properties.path, name || properties.title); }; /** * Identify. * * @param {Identify} id (optional) */ Clicky.prototype.identify = function(identify){ window.clicky_custom = window.clicky_custom || {}; window.clicky_custom.session = window.clicky_custom.session || {}; extend(window.clicky_custom.session, identify.traits()); }; /** * Track. * * http://clicky.com/help/customization#/help/custom/manual * * @param {Track} event */ Clicky.prototype.track = function(track){ window.clicky.goal(track.event(), track.revenue()); }; }, {"facade":124,"extend":122,"analytics.js-integration":83,"is":86}], 23: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var useHttps = require('use-https'); /** * Expose `Comscore` integration. */ var Comscore = module.exports = integration('comScore') .assumesPageview() .global('_comscore') .global('COMSCORE') .option('c1', '2') .option('c2', '') .tag('http', '<script src="http://b.scorecardresearch.com/beacon.js">') .tag('https', '<script src="https://sb.scorecardresearch.com/beacon.js">'); /** * Initialize. * * @param {Object} page */ Comscore.prototype.initialize = function(page){ window._comscore = window._comscore || [this.options]; var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ Comscore.prototype.loaded = function(){ return !! window.COMSCORE; }; }, {"analytics.js-integration":83,"use-https":85}], 24: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `CrazyEgg` integration. */ var CrazyEgg = module.exports = integration('Crazy Egg') .assumesPageview() .global('CE2') .option('accountNumber', '') .tag('<script src="//dnn506yrbagrg.cloudfront.net/pages/scripts/{{ path }}.js?{{ cache }}">'); /** * Initialize. * * @param {Object} page */ CrazyEgg.prototype.initialize = function(page){ var number = this.options.accountNumber; var path = number.slice(0,4) + '/' + number.slice(4); var cache = Math.floor(new Date().getTime() / 3600000); this.load({ path: path, cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ CrazyEgg.prototype.loaded = function(){ return !! window.CE2; }; }, {"analytics.js-integration":83}], 25: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_curebitq'); var Identify = require('facade').Identify; var throttle = require('throttle'); var Track = require('facade').Track; var iso = require('to-iso-string'); var clone = require('clone'); var each = require('each'); var bind = require('bind'); /** * Expose `Curebit` integration. */ var Curebit = module.exports = integration('Curebit') .global('_curebitq') .global('curebit') .option('siteId', '') .option('iframeWidth', '100%') .option('iframeHeight', '480') .option('iframeBorder', 0) .option('iframeId', 'curebit_integration') .option('responsive', true) .option('device', '') .option('insertIntoId', '') .option('campaigns', {}) .option('server', 'https://www.curebit.com') .tag('<script src="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js">'); /** * Initialize. * * @param {Object} page */ Curebit.prototype.initialize = function(page){ push('init', { site_id: this.options.siteId, server: this.options.server }); this.load(this.ready); // throttle the call to `page` since curebit needs to append an iframe this.page = throttle(bind(this, this.page), 250); }; /** * Loaded? * * @return {Boolean} */ Curebit.prototype.loaded = function(){ return !!window.curebit; }; /** * Page. * * Call the `register_affiliate` method of the Curebit API that will load a * custom iframe onto the page, only if this page's path is marked as a * campaign. * * http://www.curebit.com/docs/affiliate/registration * * This is throttled to prevent accidentally drawing the iframe multiple times, * from multiple `.page()` calls. The `250` is from the curebit script. * * @param {String} url * @param {String} id * @param {Function} fn * @api private */ Curebit.prototype.injectIntoId = function(url, id, fn){ var server = this.options.server; when(function(){ return document.getElementById(id); }, function(){ var script = document.createElement('script'); script.src = url; var parent = document.getElementById(id); parent.appendChild(script); onload(script, fn); }); }; /** * Campaign tags. * * @param {Page} page */ Curebit.prototype.page = function(page){ var user = this.analytics.user(); var campaigns = this.options.campaigns; var path = window.location.pathname; if (!campaigns[path]) return; var tags = (campaigns[path] || '').split(','); if (!tags.length) return; var settings = { responsive: this.options.responsive, device: this.options.device, campaign_tags: tags, iframe: { width: this.options.iframeWidth, height: this.options.iframeHeight, id: this.options.iframeId, frameborder: this.options.iframeBorder, container: this.options.insertIntoId } }; var identify = new Identify({ userId: user.id(), traits: user.traits() }); // if we have an email, add any information about the user if (identify.email()) { settings.affiliate_member = { email: identify.email(), first_name: identify.firstName(), last_name: identify.lastName(), customer_id: identify.userId() }; } push('register_affiliate', settings); }; /** * Completed order. * * Fire the Curebit `register_purchase` with the order details and items. * * https://www.curebit.com/docs/ecommerce/custom * * @param {Track} track */ Curebit.prototype.completedOrder = function(track){ var user = this.analytics.user(); var orderId = track.orderId(); var products = track.products(); var props = track.properties(); var items = []; var identify = new Identify({ traits: user.traits(), userId: user.id() }); each(products, function(product){ var track = new Track({ properties: product }); items.push({ product_id: track.id() || track.sku(), quantity: track.quantity(), image_url: product.image, price: track.price(), title: track.name(), url: product.url, }); }); push('register_purchase', { order_date: iso(props.date || new Date()), order_number: orderId, coupon_code: track.coupon(), subtotal: track.total(), customer_id: identify.userId(), first_name: identify.firstName(), last_name: identify.lastName(), email: identify.email(), items: items }); }; }, {"analytics.js-integration":83,"global-queue":167,"facade":124,"throttle":169,"to-iso-string":170,"clone":171,"each":4,"bind":95}], 169: [function(require, module, exports) { /** * Module exports. */ module.exports = throttle; /** * Returns a new function that, when invoked, invokes `func` at most one time per * `wait` milliseconds. * * @param {Function} func The `Function` instance to wrap. * @param {Number} wait The minimum number of milliseconds that must elapse in between `func` invokations. * @return {Function} A new function that wraps the `func` function passed in. * @api public */ function throttle (func, wait) { var rtn; // return value var last = 0; // last invokation timestamp return function throttled () { var now = new Date().getTime(); var delta = now - last; if (delta >= wait) { rtn = func.apply(this, arguments); last = now; } return rtn; }; } }, {}], 170: [function(require, module, exports) { /** * Expose `toIsoString`. */ module.exports = toIsoString; /** * Turn a `date` into an ISO string. * * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString * * @param {Date} date * @return {String} */ function toIsoString (date) { return date.getUTCFullYear() + '-' + pad(date.getUTCMonth() + 1) + '-' + pad(date.getUTCDate()) + 'T' + pad(date.getUTCHours()) + ':' + pad(date.getUTCMinutes()) + ':' + pad(date.getUTCSeconds()) + '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5) + 'Z'; } /** * Pad a `number` with a ten's place zero. * * @param {Number} number * @return {String} */ function pad (number) { var n = number.toString(); return n.length === 1 ? '0' + n : n; } }, {}], 171: [function(require, module, exports) { /** * Module dependencies. */ var type; try { type = require('type'); } catch(e){ type = require('type-component'); } /** * Module exports. */ module.exports = clone; /** * Clones objects. * * @param {Mixed} any object * @api public */ function clone(obj){ switch (type(obj)) { case 'object': var copy = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { copy[key] = clone(obj[key]); } } return copy; case 'array': var copy = new Array(obj.length); for (var i = 0, l = obj.length; i < l; i++) { copy[i] = clone(obj[i]); } return copy; case 'regexp': // from millermedeiros/amd-utils - MIT var flags = ''; flags += obj.multiline ? 'm' : ''; flags += obj.global ? 'g' : ''; flags += obj.ignoreCase ? 'i' : ''; return new RegExp(obj.source, flags); case 'date': return new Date(obj.getTime()); default: // string, number, boolean, … return obj; } } }, {"type":7}], 26: [function(require, module, exports) { /** * Module dependencies. */ var alias = require('alias'); var convertDates = require('convert-dates'); var Identify = require('facade').Identify; var integration = require('analytics.js-integration'); /** * Expose `Customerio` integration. */ var Customerio = module.exports = integration('Customer.io') .assumesPageview() .global('_cio') .option('siteId', '') .tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">'); /** * Initialize. * * http://customer.io/docs/api/javascript.html * * @param {Object} page */ Customerio.prototype.initialize = function(page){ window._cio = window._cio || []; (function(){var a,b,c; a = function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0))); }; }; b = ['identify', 'track']; for (c = 0; c < b.length; c++) {window._cio[b[c]] = a(b[c]); } })(); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Customerio.prototype.loaded = function(){ return (!! window._cio) && (window._cio.push !== Array.prototype.push); }; /** * Identify. * * http://customer.io/docs/api/javascript.html#section-Identify_customers * * @param {Identify} identify */ Customerio.prototype.identify = function(identify){ if (!identify.userId()) return this.debug('user id required'); var traits = identify.traits({ created: 'created_at' }); traits = convertDates(traits, convertDate); window._cio.identify(traits); }; /** * Group. * * @param {Group} group */ Customerio.prototype.group = function(group){ var traits = group.traits(); var user = this.analytics.user(); traits = alias(traits, function(trait){ return 'Group ' + trait; }); this.identify(new Identify({ userId: user.id(), traits: traits })); }; /** * Track. * * http://customer.io/docs/api/javascript.html#section-Track_a_custom_event * * @param {Track} track */ Customerio.prototype.track = function(track){ var properties = track.properties(); properties = convertDates(properties, convertDate); window._cio.track(track.event(), properties); }; /** * Convert a date to the format Customer.io supports. * * @param {Date} date * @return {Number} */ function convertDate(date){ return Math.floor(date.getTime() / 1000); } }, {"alias":172,"convert-dates":173,"facade":124,"analytics.js-integration":83}], 172: [function(require, module, exports) { var type = require('type'); try { var clone = require('clone'); } catch (e) { var clone = require('clone-component'); } /** * Expose `alias`. */ module.exports = alias; /** * Alias an `object`. * * @param {Object} obj * @param {Mixed} method */ function alias (obj, method) { switch (type(method)) { case 'object': return aliasByDictionary(clone(obj), method); case 'function': return aliasByFunction(clone(obj), method); } } /** * Convert the keys in an `obj` using a dictionary of `aliases`. * * @param {Object} obj * @param {Object} aliases */ function aliasByDictionary (obj, aliases) { for (var key in aliases) { if (undefined === obj[key]) continue; obj[aliases[key]] = obj[key]; delete obj[key]; } return obj; } /** * Convert the keys in an `obj` using a `convert` function. * * @param {Object} obj * @param {Function} convert */ function aliasByFunction (obj, convert) { // have to create another object so that ie8 won't infinite loop on keys var output = {}; for (var key in obj) output[convert(key)] = obj[key]; return output; } }, {"type":7,"clone":143}], 173: [function(require, module, exports) { var is = require('is'); try { var clone = require('clone'); } catch (e) { var clone = require('clone-component'); } /** * Expose `convertDates`. */ module.exports = convertDates; /** * Recursively convert an `obj`'s dates to new values. * * @param {Object} obj * @param {Function} convert * @return {Object} */ function convertDates (obj, convert) { obj = clone(obj); for (var key in obj) { var val = obj[key]; if (is.date(val)) obj[key] = convert(val); if (is.object(val)) obj[key] = convertDates(val, convert); } return obj; } }, {"is":86,"clone":89}], 27: [function(require, module, exports) { /** * Module dependencies. */ var alias = require('alias'); var integration = require('analytics.js-integration'); var is = require('is'); var load = require('load-script'); var push = require('global-queue')('_dcq'); /** * Expose `Drip` integration. */ var Drip = module.exports = integration('Drip') .assumesPageview() .global('dc') .global('_dcq') .global('_dcs') .option('account', '') .tag('<script src="//tag.getdrip.com/{{ account }}.js">'); /** * Initialize. * * @param {Object} page */ Drip.prototype.initialize = function(page){ window._dcq = window._dcq || []; window._dcs = window._dcs || {}; window._dcs.account = this.options.account; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Drip.prototype.loaded = function(){ return is.object(window.dc); }; /** * Track. * * @param {Track} track */ Drip.prototype.track = function(track){ var props = track.properties(); var cents = track.cents(); if (cents) props.value = cents; delete props.revenue; push('track', track.event(), props); }; /** * Identify. * * @param {Identify} identify */ Drip.prototype.identify = function (identify) { push('identify', identify.traits()); }; }, {"alias":172,"analytics.js-integration":83,"is":86,"load-script":120,"global-queue":167}], 28: [function(require, module, exports) { /** * Module dependencies. */ var extend = require('extend'); var integration = require('analytics.js-integration'); var onError = require('on-error'); var push = require('global-queue')('_errs'); /** * Expose `Errorception` integration. */ var Errorception = module.exports = integration('Errorception') .assumesPageview() .global('_errs') .option('projectId', '') .option('meta', true) .tag('<script src="//beacon.errorception.com/{{ projectId }}.js">'); /** * Initialize. * * https://github.com/amplitude/Errorception-Javascript * * @param {Object} page */ Errorception.prototype.initialize = function(page){ window._errs = window._errs || [this.options.projectId]; onError(push); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Errorception.prototype.loaded = function(){ return !! (window._errs && window._errs.push !== Array.prototype.push); }; /** * Identify. * * http://blog.errorception.com/2012/11/capture-custom-data-with-your-errors.html * * @param {Object} identify */ Errorception.prototype.identify = function(identify){ if (!this.options.meta) return; var traits = identify.traits(); window._errs = window._errs || []; window._errs.meta = window._errs.meta || {}; extend(window._errs.meta, traits); }; }, {"extend":122,"analytics.js-integration":83,"on-error":165,"global-queue":167}], 29: [function(require, module, exports) { /** * Module dependencies. */ var each = require('each'); var integration = require('analytics.js-integration'); var push = require('global-queue')('_aaq'); /** * Expose `Evergage` integration.integration. */ var Evergage = module.exports = integration('Evergage') .assumesPageview() .global('_aaq') .option('account', '') .option('dataset', '') .tag('<script src="//cdn.evergage.com/beacon/{{ account }}/{{ dataset }}/scripts/evergage.min.js">'); /** * Initialize. * * @param {Object} page */ Evergage.prototype.initialize = function(page){ var account = this.options.account; var dataset = this.options.dataset; window._aaq = window._aaq || []; push('setEvergageAccount', account); push('setDataset', dataset); push('setUseSiteConfig', true); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Evergage.prototype.loaded = function(){ return !! (window._aaq && window._aaq.push !== Array.prototype.push); }; /** * Page. * * @param {Page} page */ Evergage.prototype.page = function(page){ var props = page.properties(); var name = page.name(); if (name) push('namePage', name); each(props, function(key, value){ push('setCustomField', key, value, 'page'); }); window.Evergage.init(true); }; /** * Identify. * * @param {Identify} identify */ Evergage.prototype.identify = function(identify){ var id = identify.userId(); if (!id) return; push('setUser', id); var traits = identify.traits({ email: 'userEmail', name: 'userName' }); each(traits, function(key, value){ push('setUserField', key, value, 'page'); }); }; /** * Group. * * @param {Group} group */ Evergage.prototype.group = function(group){ var props = group.traits(); var id = group.groupId(); if (!id) return; push('setCompany', id); each(props, function(key, value){ push('setAccountField', key, value, 'page'); }); }; /** * Track. * * @param {Track} track */ Evergage.prototype.track = function(track){ push('trackAction', track.event(), track.properties()); }; }, {"each":4,"analytics.js-integration":83,"global-queue":167}], 30: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_fbq'); var each = require('each'); /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `Facebook` */ var Facebook = module.exports = integration('Facebook Conversion Tracking') .global('_fbq') .option('currency', 'USD') .tag('<script src="//connect.facebook.net/en_US/fbds.js">') .mapping('events'); /** * Initialize Facebook Conversion Tracking * * https://developers.facebook.com/docs/ads-for-websites/conversion-pixel-code-migration * * @param {Object} page */ Facebook.prototype.initialize = function(page){ window._fbq = window._fbq || []; this.load(this.ready); window._fbq.loaded = true; }; /** * Loaded? * * @return {Boolean} */ Facebook.prototype.loaded = function(){ return !! (window._fbq && window._fbq.loaded); }; /** * Track. * * https://developers.facebook.com/docs/reference/ads-api/custom-audience-website-faq/#fbpixel * * @param {Track} track */ Facebook.prototype.track = function(track){ var event = track.event(); var events = this.events(event); var revenue = track.revenue() || 0; var self = this; each(events, function(event){ push('track', event, { value: String(revenue.toFixed(2)), currency: self.options.currency }); }); if (!events.length) { var data = track.properties(); push('track', event, data); } }; }, {"analytics.js-integration":83,"global-queue":167,"each":4}], 31: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('_fxm'); var integration = require('analytics.js-integration'); var Track = require('facade').Track; var each = require('each'); /** * Expose `FoxMetrics` integration. */ var FoxMetrics = module.exports = integration('FoxMetrics') .assumesPageview() .global('_fxm') .option('appId', '') .tag('<script src="//d35tca7vmefkrc.cloudfront.net/scripts/{{ appId }}.js">'); /** * Initialize. * * http://foxmetrics.com/documentation/apijavascript * * @param {Object} page */ FoxMetrics.prototype.initialize = function(page){ window._fxm = window._fxm || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ FoxMetrics.prototype.loaded = function(){ return !! (window._fxm && window._fxm.appId); }; /** * Page. * * @param {Page} page */ FoxMetrics.prototype.page = function(page){ var properties = page.proxy('properties'); var category = page.category(); var name = page.name(); this._category = category; // store for later push( '_fxm.pages.view', properties.title, // title name, // name category, // category properties.url, // url properties.referrer // referrer ); }; /** * Identify. * * @param {Identify} identify */ FoxMetrics.prototype.identify = function(identify){ var id = identify.userId(); if (!id) return; push( '_fxm.visitor.profile', id, // user id identify.firstName(), // first name identify.lastName(), // last name identify.email(), // email identify.address(), // address undefined, // social undefined, // partners identify.traits() // attributes ); }; /** * Track. * * @param {Track} track */ FoxMetrics.prototype.track = function(track){ var props = track.properties(); var category = this._category || props.category; push(track.event(), category, props); }; /** * Viewed product. * * @param {Track} track * @api private */ FoxMetrics.prototype.viewedProduct = function(track){ ecommerce('productview', track); }; /** * Removed product. * * @param {Track} track * @api private */ FoxMetrics.prototype.removedProduct = function(track){ ecommerce('removecartitem', track); }; /** * Added product. * * @param {Track} track * @api private */ FoxMetrics.prototype.addedProduct = function(track){ ecommerce('cartitem', track); }; /** * Completed Order. * * @param {Track} track * @api private */ FoxMetrics.prototype.completedOrder = function(track){ var orderId = track.orderId(); // transaction push( '_fxm.ecommerce.order', orderId, track.subtotal(), track.shipping(), track.tax(), track.city(), track.state(), track.zip(), track.quantity() ); // items each(track.products(), function(product){ var track = new Track({ properties: product }); ecommerce('purchaseitem', track, [ track.quantity(), track.price(), orderId ]); }); }; /** * Track ecommerce `event` with `track` * with optional `arr` to append. * * @param {String} event * @param {Track} track * @param {Array} arr * @api private */ function ecommerce(event, track, arr){ push.apply(null, [ '_fxm.ecommerce.' + event, track.id() || track.sku(), track.name(), track.category() ].concat(arr || [])); } }, {"global-queue":167,"analytics.js-integration":83,"facade":124,"each":4}], 32: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var bind = require('bind'); var when = require('when'); var is = require('is'); /** * Expose `Frontleaf` integration. */ var Frontleaf = module.exports = integration('Frontleaf') .assumesPageview() .global('_fl') .global('_flBaseUrl') .option('baseUrl', 'https://api.frontleaf.com') .option('token', '') .option('stream', '') .option('trackNamedPages', false) .option('trackCategorizedPages', false) .tag('<script id="_fl" src="{{ baseUrl }}/lib/tracker.js">'); /** * Initialize. * * http://docs.frontleaf.com/#/technical-implementation/tracking-customers/tracking-beacon * * @param {Object} page */ Frontleaf.prototype.initialize = function(page){ window._fl = window._fl || []; window._flBaseUrl = window._flBaseUrl || this.options.baseUrl; this._push('setApiToken', this.options.token); this._push('setStream', this.options.stream); var loaded = bind(this, this.loaded); var ready = this.ready; this.load({ baseUrl: window._flBaseUrl }, this.ready); }; /** * Loaded? * * @return {Boolean} */ Frontleaf.prototype.loaded = function(){ return is.array(window._fl) && window._fl.ready === true; }; /** * Identify. * * @param {Identify} identify */ Frontleaf.prototype.identify = function(identify){ var userId = identify.userId(); if (userId) { this._push('setUser', { id: userId, name: identify.name() || identify.username(), data: clean(identify.traits()) }); } }; /** * Group. * * @param {Group} group */ Frontleaf.prototype.group = function(group){ var groupId = group.groupId(); if (groupId) { this._push('setAccount', { id: groupId, name: group.proxy('traits.name'), data: clean(group.traits()) }); } }; /** * Page. * * @param {Page} page */ Frontleaf.prototype.page = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Track. * * @param {Track} track */ Frontleaf.prototype.track = function(track){ var event = track.event(); this._push('event', event, clean(track.properties())); }; /** * Push a command onto the global Frontleaf queue. * * @param {String} command * @return {Object} args * @api private */ Frontleaf.prototype._push = function(command){ var args = [].slice.call(arguments, 1); window._fl.push(function(t){ t[command].apply(command, args); }); }; /** * Clean all nested objects and arrays. * * @param {Object} obj * @return {Object} * @api private */ function clean(obj){ var ret = {}; // Remove traits/properties that are already represented // outside of the data container var excludeKeys = ["id","name","firstName","lastName"]; var len = excludeKeys.length; for (var i = 0; i < len; i++) { clear(obj, excludeKeys[i]); } // Flatten nested hierarchy, preserving arrays obj = flatten(obj); // Discard nulls, represent arrays as comma-separated strings for (var key in obj) { var val = obj[key]; if (null == val) { continue; } if (is.array(val)) { ret[key] = val.toString(); continue; } ret[key] = val; } return ret; } /** * Remove a property from an object if set. * * @param {Object} obj * @param {String} key * @api private */ function clear(obj, key){ if (obj.hasOwnProperty(key)) { delete obj[key]; } } /** * Flatten a nested object into a single level space-delimited * hierarchy. * * Based on https://github.com/hughsk/flat * * @param {Object} source * @return {Object} * @api private */ function flatten(source){ var output = {}; function step(object, prev){ for (var key in object) { var value = object[key]; var newKey = prev ? prev + ' ' + key : key; if (!is.array(value) && is.object(value)) { return step(value, newKey); } output[newKey] = value; } } step(source); return output; } }, {"analytics.js-integration":83,"bind":95,"when":123,"is":86}], 33: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_gauges'); /** * Expose `Gauges` integration. */ var Gauges = module.exports = integration('Gauges') .assumesPageview() .global('_gauges') .option('siteId', '') .tag('<script id="gauges-tracker" src="//secure.gaug.es/track.js" data-site-id="{{ siteId }}">'); /** * Initialize Gauges. * * http://get.gaug.es/documentation/tracking/ * * @param {Object} page */ Gauges.prototype.initialize = function(page){ window._gauges = window._gauges || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Gauges.prototype.loaded = function(){ return !! (window._gauges && window._gauges.push !== Array.prototype.push); }; /** * Page. * * @param {Page} page */ Gauges.prototype.page = function(page){ push('track'); }; }, {"analytics.js-integration":83,"global-queue":167}], 34: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var onBody = require('on-body'); /** * Expose `GetSatisfaction` integration. */ var GetSatisfaction = module.exports = integration('Get Satisfaction') .assumesPageview() .global('GSFN') .option('widgetId', '') .tag('<script src="https://loader.engage.gsfn.us/loader.js">'); /** * Initialize. * * https://console.getsatisfaction.com/start/101022?signup=true#engage * * @param {Object} page */ GetSatisfaction.prototype.initialize = function(page){ var self = this; var widget = this.options.widgetId; var div = document.createElement('div'); var id = div.id = 'getsat-widget-' + widget; onBody(function(body){ body.appendChild(div); }); // usually the snippet is sync, so wait for it before initializing the tab this.load(function(){ window.GSFN.loadWidget(widget, { containerId: id }); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ GetSatisfaction.prototype.loaded = function(){ return !! window.GSFN; }; }, {"analytics.js-integration":83,"on-body":121}], 35: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_gaq'); var length = require('object').length; var canonical = require('canonical'); var useHttps = require('use-https'); var Track = require('facade').Track; var callback = require('callback'); var load = require('load-script'); var keys = require('object').keys; var dot = require('obj-case'); var each = require('each'); var type = require('type'); var url = require('url'); var is = require('is'); var group; var user; /** * Expose plugin. */ module.exports = exports = function(analytics){ analytics.addIntegration(GA); group = analytics.group(); user = analytics.user(); }; /** * Expose `GA` integration. * * http://support.google.com/analytics/bin/answer.py?hl=en&answer=2558867 * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration#_gat.GA_Tracker_._setSiteSpeedSampleRate */ var GA = exports.Integration = integration('Google Analytics') .readyOnLoad() .global('ga') .global('gaplugins') .global('_gaq') .global('GoogleAnalyticsObject') .option('anonymizeIp', false) .option('classic', false) .option('domain', 'none') .option('doubleClick', false) .option('enhancedLinkAttribution', false) .option('ignoredReferrers', null) .option('includeSearch', false) .option('siteSpeedSampleRate', 1) .option('trackingId', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .option('sendUserId', false) .option('metrics', {}) .option('dimensions', {}) .tag('library', '<script src="//www.google-analytics.com/analytics.js">') .tag('double click', '<script src="//stats.g.doubleclick.net/dc.js">') .tag('http', '<script src="http://www.google-analytics.com/ga.js">') .tag('https', '<script src="https://ssl.google-analytics.com/ga.js">'); /** * When in "classic" mode, on `construct` swap all of the method to point to * their classic counterparts. */ GA.on('construct', function(integration){ if (!integration.options.classic) return; integration.initialize = integration.initializeClassic; integration.loaded = integration.loadedClassic; integration.page = integration.pageClassic; integration.track = integration.trackClassic; integration.completedOrder = integration.completedOrderClassic; }); /** * Initialize. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced */ GA.prototype.initialize = function(){ var opts = this.options; // setup the tracker globals window.GoogleAnalyticsObject = 'ga'; window.ga = window.ga || function(){ window.ga.q = window.ga.q || []; window.ga.q.push(arguments); }; window.ga.l = new Date().getTime(); window.ga('create', opts.trackingId, { cookieDomain: opts.domain || GA.prototype.defaults.domain, // to protect against empty string siteSpeedSampleRate: opts.siteSpeedSampleRate, allowLinker: true }); // display advertising if (opts.doubleClick) { window.ga('require', 'displayfeatures'); } // send global id if (opts.sendUserId && user.id()) { window.ga('set', 'userId', user.id()); } // anonymize after initializing, otherwise a warning is shown // in google analytics debugger if (opts.anonymizeIp) window.ga('set', 'anonymizeIp', true); // custom dimensions & metrics var custom = metrics(user.traits(), opts); if (length(custom)) window.ga('set', custom); this.load('library', this.ready); }; /** * Loaded? * * @return {Boolean} */ GA.prototype.loaded = function(){ return !! window.gaplugins; }; /** * Page. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/pages * * @param {Page} page */ GA.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); var pageview = {}; var track; this._category = category; // store for later // send window.ga('send', 'pageview', { page: path(props, this.options), title: name || props.title, location: props.url }); // categorized pages if (category && this.options.trackCategorizedPages) { track = page.track(category); this.track(track, { noninteraction: true }); } // named pages if (name && this.options.trackNamedPages) { track = page.track(name); this.track(track, { noninteraction: true }); } }; /** * Track. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/events * https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference * * @param {Track} event */ GA.prototype.track = function(track, options){ var opts = options || track.options(this.name); var props = track.properties(); window.ga('send', 'event', { eventAction: track.event(), eventCategory: props.category || this._category || 'All', eventLabel: props.label, eventValue: formatValue(props.value || track.revenue()), nonInteraction: props.noninteraction || opts.noninteraction }); }; /** * Completed order. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce * https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce#multicurrency * * @param {Track} track * @api private */ GA.prototype.completedOrder = function(track){ var total = track.total() || track.revenue() || 0; var orderId = track.orderId(); var products = track.products(); var props = track.properties(); // orderId is required. if (!orderId) return; // require ecommerce if (!this.ecommerce) { window.ga('require', 'ecommerce'); this.ecommerce = true; } // add transaction window.ga('ecommerce:addTransaction', { affiliation: props.affiliation, shipping: track.shipping(), revenue: total, tax: track.tax(), id: orderId, currency: track.currency() }); // add products each(products, function(product){ var track = new Track({ properties: product }); window.ga('ecommerce:addItem', { category: track.category(), quantity: track.quantity(), price: track.price(), name: track.name(), sku: track.sku(), id: orderId, currency: track.currency() }); }); // send window.ga('ecommerce:send'); }; /** * Initialize (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration */ GA.prototype.initializeClassic = function(){ var opts = this.options; var anonymize = opts.anonymizeIp; var db = opts.doubleClick; var domain = opts.domain; var enhanced = opts.enhancedLinkAttribution; var ignore = opts.ignoredReferrers; var sample = opts.siteSpeedSampleRate; window._gaq = window._gaq || []; push('_setAccount', opts.trackingId); push('_setAllowLinker', true); if (anonymize) push('_gat._anonymizeIp'); if (domain) push('_setDomainName', domain); if (sample) push('_setSiteSpeedSampleRate', sample); if (enhanced) { var protocol = 'https:' === document.location.protocol ? 'https:' : 'http:'; var pluginUrl = protocol + '//www.google-analytics.com/plugins/ga/inpage_linkid.js'; push('_require', 'inpage_linkid', pluginUrl); } if (ignore) { if (!is.array(ignore)) ignore = [ignore]; each(ignore, function (domain) { push('_addIgnoredRef', domain); }); } if (this.options.doubleClick) { this.load('double click', this.ready); } else { var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); } }; /** * Loaded? (classic) * * @return {Boolean} */ GA.prototype.loadedClassic = function(){ return !! (window._gaq && window._gaq.push !== Array.prototype.push); }; /** * Page (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration * * @param {Page} page */ GA.prototype.pageClassic = function(page){ var opts = page.options(this.name); var category = page.category(); var props = page.properties(); var name = page.fullName(); var track; push('_trackPageview', path(props, this.options)); // categorized pages if (category && this.options.trackCategorizedPages) { track = page.track(category); this.track(track, { noninteraction: true }); } // named pages if (name && this.options.trackNamedPages) { track = page.track(name); this.track(track, { noninteraction: true }); } }; /** * Track (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking * * @param {Track} track */ GA.prototype.trackClassic = function(track, options){ var opts = options || track.options(this.name); var props = track.properties(); var revenue = track.revenue(); var event = track.event(); var category = this._category || props.category || 'All'; var label = props.label; var value = formatValue(revenue || props.value); var noninteraction = props.noninteraction || opts.noninteraction; push('_trackEvent', category, event, label, value, noninteraction); }; /** * Completed order. * * https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce * https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce#localcurrencies * * @param {Track} track * @api private */ GA.prototype.completedOrderClassic = function(track){ var total = track.total() || track.revenue() || 0; var orderId = track.orderId(); var products = track.products() || []; var props = track.properties(); var currency = track.currency(); // required if (!orderId) return; // add transaction push('_addTrans' , orderId , props.affiliation , total , track.tax() , track.shipping() , track.city() , track.state() , track.country()); // add items each(products, function(product){ var track = new Track({ properties: product }); push('_addItem' , orderId , track.sku() , track.name() , track.category() , track.price() , track.quantity()); }); // send push('_set', 'currencyCode', currency); push('_trackTrans'); }; /** * Return the path based on `properties` and `options`. * * @param {Object} properties * @param {Object} options */ function path(properties, options) { if (!properties) return; var str = properties.path; if (options.includeSearch && properties.search) str += properties.search; return str; } /** * Format the value property to Google's liking. * * @param {Number} value * @return {Number} */ function formatValue(value) { if (!value || value < 0) return 0; return Math.round(value); } /** * Map google's custom dimensions & metrics with `obj`. * * Example: * * metrics({ revenue: 1.9 }, { { metrics : { revenue: 'metric8' } }); * // => { metric8: 1.9 } * * metrics({ revenue: 1.9 }, {}); * // => {} * * @param {Object} obj * @param {Object} data * @return {Object|null} * @api private */ function metrics(obj, data){ var dimensions = data.dimensions; var metrics = data.metrics; var names = keys(metrics).concat(keys(dimensions)); var ret = {}; for (var i = 0; i < names.length; ++i) { var name = names[i]; var key = metrics[name] || dimensions[name]; var value = dot(obj, name) || obj[name]; if (null == value) continue; ret[key] = value; } return ret; } }, {"analytics.js-integration":83,"global-queue":167,"object":174,"canonical":175,"use-https":85,"facade":124,"callback":88,"load-script":120,"obj-case":138,"each":4,"type":7,"url":176,"is":86}], 174: [function(require, module, exports) { /** * HOP ref. */ var has = Object.prototype.hasOwnProperty; /** * Return own keys in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.keys = Object.keys || function(obj){ var keys = []; for (var key in obj) { if (has.call(obj, key)) { keys.push(key); } } return keys; }; /** * Return own values in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.values = function(obj){ var vals = []; for (var key in obj) { if (has.call(obj, key)) { vals.push(obj[key]); } } return vals; }; /** * Merge `b` into `a`. * * @param {Object} a * @param {Object} b * @return {Object} a * @api public */ exports.merge = function(a, b){ for (var key in b) { if (has.call(b, key)) { a[key] = b[key]; } } return a; }; /** * Return length of `obj`. * * @param {Object} obj * @return {Number} * @api public */ exports.length = function(obj){ return exports.keys(obj).length; }; /** * Check if `obj` is empty. * * @param {Object} obj * @return {Boolean} * @api public */ exports.isEmpty = function(obj){ return 0 == exports.length(obj); }; }, {}], 175: [function(require, module, exports) { module.exports = function canonical () { var tags = document.getElementsByTagName('link'); for (var i = 0, tag; tag = tags[i]; i++) { if ('canonical' == tag.getAttribute('rel')) return tag.getAttribute('href'); } }; }, {}], 176: [function(require, module, exports) { /** * Parse the given `url`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(url){ var a = document.createElement('a'); a.href = url; return { href: a.href, host: a.host, port: a.port, hash: a.hash, hostname: a.hostname, pathname: a.pathname, protocol: a.protocol, search: a.search, query: a.search.slice(1) } }; /** * Check if `url` is absolute. * * @param {String} url * @return {Boolean} * @api public */ exports.isAbsolute = function(url){ if (0 == url.indexOf('//')) return true; if (~url.indexOf('://')) return true; return false; }; /** * Check if `url` is relative. * * @param {String} url * @return {Boolean} * @api public */ exports.isRelative = function(url){ return ! exports.isAbsolute(url); }; /** * Check if `url` is cross domain. * * @param {String} url * @return {Boolean} * @api public */ exports.isCrossDomain = function(url){ url = exports.parse(url); return url.hostname != location.hostname || url.port != location.port || url.protocol != location.protocol; }; }, {}], 36: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('dataLayer', { wrap: false }); var integration = require('analytics.js-integration'); /** * Expose `GTM`. */ var GTM = module.exports = integration('Google Tag Manager') .assumesPageview() .global('dataLayer') .global('google_tag_manager') .option('containerId', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//www.googletagmanager.com/gtm.js?id={{ containerId }}&l=dataLayer">'); /** * Initialize. * * https://developers.google.com/tag-manager * * @param {Object} page */ GTM.prototype.initialize = function(){ push({ 'gtm.start': +new Date, event: 'gtm.js' }); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ GTM.prototype.loaded = function(){ return !! (window.dataLayer && [].push != window.dataLayer.push); }; /** * Page. * * @param {Page} page * @api public */ GTM.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); var opts = this.options; var track; // all if (opts.trackAllPages) { this.track(page.track()); } // categorized if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Track. * * https://developers.google.com/tag-manager/devguide#events * * @param {Track} track * @api public */ GTM.prototype.track = function(track){ var props = track.properties(); props.event = track.event(); push(props); }; }, {"global-queue":167,"analytics.js-integration":83}], 37: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var Identify = require('facade').Identify; var Track = require('facade').Track; var callback = require('callback'); var load = require('load-script'); var onBody = require('on-body'); var each = require('each'); /** * Expose `GoSquared` integration. */ var GoSquared = module.exports = integration('GoSquared') .assumesPageview() .global('_gs') .option('siteToken', '') .option('anonymizeIP', false) .option('cookieDomain', null) .option('useCookies', true) .option('trackHash', false) .option('trackLocal', false) .option('trackParams', true) .tag('<script src="//d1l6p2sc9645hc.cloudfront.net/tracker.js">'); /** * Initialize. * * https://www.gosquared.com/developer/tracker * Options: https://www.gosquared.com/developer/tracker/configuration * * @param {Object} page */ GoSquared.prototype.initialize = function(page){ var self = this; var options = this.options; var user = this.analytics.user(); push(options.siteToken); each(options, function(name, value){ if ('siteToken' == name) return; if (null == value) return; push('set', name, value); }); self.identify(new Identify({ traits: user.traits(), userId: user.id() })); self.load(this.ready); }; /** * Loaded? (checks if the tracker version is set) * * @return {Boolean} */ GoSquared.prototype.loaded = function(){ return !! (window._gs && window._gs.v); }; /** * Page. * * https://www.gosquared.com/developer/tracker/pageviews * * @param {Page} page */ GoSquared.prototype.page = function(page){ var props = page.properties(); var name = page.fullName(); push('track', props.path, name || props.title) }; /** * Identify. * * https://www.gosquared.com/developer/tracker/tagging * * @param {Identify} identify */ GoSquared.prototype.identify = function(identify){ var traits = identify.traits({ userId: 'userID' }); var username = identify.username(); var email = identify.email(); var id = identify.userId(); if (id) push('set', 'visitorID', id); var name = email || username || id; if (name) push('set', 'visitorName', name); push('set', 'visitor', traits); }; /** * Track. * * https://www.gosquared.com/developer/tracker/events * * @param {Track} track */ GoSquared.prototype.track = function(track){ push('event', track.event(), track.properties()); }; /** * Checked out. * * @param {Track} track * @api private */ GoSquared.prototype.completedOrder = function(track){ var products = track.products(); var items = []; each(products, function(product){ var track = new Track({ properties: product }); items.push({ category: track.category(), quantity: track.quantity(), price: track.price(), name: track.name(), }); }) push('transaction', track.orderId(), { revenue: track.total(), track: true }, items); }; /** * Push to `_gs.q`. * * @param {...} args * @api private */ function push(){ var _gs = window._gs = window._gs || function(){ (_gs.q = _gs.q || []).push(arguments); }; _gs.apply(null, arguments); } }, {"analytics.js-integration":83,"facade":124,"callback":88,"load-script":120,"on-body":121,"each":4}], 38: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var alias = require('alias'); /** * Expose `Heap` integration. */ var Heap = module.exports = integration('Heap') .assumesPageview() .global('heap') .global('_heapid') .option('apiKey', '') .tag('<script src="//d36lvucg9kzous.cloudfront.net">'); /** * Initialize. * * https://heapanalytics.com/docs#installWeb * * @param {Object} page */ Heap.prototype.initialize = function(page){ window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)));};},e=["identify","track"];for (var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f]);}; window.heap.load(this.options.apiKey); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Heap.prototype.loaded = function(){ return (window.heap && window.heap.appid); }; /** * Identify. * * https://heapanalytics.com/docs#identify * * @param {Identify} identify */ Heap.prototype.identify = function(identify){ var traits = identify.traits(); var username = identify.username(); var id = identify.userId(); var handle = username || id; if (handle) traits.handle = handle; delete traits.username; window.heap.identify(traits); }; /** * Track. * * https://heapanalytics.com/docs#track * * @param {Track} track */ Heap.prototype.track = function(track){ window.heap.track(track.event(), track.properties()); }; }, {"analytics.js-integration":83,"alias":172}], 39: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `hellobar.com` integration. */ var Hellobar = module.exports = integration('Hello Bar') .assumesPageview() .global('_hbq') .option('apiKey', '') .tag('<script src="//s3.amazonaws.com/scripts.hellobar.com/{{ apiKey }}.js">'); /** * Initialize. * * https://s3.amazonaws.com/scripts.hellobar.com/bb900665a3090a79ee1db98c3af21ea174bbc09f.js * * @param {Object} page */ Hellobar.prototype.initialize = function(page){ window._hbq = window._hbq || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Hellobar.prototype.loaded = function(){ return !! (window._hbq && window._hbq.push !== Array.prototype.push); }; }, {"analytics.js-integration":83}], 40: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var is = require('is'); /** * Expose `HitTail` integration. */ var HitTail = module.exports = integration('HitTail') .assumesPageview() .global('htk') .option('siteId', '') .tag('<script src="//{{ siteId }}.hittail.com/mlt.js">'); /** * Initialize. * * @param {Object} page */ HitTail.prototype.initialize = function(page){ this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ HitTail.prototype.loaded = function(){ return is.fn(window.htk); }; }, {"analytics.js-integration":83,"is":86}], 41: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `hublo.com` integration. */ var Hublo = module.exports = integration('Hublo') .assumesPageview() .global('_hublo_') .option('apiKey', null) .tag('<script src="//cdn.hublo.co/{{ apiKey }}.js">'); /** * Initialize. * * https://cdn.hublo.co/5353a2e62b26c1277b000004.js * * @param {Object} page */ Hublo.prototype.initialize = function(page){ this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Hublo.prototype.loaded = function(){ return !! (window._hublo_ && typeof window._hublo_.setup === 'function'); }; }, {"analytics.js-integration":83}], 42: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_hsq'); var convert = require('convert-dates'); /** * Expose `HubSpot` integration. */ var HubSpot = module.exports = integration('HubSpot') .assumesPageview() .global('_hsq') .option('portalId', null) .tag('<script id="hs-analytics" src="https://js.hs-analytics.net/analytics/{{ cache }}/{{ portalId }}.js">'); /** * Initialize. * * @param {Object} page */ HubSpot.prototype.initialize = function(page){ window._hsq = []; var cache = Math.ceil(new Date() / 300000) * 300000; this.load({ cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ HubSpot.prototype.loaded = function(){ return !! (window._hsq && window._hsq.push !== Array.prototype.push); }; /** * Page. * * @param {String} category (optional) * @param {String} name (optional) * @param {Object} properties (optional) * @param {Object} options (optional) */ HubSpot.prototype.page = function(page){ push('_trackPageview'); }; /** * Identify. * * @param {Identify} identify */ HubSpot.prototype.identify = function(identify){ if (!identify.email()) return; var traits = identify.traits(); traits = convertDates(traits); push('identify', traits); }; /** * Track. * * @param {Track} track */ HubSpot.prototype.track = function(track){ var props = track.properties(); props = convertDates(props); push('trackEvent', track.event(), props); }; /** * Convert all the dates in the HubSpot properties to millisecond times * * @param {Object} properties */ function convertDates(properties){ return convert(properties, function(date){ return date.getTime(); }); } }, {"analytics.js-integration":83,"global-queue":167,"convert-dates":173}], 43: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var alias = require('alias'); /** * Expose `Improvely` integration. */ var Improvely = module.exports = integration('Improvely') .assumesPageview() .global('_improvely') .global('improvely') .option('domain', '') .option('projectId', null) .tag('<script src="//{{ domain }}.iljmp.com/improvely.js">'); /** * Initialize. * * http://www.improvely.com/docs/landing-page-code * * @param {Object} page */ Improvely.prototype.initialize = function(page){ window._improvely = []; window.improvely = { init: function(e, t){ window._improvely.push(["init", e, t]); }, goal: function(e){ window._improvely.push(["goal", e]); }, label: function(e){ window._improvely.push(["label", e]); }}; var domain = this.options.domain; var id = this.options.projectId; window.improvely.init(domain, id); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Improvely.prototype.loaded = function(){ return !! (window.improvely && window.improvely.identify); }; /** * Identify. * * http://www.improvely.com/docs/labeling-visitors * * @param {Identify} identify */ Improvely.prototype.identify = function(identify){ var id = identify.userId(); if (id) window.improvely.label(id); }; /** * Track. * * http://www.improvely.com/docs/conversion-code * * @param {Track} track */ Improvely.prototype.track = function(track){ var props = track.properties({ revenue: 'amount' }); props.type = track.event(); window.improvely.goal(props); }; }, {"analytics.js-integration":83,"alias":172}], 44: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_iva'); var Track = require('facade').Track; var is = require('is'); /** * HOP. */ var has = Object.prototype.hasOwnProperty; /** * Expose `InsideVault` integration. */ var InsideVault = module.exports = integration('InsideVault') .global('_iva') .option('clientId', '') .option('domain', '') .tag('<script src="//analytics.staticiv.com/iva.js">') .mapping('events'); /** * Initialize. * * @param page */ InsideVault.prototype.initialize = function(page){ var domain = this.options.domain; window._iva = window._iva || []; push('setClientId', this.options.clientId); if (domain) push('setDomain', domain); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ InsideVault.prototype.loaded = function(){ return !! (window._iva && window._iva.push !== Array.prototype.push); }; /** * Page. * * @param {Page} page */ InsideVault.prototype.page = function(page){ // they want every landing page to send a "click" event. push('trackEvent', 'click'); }; /** * Track. * * Tracks everything except 'sale' events. * * @param {Track} track */ InsideVault.prototype.track = function(track){ var user = this.analytics.user(); var events = this.options.events; var event = track.event(); var value = track.revenue() || track.value() || 0; var eventId = track.orderId() || user.id() || ''; if (!has.call(events, event)) return; event = events[event]; // 'sale' is a special event that will be routed to a table that is deprecated on InsideVault's end. // They don't want a generic 'sale' event to go to their deprecated table. if (event != 'sale') { push('trackEvent', event, value, eventId); } }; }, {"analytics.js-integration":83,"global-queue":167,"facade":124,"is":86}], 45: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('__insp'); var alias = require('alias'); var clone = require('clone'); /** * Expose `Inspectlet` integration. */ var Inspectlet = module.exports = integration('Inspectlet') .assumesPageview() .global('__insp') .global('__insp_') .option('wid', '') .tag('<script src="//www.inspectlet.com/inspectlet.js">'); /** * Initialize. * * https://www.inspectlet.com/dashboard/embedcode/1492461759/initial * * @param {Object} page */ Inspectlet.prototype.initialize = function(page){ push('wid', this.options.wid); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Inspectlet.prototype.loaded = function(){ return !! window.__insp_; }; /** * Identify. * * http://www.inspectlet.com/docs#tagging * * @param {Identify} identify */ Inspectlet.prototype.identify = function (identify) { var traits = identify.traits({ id: 'userid' }); push('tagSession', traits); }; /** * Track. * * http://www.inspectlet.com/docs/tags * * @param {Track} track */ Inspectlet.prototype.track = function(track){ push('tagSession', track.event()); }; }, {"analytics.js-integration":83,"global-queue":167,"alias":172,"clone":171}], 46: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var convertDates = require('convert-dates'); var defaults = require('defaults'); var isEmail = require('is-email'); var load = require('load-script'); var empty = require('is-empty'); var alias = require('alias'); var each = require('each'); var when = require('when'); var is = require('is'); /** * Expose `Intercom` integration. */ var Intercom = module.exports = integration('Intercom') .assumesPageview() .global('Intercom') .option('activator', '#IntercomDefaultWidget') .option('appId', '') .option('inbox', false) .tag('<script src="https://static.intercomcdn.com/intercom.v1.js">'); /** * Initialize. * * http://docs.intercom.io/ * http://docs.intercom.io/#IntercomJS * * @param {Object} page */ Intercom.prototype.initialize = function(page){ var self = this; this.load(function(){ when(function(){ return self.loaded(); }, self.ready); }); }; /** * Loaded? * * @return {Boolean} */ Intercom.prototype.loaded = function(){ return is.fn(window.Intercom); }; /** * Page. * * @param {Page} page */ Intercom.prototype.page = function(page){ window.Intercom('update'); }; /** * Identify. * * http://docs.intercom.io/#IntercomJS * * @param {Identify} identify */ Intercom.prototype.identify = function(identify){ var traits = identify.traits({ userId: 'user_id' }); var activator = this.options.activator; var opts = identify.options(this.name); var companyCreated = identify.companyCreated(); var created = identify.created(); var email = identify.email(); var name = identify.name(); var id = identify.userId(); var group = this.analytics.group(); if (!id && !traits.email) return; // one is required traits.app_id = this.options.appId; // intercom requires `company` to be an object. default it with group traits // so that we guarantee an `id` is there, since they require it if (null != traits.company && !is.object(traits.company)) delete traits.company; if (traits.company) defaults(traits.company, group.traits()); // name if (name) traits.name = name; // handle dates if (traits.company && companyCreated) traits.company.created = companyCreated; if (created) traits.created = created; // convert dates traits = convertDates(traits, formatDate); traits = alias(traits, { created: 'created_at'}); if (traits.company) traits.company = alias(traits.company, { created: 'created_at' }); // handle options if (opts.increments) traits.increments = opts.increments; if (opts.userHash) traits.user_hash = opts.userHash; if (opts.user_hash) traits.user_hash = opts.user_hash; // Intercom, will force the widget to appear // if the selector is #IntercomDefaultWidget // so no need to check inbox, just need to check // that the selector isn't #IntercomDefaultWidget. if ('#IntercomDefaultWidget' != activator) { traits.widget = { activator: activator }; } var method = this._id !== id ? 'boot': 'update'; this._id = id; // cache for next time window.Intercom(method, traits); }; /** * Group. * * @param {Group} group */ Intercom.prototype.group = function(group){ var props = group.properties(); var id = group.groupId(); if (id) props.id = id; window.Intercom('update', { company: props }); }; /** * Track. * * @param {Track} track */ Intercom.prototype.track = function(track){ window.Intercom('trackEvent', track.event(), track.properties()); }; /** * Format a date to Intercom's liking. * * @param {Date} date * @return {Number} */ function formatDate(date) { return Math.floor(date / 1000); } }, {"analytics.js-integration":83,"convert-dates":173,"defaults":166,"is-email":162,"load-script":120,"is-empty":118,"alias":172,"each":4,"when":123,"is":86}], 47: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `Keen IO` integration. */ var Keen = module.exports = integration('Keen IO') .global('Keen') .option('projectId', '') .option('readKey', '') .option('writeKey', '') .option('ipAddon', false) .option('uaAddon', false) .option('urlAddon', false) .option('referrerAddon', false) .option('trackNamedPages', true) .option('trackAllPages', false) .option('trackCategorizedPages', true) .tag('<script src="//d26b395fwzu5fz.cloudfront.net/3.0.7/{{ lib }}.min.js">'); /** * Initialize. * * https://keen.io/docs/ */ Keen.prototype.initialize = function(){ var options = this.options; !function(a,b){if(void 0===b[a]){b["_"+a]={},b[a]=function(c){b["_"+a].clients=b["_"+a].clients||{},b["_"+a].clients[c.projectId]=this,this._config=c},b[a].ready=function(c){b["_"+a].ready=b["_"+a].ready||[],b["_"+a].ready.push(c)};for(var c=["addEvent","setGlobalProperties","trackExternalLink","on"],d=0;d<c.length;d++){var e=c[d],f=function(a){return function(){return this["_"+a]=this["_"+a]||[],this["_"+a].push(arguments),this}};b[a].prototype[e]=f(e)}}}("Keen",window); this.client = new window.Keen({ projectId: options.projectId, writeKey: options.writeKey, readKey: options.readKey }); // if you have a read-key, then load the full keen library var lib = this.options.readKey ? 'keen' : 'keen-tracker'; this.load({ lib: lib }, this.ready); }; /** * Loaded? * * @return {Boolean} */ Keen.prototype.loaded = function(){ return !!(window.Keen && window.Keen.prototype.configure); }; /** * Page. * * @param {Page} page */ Keen.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Identify. * * TODO: migrate from old `userId` to simpler `id` * https://keen.io/docs/data-collection/data-enrichment/#add-ons * * Set up the Keen addons object. These must be specifically * enabled by the settings in order to include the plugins, or else * Keen will reject the request. * * @param {Identify} identify */ Keen.prototype.identify = function(identify){ var traits = identify.traits(); var id = identify.userId(); var user = {}; var options = this.options; if (id) user.userId = id; if (traits) user.traits = traits; var props = { user: user }; var addons = []; if (options.ipAddon) { addons.push({ name: 'keen:ip_to_geo', input: { ip: 'ip_address' }, output: 'ip_geo_info' }); props.ip_address = '${keen.ip}'; } if (options.uaAddon) { addons.push({ name: 'keen:ua_parser', input: { ua_string: 'user_agent' }, output: 'parsed_user_agent' }); props.user_agent = '${keen.user_agent}'; } if (options.urlAddon) { addons.push({ name: 'keen:url_parser', input: { url: 'page_url' }, output: 'parsed_page_url' }); props.page_url = document.location.href; } if (options.referrerAddon) { addons.push({ name: 'keen:referrer_parser', input: { referrer_url: 'referrer_url', page_url: 'page_url' }, output: 'referrer_info' }); props.referrer_url = document.referrer; props.page_url = document.location.href; } props.keen = { timestamp: identify.timestamp(), addons: addons }; this.client.setGlobalProperties(function(){ return props; }); }; /** * Track. * * @param {Track} track */ Keen.prototype.track = function(track){ this.client.addEvent(track.event(), track.properties()); }; }, {"analytics.js-integration":83}], 48: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var indexof = require('indexof'); var is = require('is'); /** * Expose `Kenshoo` integration. */ var Kenshoo = module.exports = integration('Kenshoo') .global('k_trackevent') .option('cid', '') .option('subdomain', '') .option('events', []) .tag('<script src="//{{ subdomain }}.xg4ken.com/media/getpx.php?cid={{ cid }}">'); /** * Initialize. * * See https://gist.github.com/justinboyle/7875832 * * @param {Object} page */ Kenshoo.prototype.initialize = function(page){ this.load(this.ready); }; /** * Loaded? (checks if the tracking function is set) * * @return {Boolean} */ Kenshoo.prototype.loaded = function(){ return is.fn(window.k_trackevent); }; /** * Track. * * Only tracks events if they are listed in the events array option. * We've asked for docs a few times but no go :/ * * https://github.com/jorgegorka/the_tracker/blob/master/lib/the_tracker/trackers/kenshoo.rb * * @param {Track} event */ Kenshoo.prototype.track = function(track){ var events = this.options.events; var traits = track.traits(); var event = track.event(); var revenue = track.revenue() || 0; if (!~indexof(events, event)) return; var params = [ 'id=' + this.options.cid, 'type=conv', 'val=' + revenue, 'orderId=' + track.orderId(), 'promoCode=' + track.coupon(), 'valueCurrency=' + track.currency(), // Live tracking fields. Ignored for now (until we get documentation). 'GCID=', 'kw=', 'product=' ]; window.k_trackevent(params, this.options.subdomain); }; }, {"analytics.js-integration":83,"indexof":109,"is":86}], 49: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_kmq'); var Track = require('facade').Track; var alias = require('alias'); var Batch = require('batch'); var each = require('each'); var is = require('is'); /** * Expose `KISSmetrics` integration. */ var KISSmetrics = module.exports = integration('KISSmetrics') .assumesPageview() .global('_kmq') .global('KM') .global('_kmil') .option('apiKey', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .option('prefixProperties', true) .tag('useless', '<script src="//i.kissmetrics.com/i.js">') .tag('library', '<script src="//doug1izaerwt3.cloudfront.net/{{ apiKey }}.1.js">'); /** * Check if browser is mobile, for kissmetrics. * * http://support.kissmetrics.com/how-tos/browser-detection.html#mobile-vs-non-mobile */ exports.isMobile = navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone|iPod/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/Opera Mini/i) || navigator.userAgent.match(/IEMobile/i); /** * Initialize. * * http://support.kissmetrics.com/apis/javascript * * @param {Object} page */ KISSmetrics.prototype.initialize = function(page){ var self = this; window._kmq = []; if (exports.isMobile) push('set', { 'Mobile Session': 'Yes' }); var batch = new Batch(); batch.push(function(done){ self.load('useless', done); }) // :) batch.push(function(done){ self.load('library', done); }) batch.end(function(){ self.trackPage(page); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ KISSmetrics.prototype.loaded = function(){ return is.object(window.KM); }; /** * Page. * * @param {Page} page */ KISSmetrics.prototype.page = function(page){ if (!window.KM_SKIP_PAGE_VIEW) window.KM.pageView(); this.trackPage(page); }; /** * Track page. * * @param {Page} page */ KISSmetrics.prototype.trackPage = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Identify. * * @param {Identify} identify */ KISSmetrics.prototype.identify = function(identify){ var traits = identify.traits(); var id = identify.userId(); if (id) push('identify', id); if (traits) push('set', traits); }; /** * Track. * * @param {Track} track */ KISSmetrics.prototype.track = function(track){ var mapping = { revenue: 'Billing Amount' }; var event = track.event(); var properties = track.properties(mapping); if (this.options.prefixProperties) properties = prefix(event, properties); push('record', event, properties); }; /** * Alias. * * @param {Alias} to */ KISSmetrics.prototype.alias = function(alias){ push('alias', alias.to(), alias.from()); }; /** * Completed order. * * @param {Track} track * @api private */ KISSmetrics.prototype.completedOrder = function(track){ var products = track.products(); var event = track.event(); // transaction push('record', event, prefix(event, track.properties())); // items window._kmq.push(function(){ var km = window.KM; each(products, function(product, i){ var temp = new Track({ event: event, properties: product }); var item = prefix(event, product); item._t = km.ts() + i; item._d = 1; km.set(item); }); }); }; /** * Prefix properties with the event name. * * @param {String} event * @param {Object} properties * @return {Object} prefixed * @api private */ function prefix(event, properties){ var prefixed = {}; each(properties, function(key, val){ if (key === 'Billing Amount') { prefixed[key] = val; } else { prefixed[event + ' - ' + key] = val; } }); return prefixed; } }, {"analytics.js-integration":83,"global-queue":167,"facade":124,"alias":172,"batch":177,"each":4,"is":86}], 177: [function(require, module, exports) { /** * Module dependencies. */ try { var EventEmitter = require('events').EventEmitter; } catch (err) { var Emitter = require('emitter'); } /** * Noop. */ function noop(){} /** * Expose `Batch`. */ module.exports = Batch; /** * Create a new Batch. */ function Batch() { if (!(this instanceof Batch)) return new Batch; this.fns = []; this.concurrency(Infinity); this.throws(true); for (var i = 0, len = arguments.length; i < len; ++i) { this.push(arguments[i]); } } /** * Inherit from `EventEmitter.prototype`. */ if (EventEmitter) { Batch.prototype.__proto__ = EventEmitter.prototype; } else { Emitter(Batch.prototype); } /** * Set concurrency to `n`. * * @param {Number} n * @return {Batch} * @api public */ Batch.prototype.concurrency = function(n){ this.n = n; return this; }; /** * Queue a function. * * @param {Function} fn * @return {Batch} * @api public */ Batch.prototype.push = function(fn){ this.fns.push(fn); return this; }; /** * Set wether Batch will or will not throw up. * * @param {Boolean} throws * @return {Batch} * @api public */ Batch.prototype.throws = function(throws) { this.e = !!throws; return this; }; /** * Execute all queued functions in parallel, * executing `cb(err, results)`. * * @param {Function} cb * @return {Batch} * @api public */ Batch.prototype.end = function(cb){ var self = this , total = this.fns.length , pending = total , results = [] , errors = [] , cb = cb || noop , fns = this.fns , max = this.n , throws = this.e , index = 0 , done; // empty if (!fns.length) return cb(null, results); // process function next() { var i = index++; var fn = fns[i]; if (!fn) return; var start = new Date; try { fn(callback); } catch (err) { callback(err); } function callback(err, res){ if (done) return; if (err && throws) return done = true, cb(err); var complete = total - pending + 1; var end = new Date; results[i] = res; errors[i] = err; self.emit('progress', { index: i, value: res, error: err, pending: pending, total: total, complete: complete, percent: complete / total * 100 | 0, start: start, end: end, duration: end - start }); if (--pending) next() else if(!throws) cb(errors, results); else cb(null, results); } } // concurrency for (var i = 0; i < fns.length; i++) { if (i == max) break; next(); } return this; }; }, {"emitter":178}], 178: [function(require, module, exports) { /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; }, {}], 50: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_learnq'); var tick = require('next-tick'); var alias = require('alias'); /** * Trait aliases. */ var aliases = { id: '$id', email: '$email', firstName: '$first_name', lastName: '$last_name', phone: '$phone_number', title: '$title' }; /** * Expose `Klaviyo` integration. */ var Klaviyo = module.exports = integration('Klaviyo') .assumesPageview() .global('_learnq') .option('apiKey', '') .tag('<script src="//a.klaviyo.com/media/js/learnmarklet.js">'); /** * Initialize. * * https://www.klaviyo.com/docs/getting-started * * @param {Object} page */ Klaviyo.prototype.initialize = function(page){ var self = this; push('account', this.options.apiKey); this.load(function(){ tick(self.ready); }); }; /** * Loaded? * * @return {Boolean} */ Klaviyo.prototype.loaded = function(){ return !! (window._learnq && window._learnq.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ Klaviyo.prototype.identify = function(identify){ var traits = identify.traits(aliases); if (!traits.$id && !traits.$email) return; push('identify', traits); }; /** * Group. * * @param {Group} group */ Klaviyo.prototype.group = function(group){ var props = group.properties(); if (!props.name) return; push('identify', { $organization: props.name }); }; /** * Track. * * @param {Track} track */ Klaviyo.prototype.track = function(track){ push('track', track.event(), track.properties({ revenue: '$value' })); }; }, {"analytics.js-integration":83,"global-queue":167,"next-tick":97,"alias":172}], 51: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `LeadLander` integration. */ var LeadLander = module.exports = integration('LeadLander') .assumesPageview() .global('llactid') .global('trackalyzer') .option('accountId', null) .tag('<script src="http://t6.trackalyzer.com/trackalyze-nodoc.js">'); /** * Initialize. * * @param {Object} page */ LeadLander.prototype.initialize = function(page){ window.llactid = this.options.accountId; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ LeadLander.prototype.loaded = function(){ return !! window.trackalyzer; }; }, {"analytics.js-integration":83}], 52: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var clone = require('clone'); var each = require('each'); var Identify = require('facade').Identify; var when = require('when'); /** * Expose `LiveChat` integration. */ var LiveChat = module.exports = integration('LiveChat') .assumesPageview() .global('__lc') .global('__lc_inited') .global('LC_API') .global('LC_Invite') .option('group', 0) .option('license', '') .tag('<script src="//cdn.livechatinc.com/tracking.js">'); /** * Initialize. * * http://www.livechatinc.com/api/javascript-api * * @param {Object} page */ LiveChat.prototype.initialize = function(page){ var self = this; var user = this.analytics.user(); var identify = new Identify({ userId: user.id(), traits: user.traits() }); window.__lc = clone(this.options); window.__lc.visitor = { name: identify.name(), email: identify.email() }; this.load(function(){ when(function(){ return self.loaded(); }, self.ready); }); }; /** * Loaded? * * @return {Boolean} */ LiveChat.prototype.loaded = function(){ return !!(window.LC_API && window.LC_Invite); }; /** * Identify. * * @param {Identify} identify */ LiveChat.prototype.identify = function(identify){ var traits = identify.traits({ userId: 'User ID' }); window.LC_API.set_custom_variables(convert(traits)); }; /** * Convert a traits object into the format LiveChat requires. * * @param {Object} traits * @return {Array} */ function convert(traits){ var arr = []; each(traits, function(key, value){ arr.push({ name: key, value: value }); }); return arr; } }, {"analytics.js-integration":83,"clone":171,"each":4,"facade":124,"when":123}], 53: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var Identify = require('facade').Identify; var useHttps = require('use-https'); /** * Expose `LuckyOrange` integration. */ var LuckyOrange = module.exports = integration('Lucky Orange') .assumesPageview() .global('_loq') .global('__wtw_watcher_added') .global('__wtw_lucky_site_id') .global('__wtw_lucky_is_segment_io') .global('__wtw_custom_user_data') .option('siteId', null) .tag('http', '<script src="http://www.luckyorange.com/w.js?{{ cache }}">') .tag('https', '<script src="https://ssl.luckyorange.com/w.js?{{ cache }}">'); /** * Initialize. * * @param {Object} page */ LuckyOrange.prototype.initialize = function(page){ var user = this.analytics.user(); window._loq || (window._loq = []); window.__wtw_lucky_site_id = this.options.siteId; this.identify(new Identify({ traits: user.traits(), userId: user.id() })); var cache = Math.floor(new Date().getTime() / 60000); var name = useHttps() ? 'https' : 'http'; this.load(name, { cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ LuckyOrange.prototype.loaded = function(){ return !! window.__wtw_watcher_added; }; /** * Identify. * * @param {Identify} identify */ LuckyOrange.prototype.identify = function(identify){ var traits = identify.traits(); var email = identify.email(); var name = identify.name(); if (name) traits.name = name; if (email) traits.email = email; window.__wtw_custom_user_data = traits; }; }, {"analytics.js-integration":83,"facade":124,"use-https":85}], 54: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var alias = require('alias'); /** * Expose `Lytics` integration. */ var Lytics = module.exports = integration('Lytics') .global('jstag') .option('cid', '') .option('cookie', 'seerid') .option('delay', 2000) .option('sessionTimeout', 1800) .option('url', '//c.lytics.io') .tag('<script src="//c.lytics.io/static/io.min.js">'); /** * Options aliases. */ var aliases = { sessionTimeout: 'sessecs' }; /** * Initialize. * * http://admin.lytics.io/doc#jstag * * @param {Object} page */ Lytics.prototype.initialize = function(page){ var options = alias(this.options, aliases); window.jstag = (function(){var t = { _q: [], _c: options, ts: (new Date()).getTime() }; t.send = function(){this._q.push(['ready', 'send', Array.prototype.slice.call(arguments)]); return this; }; return t; })(); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Lytics.prototype.loaded = function(){ return !! (window.jstag && window.jstag.bind); }; /** * Page. * * @param {Page} page */ Lytics.prototype.page = function(page){ window.jstag.send(page.properties()); }; /** * Idenfity. * * @param {Identify} identify */ Lytics.prototype.identify = function(identify){ var traits = identify.traits({ userId: '_uid' }); window.jstag.send(traits); }; /** * Track. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) */ Lytics.prototype.track = function(track){ var props = track.properties(); props._e = track.event(); window.jstag.send(props); }; }, {"analytics.js-integration":83,"alias":172}], 55: [function(require, module, exports) { /** * Module dependencies. */ var alias = require('alias'); var clone = require('clone'); var dates = require('convert-dates'); var integration = require('analytics.js-integration'); var is = require('is'); var iso = require('to-iso-string'); var indexof = require('indexof'); var del = require('obj-case').del; var some = require('some'); /** * Expose `Mixpanel` integration. */ var Mixpanel = module.exports = integration('Mixpanel') .global('mixpanel') .option('increments', []) .option('cookieName', '') .option('nameTag', true) .option('pageview', false) .option('people', false) .option('token', '') .option('trackAllPages', false) .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//cdn.mxpnl.com/libs/mixpanel-2.2.min.js">'); /** * Options aliases. */ var optionsAliases = { cookieName: 'cookie_name' }; /** * Initialize. * * https://mixpanel.com/help/reference/javascript#installing * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.init */ Mixpanel.prototype.initialize = function(){ (function(c, a){window.mixpanel = a; var b, d, h, e; a._i = []; a.init = function(b, c, f){function d(a, b){var c = b.split('.'); 2 == c.length && (a = a[c[0]], b = c[1]); a[b] = function(){a.push([b].concat(Array.prototype.slice.call(arguments, 0))); }; } var g = a; 'undefined' !== typeof f ? g = a[f] = [] : f = 'mixpanel'; g.people = g.people || []; h = ['disable', 'track', 'track_pageview', 'track_links', 'track_forms', 'register', 'register_once', 'unregister', 'identify', 'alias', 'name_tag', 'set_config', 'people.set', 'people.increment', 'people.track_charge', 'people.append']; for (e = 0; e < h.length; e++) d(g, h[e]); a._i.push([b, c, f]); }; a.__SV = 1.2; })(document, window.mixpanel || []); this.options.increments = lowercase(this.options.increments); var options = alias(this.options, optionsAliases); window.mixpanel.init(options.token, options); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Mixpanel.prototype.loaded = function(){ return !! (window.mixpanel && window.mixpanel.config); }; /** * Page. * * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.track_pageview * * @param {String} category (optional) * @param {String} name (optional) * @param {Object} properties (optional) * @param {Object} options (optional) */ Mixpanel.prototype.page = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Trait aliases. */ var traitAliases = { created: '$created', email: '$email', firstName: '$first_name', lastName: '$last_name', lastSeen: '$last_seen', name: '$name', username: '$username', phone: '$phone' }; /** * Identify. * * https://mixpanel.com/help/reference/javascript#super-properties * https://mixpanel.com/help/reference/javascript#user-identity * https://mixpanel.com/help/reference/javascript#storing-user-profiles * * @param {Identify} identify */ Mixpanel.prototype.identify = function(identify){ var username = identify.username(); var email = identify.email(); var id = identify.userId(); // id if (id) window.mixpanel.identify(id); // name tag var nametag = email || username || id; if (nametag) window.mixpanel.name_tag(nametag); // traits var traits = identify.traits(traitAliases); if (traits.$created) del(traits, 'createdAt'); window.mixpanel.register(dates(traits, iso)); if (this.options.people) window.mixpanel.people.set(traits); }; /** * Track. * * https://mixpanel.com/help/reference/javascript#sending-events * https://mixpanel.com/help/reference/javascript#tracking-revenue * * @param {Track} track */ Mixpanel.prototype.track = function(track){ var increments = this.options.increments; var increment = track.event().toLowerCase(); var people = this.options.people; var props = track.properties(); var revenue = track.revenue(); // delete mixpanel's reserved properties, so they don't conflict delete props.distinct_id; delete props.ip; delete props.mp_name_tag; delete props.mp_note; delete props.token; // convert arrays of objects to length, since mixpanel doesn't support object arrays for (var key in props) { var val = props[key]; if (is.array(val) && some(val, is.object)) props[key] = val.length; } // increment properties in mixpanel people if (people && ~indexof(increments, increment)) { window.mixpanel.people.increment(track.event()); window.mixpanel.people.set('Last ' + track.event(), new Date); } // track the event props = dates(props, iso); window.mixpanel.track(track.event(), props); // track revenue specifically if (revenue && people) { window.mixpanel.people.track_charge(revenue); } }; /** * Alias. * * https://mixpanel.com/help/reference/javascript#user-identity * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.alias * * @param {Alias} alias */ Mixpanel.prototype.alias = function(alias){ var mp = window.mixpanel; var to = alias.to(); if (mp.get_distinct_id && mp.get_distinct_id() === to) return; // HACK: internal mixpanel API to ensure we don't overwrite if (mp.get_property && mp.get_property('$people_distinct_id') === to) return; // although undocumented, mixpanel takes an optional original id mp.alias(to, alias.from()); }; /** * Lowercase the given `arr`. * * @param {Array} arr * @return {Array} * @api private */ function lowercase(arr){ var ret = new Array(arr.length); for (var i = 0; i < arr.length; ++i) { ret[i] = String(arr[i]).toLowerCase(); } return ret; } }, {"alias":172,"clone":171,"convert-dates":173,"analytics.js-integration":83,"is":86,"to-iso-string":170,"indexof":109,"obj-case":138,"some":179}], 179: [function(require, module, exports) { /** * some */ var some = [].some; /** * test whether some elements in * the array pass the test implemented * by `fn`. * * example: * * some([1, 'foo', 'bar'], function (el, i) { * return 'string' == typeof el; * }); * // > true * * @param {Array} arr * @param {Function} fn * @return {bool} */ module.exports = function (arr, fn) { if (some) return some.call(arr, fn); for (var i = 0, l = arr.length; i < l; ++i) { if (fn(arr[i], i)) return true; } return false; }; }, {}], 56: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var bind = require('bind'); var when = require('when'); var is = require('is'); /** * Expose `Mojn` */ var Mojn = module.exports = integration('Mojn') .option('customerCode', '') .global('_mojnTrack') .tag('<script src="https://track.idtargeting.com/{{ customerCode }}/track.js">'); /** * Initialize. * * @param {Object} page */ Mojn.prototype.initialize = function(){ window._mojnTrack = window._mojnTrack || []; window._mojnTrack.push({ cid: this.options.customerCode }); var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, ready); }); }; /** * Loaded? * * @return {Boolean} */ Mojn.prototype.loaded = function(){ return is.object(window._mojnTrack); }; /** * Identify. * * @param {Identify} identify */ Mojn.prototype.identify = function(identify){ var email = identify.email(); if (!email) return; var img = new Image(); img.src = '//matcher.idtargeting.com/analytics.gif?cid=' + this.options.customerCode + '&_mjnctid='+email; img.width = 1; img.height = 1; return img; }; /** * Track. * * @param {Track} event */ Mojn.prototype.track = function(track){ var properties = track.properties(); var revenue = properties.revenue; var currency = properties.currency || ''; var conv = currency + revenue; if (!revenue) return; window._mojnTrack.push({ conv: conv }); return conv; }; }, {"analytics.js-integration":83,"bind":95,"when":123,"is":86}], 57: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('_mfq'); var integration = require('analytics.js-integration'); var each = require('each'); /** * Expose `Mouseflow`. */ var Mouseflow = module.exports = integration('Mouseflow') .assumesPageview() .global('mouseflow') .global('_mfq') .option('apiKey', '') .option('mouseflowHtmlDelay', 0) .tag('<script src="//cdn.mouseflow.com/projects/{{ apiKey }}.js">'); /** * Initalize. * * @param {Object} page */ Mouseflow.prototype.initialize = function(page){ window.mouseflowHtmlDelay = this.options.mouseflowHtmlDelay; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Mouseflow.prototype.loaded = function(){ return !! window.mouseflow; }; /** * Page. * * http://mouseflow.zendesk.com/entries/22528817-Single-page-websites * * @param {Page} page */ Mouseflow.prototype.page = function(page){ if (!window.mouseflow) return; if ('function' != typeof mouseflow.newPageView) return; mouseflow.newPageView(); }; /** * Identify. * * http://mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging * * @param {Identify} identify */ Mouseflow.prototype.identify = function(identify){ set(identify.traits()); }; /** * Track. * * http://mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging * * @param {Track} track */ Mouseflow.prototype.track = function(track){ var props = track.properties(); props.event = track.event(); set(props); }; /** * Push each key and value in the given `obj` onto the queue. * * @param {Object} obj */ function set(obj){ each(obj, function(key, value){ push('setVariable', key, value); }); } }, {"global-queue":167,"analytics.js-integration":83,"each":4}], 58: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var useHttps = require('use-https'); var each = require('each'); var is = require('is'); /** * Expose `MouseStats` integration. */ var MouseStats = module.exports = integration('MouseStats') .assumesPageview() .global('msaa') .global('MouseStatsVisitorPlaybacks') .option('accountNumber', '') .tag('http', '<script src="http://www2.mousestats.com/js/{{ path }}.js?{{ cache }}">') .tag('https', '<script src="https://ssl.mousestats.com/js/{{ path }}.js?{{ cache }}">'); /** * Initialize. * * http://www.mousestats.com/docs/pages/allpages * * @param {Object} page */ MouseStats.prototype.initialize = function(page){ var number = this.options.accountNumber; var path = number.slice(0,1) + '/' + number.slice(1,2) + '/' + number; var cache = Math.floor(new Date().getTime() / 60000); var name = useHttps() ? 'https' : 'http'; this.load(name, { path: path, cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ MouseStats.prototype.loaded = function(){ return is.array(window.MouseStatsVisitorPlaybacks); }; /** * Identify. * * http://www.mousestats.com/docs/wiki/7/how-to-add-custom-data-to-visitor-playbacks * * @param {Identify} identify */ MouseStats.prototype.identify = function(identify){ each(identify.traits(), function (key, value) { window.MouseStatsVisitorPlaybacks.customVariable(key, value); }); }; }, {"analytics.js-integration":83,"use-https":85,"each":4,"is":86}], 59: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('__nls'); /** * Expose `Navilytics` integration. */ var Navilytics = module.exports = integration('Navilytics') .assumesPageview() .global('__nls') .option('memberId', '') .option('projectId', '') .tag('<script src="//www.navilytics.com/nls.js?mid={{ memberId }}&pid={{ projectId }}">'); /** * Initialize. * * https://www.navilytics.com/member/code_settings * * @param {Object} page */ Navilytics.prototype.initialize = function(page){ window.__nls = window.__nls || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Navilytics.prototype.loaded = function(){ return !! (window.__nls && [].push != window.__nls.push); }; /** * Track. * * https://www.navilytics.com/docs#tags * * @param {Track} track */ Navilytics.prototype.track = function(track){ push('tagRecording', track.event()); }; }, {"analytics.js-integration":83,"global-queue":167}], 60: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var https = require('use-https'); var tick = require('next-tick'); /** * Expose `Olark` integration. */ var Olark = module.exports = integration('Olark') .assumesPageview() .global('olark') .option('identify', true) .option('page', true) .option('siteId', '') .option('groupId', '') .option('track', false); /** * Initialize. * * http://www.olark.com/documentation * https://www.olark.com/documentation/javascript/api.chat.setOperatorGroup * * @param {Facade} page */ Olark.prototype.initialize = function(page){ var self = this; this.load(function(){ tick(self.ready); }); // assign chat to a specific site var groupId = this.options.groupId; if (groupId) api('chat.setOperatorGroup', { group: groupId }); // keep track of the widget's open state api('box.onExpand', function(){ self._open = true; }); api('box.onShrink', function(){ self._open = false; }); }; /** * Loaded? * * @return {Boolean} */ Olark.prototype.loaded = function(){ return !! window.olark; }; /** * Load. * * @param {Function} callback */ Olark.prototype.load = function(callback){ var el = document.getElementById('olark'); window.olark||(function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while (q--) {(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={ 0:+new Date() };a.P=function(u){a.p[u]=new Date()-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return ["<",hd,"></",hd,"><",i,' onl' + 'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if (!m) {return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if (/MSIE[ ]+6/.test(navigator.userAgent)) {b.src="javascript:false"}b.allowTransparency="true";v[j](b);try {b.contentWindow[g].open()}catch (w) {c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try {var t=b.contentWindow[g];t.write(p());t.close()}catch (x) {b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()})({ loader: "static.olark.com/jsclient/loader0.js", name:"olark", methods:["configure","extend","declare","identify"] }); window.olark.identify(this.options.siteId); callback(); }; /** * Page. * * @param {Facade} page */ Olark.prototype.page = function(page){ if (!this.options.page) return; var props = page.properties(); var name = page.fullName(); if (!name && !props.url) return; name = name ? name + ' page' : props.url; this.notify('looking at ' + name); }; /** * Identify. * * @param {Facade} identify */ Olark.prototype.identify = function(identify){ if (!this.options.identify) return; var username = identify.username(); var traits = identify.traits(); var id = identify.userId(); var email = identify.email(); var phone = identify.phone(); var name = identify.name() || identify.firstName(); if (traits) api('visitor.updateCustomFields', traits); if (email) api('visitor.updateEmailAddress', { emailAddress: email }); if (phone) api('visitor.updatePhoneNumber', { phoneNumber: phone }); if (name) api('visitor.updateFullName', { fullName: name }); // figure out best nickname var nickname = name || email || username || id; if (name && email) nickname += ' (' + email + ')'; if (nickname) api('chat.updateVisitorNickname', { snippet: nickname }); }; /** * Track. * * @param {Facade} track */ Olark.prototype.track = function(track){ if (!this.options.track) return; this.notify('visitor triggered "' + track.event() + '"'); }; /** * Send a notification `message` to the operator, only when a chat is active and * when the chat is open. * * @param {String} message */ Olark.prototype.notify = function(message){ if (!this._open) return; // lowercase since olark does message = message.toLowerCase(); api('visitor.getDetails', function(data){ if (!data || !data.isConversing) return; api('chat.sendNotificationToOperator', { body: message }); }); }; /** * Helper for Olark API calls. * * @param {String} action * @param {Object} value */ function api(action, value) { window.olark('api.' + action, value); } }, {"analytics.js-integration":83,"use-https":85,"next-tick":97}], 61: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('optimizely'); var callback = require('callback'); var tick = require('next-tick'); var bind = require('bind'); var each = require('each'); /** * Expose `Optimizely` integration. */ var Optimizely = module.exports = integration('Optimizely') .option('variations', true) .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * Initialize. * * https://www.optimizely.com/docs/api#function-calls */ Optimizely.prototype.initialize = function(){ if (this.options.variations) { var self = this; tick(function(){ self.replay(); }); } this.ready(); }; /** * Track. * * https://www.optimizely.com/docs/api#track-event * * @param {Track} track */ Optimizely.prototype.track = function(track){ var props = track.properties(); if (props.revenue) props.revenue *= 100; push('trackEvent', track.event(), props); }; /** * Page. * * https://www.optimizely.com/docs/api#track-event * * @param {Page} page */ Optimizely.prototype.page = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Replay experiment data as traits to other enabled providers. * * https://www.optimizely.com/docs/api#data-object */ Optimizely.prototype.replay = function(){ if (!window.optimizely) return; // in case the snippet isnt on the page var data = window.optimizely.data; if (!data) return; var experiments = data.experiments; var map = data.state.variationNamesMap; var traits = {}; each(map, function(experimentId, variation){ var experiment = experiments[experimentId].name; traits['Experiment: ' + experiment] = variation; }); this.analytics.identify(traits); }; }, {"analytics.js-integration":83,"global-queue":167,"callback":88,"next-tick":97,"bind":95,"each":4}], 62: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `PerfectAudience` integration. */ var PerfectAudience = module.exports = integration('Perfect Audience') .assumesPageview() .global('_pa') .option('siteId', '') .tag('<script src="//tag.perfectaudience.com/serve/{{ siteId }}.js">'); /** * Initialize. * * https://www.perfectaudience.com/docs#javascript_api_autoopen * * @param {Object} page */ PerfectAudience.prototype.initialize = function(page){ window._pa = window._pa || {}; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ PerfectAudience.prototype.loaded = function(){ return !! (window._pa && window._pa.track); }; /** * Track. * * @param {Track} event */ PerfectAudience.prototype.track = function(track){ window._pa.track(track.event(), track.properties()); }; }, {"analytics.js-integration":83}], 63: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_prum'); var date = require('load-date'); /** * Expose `Pingdom` integration. */ var Pingdom = module.exports = integration('Pingdom') .assumesPageview() .global('_prum') .global('PRUM_EPISODES') .option('id', '') .tag('<script src="//rum-static.pingdom.net/prum.min.js">'); /** * Initialize. * * @param {Object} page */ Pingdom.prototype.initialize = function(page){ window._prum = window._prum || []; push('id', this.options.id); push('mark', 'firstbyte', date.getTime()); var self = this; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Pingdom.prototype.loaded = function(){ return !! (window._prum && window._prum.push !== Array.prototype.push); }; }, {"analytics.js-integration":83,"global-queue":167,"load-date":168}], 64: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_paq'); var each = require('each'); /** * Expose `Piwik` integration. */ var Piwik = module.exports = integration('Piwik') .global('_paq') .option('url', null) .option('siteId', '') .mapping('goals') .tag('<script src="{{ url }}/piwik.js">'); /** * Initialize. * * http://piwik.org/docs/javascript-tracking/#toc-asynchronous-tracking */ Piwik.prototype.initialize = function(){ window._paq = window._paq || []; push('setSiteId', this.options.siteId); push('setTrackerUrl', this.options.url + '/piwik.php'); push('enableLinkTracking'); this.load(this.ready); }; /** * Check if Piwik is loaded */ Piwik.prototype.loaded = function(){ return !! (window._paq && window._paq.push != [].push); }; /** * Page * * @param {Page} page */ Piwik.prototype.page = function(page){ push('trackPageView'); }; /** * Track. * * @param {Track} track */ Piwik.prototype.track = function(track){ var goals = this.goals(track.event()); var revenue = track.revenue() || 0; each(goals, function(goal){ push('trackGoal', goal, revenue); }); }; }, {"analytics.js-integration":83,"global-queue":167,"each":4}], 65: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var convertDates = require('convert-dates'); var push = require('global-queue')('_lnq'); var alias = require('alias'); /** * Expose `Preact` integration. */ var Preact = module.exports = integration('Preact') .assumesPageview() .global('_lnq') .option('projectCode', '') .tag('<script src="//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js">'); /** * Initialize. * * http://www.preact.io/api/javascript * * @param {Object} page */ Preact.prototype.initialize = function(page){ window._lnq = window._lnq || []; push('_setCode', this.options.projectCode); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Preact.prototype.loaded = function(){ return !! (window._lnq && window._lnq.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ Preact.prototype.identify = function(identify){ if (!identify.userId()) return; var traits = identify.traits({ created: 'created_at' }); traits = convertDates(traits, convertDate); push('_setPersonData', { name: identify.name(), email: identify.email(), uid: identify.userId(), properties: traits }); }; /** * Group. * * @param {String} id * @param {Object} properties (optional) * @param {Object} options (optional) */ Preact.prototype.group = function(group){ if (!group.groupId()) return; push('_setAccount', group.traits()); }; /** * Track. * * @param {Track} track */ Preact.prototype.track = function(track){ var props = track.properties(); var revenue = track.revenue(); var event = track.event(); var special = { name: event }; if (revenue) { special.revenue = revenue * 100; delete props.revenue; } if (props.note) { special.note = props.note; delete props.note; } push('_logEvent', special, props); }; /** * Convert a `date` to a format Preact supports. * * @param {Date} date * @return {Number} */ function convertDate(date){ return Math.floor(date / 1000); } }, {"analytics.js-integration":83,"convert-dates":173,"global-queue":167,"alias":172}], 66: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_kiq'); var Facade = require('facade'); var Identify = Facade.Identify; var bind = require('bind'); var when = require('when'); /** * Expose `Qualaroo` integration. */ var Qualaroo = module.exports = integration('Qualaroo') .assumesPageview() .global('_kiq') .option('customerId', '') .option('siteToken', '') .option('track', false) .tag('<script src="//s3.amazonaws.com/ki.js/{{ customerId }}/{{ siteToken }}.js">'); /** * Initialize. * * @param {Object} page */ Qualaroo.prototype.initialize = function(page){ window._kiq = window._kiq || []; var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, ready); }); }; /** * Loaded? * * @return {Boolean} */ Qualaroo.prototype.loaded = function(){ return !! (window._kiq && window._kiq.push !== Array.prototype.push); }; /** * Identify. * * http://help.qualaroo.com/customer/portal/articles/731085-identify-survey-nudge-takers * http://help.qualaroo.com/customer/portal/articles/731091-set-additional-user-properties * * @param {Identify} identify */ Qualaroo.prototype.identify = function(identify){ var traits = identify.traits(); var id = identify.userId(); var email = identify.email(); if (email) id = email; if (id) push('identify', id); if (traits) push('set', traits); }; /** * Track. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) */ Qualaroo.prototype.track = function(track){ if (!this.options.track) return; var event = track.event(); var traits = {}; traits['Triggered: ' + event] = true; this.identify(new Identify({ traits: traits })); }; }, {"analytics.js-integration":83,"global-queue":167,"facade":124,"bind":95,"when":123}], 67: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('_qevents', { wrap: false }); var integration = require('analytics.js-integration'); var useHttps = require('use-https'); /** * Expose `Quantcast` integration. */ var Quantcast = module.exports = integration('Quantcast') .assumesPageview() .global('_qevents') .global('__qc') .option('pCode', null) .option('advertise', false) .tag('http', '<script src="http://edge.quantserve.com/quant.js">') .tag('https', '<script src="https://secure.quantserve.com/quant.js">'); /** * Initialize. * * https://www.quantcast.com/learning-center/guides/using-the-quantcast-asynchronous-tag/ * https://www.quantcast.com/help/cross-platform-audience-measurement-guide/ * * @param {Page} page */ Quantcast.prototype.initialize = function(page){ window._qevents = window._qevents || []; var opts = this.options; var settings = { qacct: opts.pCode }; var user = this.analytics.user(); if (user.id()) settings.uid = user.id(); if (page) { settings.labels = this.labels('page', page.category(), page.name()); } push(settings); var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ Quantcast.prototype.loaded = function(){ return !! window.__qc; }; /** * Page. * * https://cloudup.com/cBRRFAfq6mf * * @param {Page} page */ Quantcast.prototype.page = function(page){ var category = page.category(); var name = page.name(); var settings = { event: 'refresh', labels: this.labels('page', category, name), qacct: this.options.pCode, }; var user = this.analytics.user(); if (user.id()) settings.uid = user.id(); push(settings); }; /** * Identify. * * https://www.quantcast.com/help/cross-platform-audience-measurement-guide/ * * @param {String} id (optional) */ Quantcast.prototype.identify = function(identify){ // edit the initial quantcast settings // TODO: could be done in a cleaner way var id = identify.userId(); if (id) { window._qevents[0] = window._qevents[0] || {}; window._qevents[0].uid = id; } }; /** * Track. * * https://cloudup.com/cBRRFAfq6mf * * @param {Track} track */ Quantcast.prototype.track = function(track){ var name = track.event(); var revenue = track.revenue(); var settings = { event: 'click', labels: this.labels('event', name), qacct: this.options.pCode }; var user = this.analytics.user(); if (null != revenue) settings.revenue = (revenue+''); // convert to string if (user.id()) settings.uid = user.id(); push(settings); }; /** * Completed Order. * * @param {Track} track * @api private */ Quantcast.prototype.completedOrder = function(track){ var name = track.event(); var revenue = track.total(); var labels = this.labels('event', name); var category = track.category(); if (this.options.advertise && category) { labels += ',' + this.labels('pcat', category); } var settings = { event: 'refresh', // the example Quantcast sent has completed order send refresh not click labels: labels, revenue: (revenue+''), // convert to string orderid: track.orderId(), qacct: this.options.pCode }; push(settings); }; /** * Generate quantcast labels. * * Example: * * options.advertise = false; * labels('event', 'my event'); * // => "event.my event" * * options.advertise = true; * labels('event', 'my event'); * // => "_fp.event.my event" * * @param {String} type * @param {String} ... * @return {String} * @api private */ Quantcast.prototype.labels = function(type){ var args = [].slice.call(arguments, 1); var advertise = this.options.advertise; var ret = []; if (advertise && 'page' == type) type = 'event'; if (advertise) type = '_fp.' + type; for (var i = 0; i < args.length; ++i) { if (null == args[i]) continue; var value = String(args[i]); ret.push(value.replace(/,/g, ';')); } ret = advertise ? ret.join(' ') : ret.join('.'); return [type, ret].join('.'); }; }, {"global-queue":167,"analytics.js-integration":83,"use-https":85}], 68: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var extend = require('extend'); var is = require('is'); /** * Expose `Rollbar` integration. */ var RollbarIntegration = module.exports = integration('Rollbar') .global('Rollbar') .option('identify', true) .option('accessToken', '') .option('environment', 'unknown') .option('captureUncaught', true); /** * Initialize. * * @param {Object} page */ RollbarIntegration.prototype.initialize = function(page){ var _rollbarConfig = this.config = { accessToken: this.options.accessToken, captureUncaught: this.options.captureUncaught, payload: { environment: this.options.environment } }; (function(a){function b(b){this.shimId=++g,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0 === a.console.shimId&&(this.logger=a.console.log)}function c(b,c,d){!d[4]&&a._rollbarWrappedError&&(d[4]=a._rollbarWrappedError,a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function d(c){var d=b;return f(function(){if (this.notifier)return this.notifier[c].apply(this.notifier,arguments);var b=this,e="scope"===c;e&&(b=new d(this));var f=Array.prototype.slice.call(arguments,0),g={ shim:b, method:c, args:f, ts:new Date };return a._rollbarShimQueue.push(g),e?b:void 0})}function e(a,b){if (b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b._wrapped||b,c)}}}function f(a,b){return b=b||this.logger,function(){try {return a.apply(this,arguments)} catch (c) {b("Rollbar internal error:",c)}}}var g=0;b.init=function(a,d){var g=d.globalAlias||"Rollbar";if ("object"==typeof a[g])return a[g];a._rollbarShimQueue=[],a._rollbarWrappedError=null,d=d||{};var h=new b;return f(function(){if (h.configure(d),d.captureUncaught){var b=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);c(h,b,a)};var f,i,j=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"];for (f=0;f<j.length;++f)i=j[f],a[i]&&a[i].prototype&&e(h,a[i].prototype)}return a[g]=h,h},h.logger)()},b.prototype.loadFull=function(a,b,c,d,e){var g=f(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=f(function(){var b;if (void 0===a._rollbarPayloadQueue){var c,d,f,g;for (b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for (f=c.args,g=0;g<f.length;++g)if (d=f[g],"function"==typeof d){d(b);break}}e&&e(b)},this.logger);f(function(){c?g():a.addEventListener?a.addEventListener("load",g,!1):a.attachEvent("onload",g)},this.logger)()},b.prototype.wrap=function(b){if ("function"!=typeof b)return b;if (b._isWrap)return b;if (!b._wrapped){b._wrapped=function(){try {return b.apply(this,arguments)} catch (c) {throw a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for (var c in b)b.hasOwnProperty(c)&&(b._wrapped[c]=b[c])}return b._wrapped};for (var h="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),i=0;i<h.length;++i)b.prototype[h[i]]=d(h[i]);var j="//d37gvrvc0wt4s1.cloudfront.net/js/v1.0/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||j,b.init(a,_rollbarConfig)})(window,document); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ RollbarIntegration.prototype.loaded = function(){ return is.object(window.Rollbar) && null == window.Rollbar.shimId; }; /** * Load. * * @param {Function} callback */ RollbarIntegration.prototype.load = function(callback){ window.Rollbar.loadFull(window, document, true, this.config, callback); }; /** * Identify. * * @param {Identify} identify */ RollbarIntegration.prototype.identify = function(identify){ // do stuff with `id` or `traits` if (!this.options.identify) return; // Don't allow identify without a user id var uid = identify.userId(); if (uid === null || uid === undefined) return; var rollbar = window.Rollbar; var person = { id: uid }; extend(person, identify.traits()); rollbar.configure({ payload: { person: person }}); }; }, {"analytics.js-integration":83,"extend":122,"is":86}], 69: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `SaaSquatch` integration. */ var SaaSquatch = module.exports = integration('SaaSquatch') .option('tenantAlias', '') .global('_sqh') .tag('<script src="//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js">'); /** * Initialize. * * @param {Page} page */ SaaSquatch.prototype.initialize = function(page){ window._sqh = window._sqh || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ SaaSquatch.prototype.loaded = function(){ return window._sqh && window._sqh.push != [].push; }; /** * Identify. * * @param {Facade} identify */ SaaSquatch.prototype.identify = function(identify){ var sqh = window._sqh; var accountId = identify.proxy('traits.accountId'); var image = identify.proxy('traits.referralImage'); var opts = identify.options(this.name); var id = identify.userId(); var email = identify.email(); if (!(id || email)) return; if (this.called) return; var init = { tenant_alias: this.options.tenantAlias, first_name: identify.firstName(), last_name: identify.lastName(), user_image: identify.avatar(), email: email, user_id: id, }; if (accountId) init.account_id = accountId; if (opts.checksum) init.checksum = opts.checksum; if (image) init.fb_share_image = image; sqh.push(['init', init]); this.called = true; this.load(); }; }, {"analytics.js-integration":83}], 70: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var is = require('is'); /** * Expose `Sentry` integration. */ var Sentry = module.exports = integration('Sentry') .global('Raven') .option('config', '') .tag('<script src="//cdn.ravenjs.com/1.1.10/native/raven.min.js">'); /** * Initialize. * * http://raven-js.readthedocs.org/en/latest/config/index.html */ Sentry.prototype.initialize = function(){ var config = this.options.config; var self = this; this.load(function(){ // for now, raven basically requires `install` to be called // https://github.com/getsentry/raven-js/blob/master/src/raven.js#L113 window.Raven.config(config).install(); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Sentry.prototype.loaded = function(){ return is.object(window.Raven); }; /** * Identify. * * @param {Identify} identify */ Sentry.prototype.identify = function(identify){ window.Raven.setUser(identify.traits()); }; }, {"analytics.js-integration":83,"is":86}], 71: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var is = require('is'); /** * Expose `SnapEngage` integration. */ var SnapEngage = module.exports = integration('SnapEngage') .assumesPageview() .global('SnapABug') .option('apiKey', '') .tag('<script src="//commondatastorage.googleapis.com/code.snapengage.com/js/{{ apiKey }}.js">'); /** * Initialize. * * http://help.snapengage.com/installation-guide-getting-started-in-a-snap/ * * @param {Object} page */ SnapEngage.prototype.initialize = function(page){ this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ SnapEngage.prototype.loaded = function(){ return is.object(window.SnapABug); }; /** * Identify. * * @param {Identify} identify */ SnapEngage.prototype.identify = function(identify){ var email = identify.email(); if (!email) return; window.SnapABug.setUserEmail(email); }; }, {"analytics.js-integration":83,"is":86}], 72: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var bind = require('bind'); var when = require('when'); /** * Expose `Spinnakr` integration. */ var Spinnakr = module.exports = integration('Spinnakr') .assumesPageview() .global('_spinnakr_site_id') .global('_spinnakr') .option('siteId', '') .tag('<script src="//d3ojzyhbolvoi5.cloudfront.net/js/so.js">'); /** * Initialize. * * @param {Object} page */ Spinnakr.prototype.initialize = function(page){ window._spinnakr_site_id = this.options.siteId; var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, ready); }); }; /** * Loaded? * * @return {Boolean} */ Spinnakr.prototype.loaded = function(){ return !! window._spinnakr; }; }, {"analytics.js-integration":83,"bind":95,"when":123}], 73: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var slug = require('slug'); var push = require('global-queue')('_tsq'); /** * Expose `Tapstream` integration. */ var Tapstream = module.exports = integration('Tapstream') .assumesPageview() .global('_tsq') .option('accountName', '') .option('trackAllPages', true) .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//cdn.tapstream.com/static/js/tapstream.js">'); /** * Initialize. * * @param {Object} page */ Tapstream.prototype.initialize = function(page){ window._tsq = window._tsq || []; push('setAccountName', this.options.accountName); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Tapstream.prototype.loaded = function(){ return !! (window._tsq && window._tsq.push !== Array.prototype.push); }; /** * Page. * * @param {Page} page */ Tapstream.prototype.page = function(page){ var category = page.category(); var opts = this.options; var name = page.fullName(); // all pages if (opts.trackAllPages) { this.track(page.track()); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Track. * * @param {Track} track */ Tapstream.prototype.track = function(track){ var props = track.properties(); push('fireHit', slug(track.event()), [props.url]); // needs events as slugs }; }, {"analytics.js-integration":83,"slug":93,"global-queue":167}], 74: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var alias = require('alias'); var clone = require('clone'); /** * Expose `Trakio` integration. */ var Trakio = module.exports = integration('trak.io') .assumesPageview() .global('trak') .option('token', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js">'); /** * Options aliases. */ var optionsAliases = { initialPageview: 'auto_track_page_view' }; /** * Initialize. * * https://docs.trak.io * * @param {Object} page */ Trakio.prototype.initialize = function(page){ var options = this.options; window.trak = window.trak || []; window.trak.io = window.trak.io || {}; window.trak.push = window.trak.push || function(){}; window.trak.io.load = window.trak.io.load || function(e){var r = function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0))); }; } ,i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"]; for (var s=0;s<i.length;s++) window.trak.io[i[s]]=r(i[s]); window.trak.io.initialize.apply(window.trak.io,arguments); }; window.trak.io.load(options.token, alias(options, optionsAliases)); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Trakio.prototype.loaded = function(){ return !! (window.trak && window.trak.loaded); }; /** * Page. * * @param {Page} page */ Trakio.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); window.trak.io.page_view(props.path, name || props.title); // named pages if (name && this.options.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && this.options.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Trait aliases. * * http://docs.trak.io/properties.html#special */ var traitAliases = { avatar: 'avatar_url', firstName: 'first_name', lastName: 'last_name' }; /** * Identify. * * @param {Identify} identify */ Trakio.prototype.identify = function(identify){ var traits = identify.traits(traitAliases); var id = identify.userId(); if (id) { window.trak.io.identify(id, traits); } else { window.trak.io.identify(traits); } }; /** * Group. * * @param {String} id (optional) * @param {Object} properties (optional) * @param {Object} options (optional) * * TODO: add group * TODO: add `trait.company/organization` from trak.io docs http://docs.trak.io/properties.html#special */ /** * Track. * * @param {Track} track */ Trakio.prototype.track = function(track){ window.trak.io.track(track.event(), track.properties()); }; /** * Alias. * * @param {Alias} alias */ Trakio.prototype.alias = function(alias){ if (!window.trak.io.distinct_id) return; var from = alias.from(); var to = alias.to(); if (to === window.trak.io.distinct_id()) return; if (from) { window.trak.io.alias(from, to); } else { window.trak.io.alias(to); } }; }, {"analytics.js-integration":83,"alias":172,"clone":171}], 75: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var each = require('each'); /** * HOP. */ var has = Object.prototype.hasOwnProperty; /** * Expose `TwitterAds`. */ var TwitterAds = module.exports = integration('Twitter Ads') .option('page', '') .tag('<img src="//analytics.twitter.com/i/adsct?txn_id={{ pixelId }}&p_id=Twitter"/>') .mapping('events'); /** * Initialize. * * @param {Object} page */ TwitterAds.prototype.initialize = function(){ this.ready(); }; /** * Page. * * @param {Page} page */ TwitterAds.prototype.page = function(page){ if (this.options.page) { this.load({ pixelId: this.options.page }); } }; /** * Track. * * @param {Track} track */ TwitterAds.prototype.track = function(track){ var events = this.events(track.event()); var self = this; each(events, function(pixelId){ self.load({ pixelId: pixelId }); }); }; }, {"analytics.js-integration":83,"each":4}], 76: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_uc'); /** * Expose `Usercycle` integration. */ var Usercycle = module.exports = integration('USERcycle') .assumesPageview() .global('_uc') .option('key', '') .tag('<script src="//api.usercycle.com/javascripts/track.js">'); /** * Initialize. * * http://docs.usercycle.com/javascript_api * * @param {Object} page */ Usercycle.prototype.initialize = function(page){ push('_key', this.options.key); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Usercycle.prototype.loaded = function(){ return !! (window._uc && window._uc.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ Usercycle.prototype.identify = function(identify){ var traits = identify.traits(); var id = identify.userId(); if (id) push('uid', id); // there's a special `came_back` event used for retention and traits push('action', 'came_back', traits); }; /** * Track. * * @param {Track} track */ Usercycle.prototype.track = function(track){ push('action', track.event(), track.properties({ revenue: 'revenue_amount' })); }; }, {"analytics.js-integration":83,"global-queue":167}], 77: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('UserVoice'); var convertDates = require('convert-dates'); var unix = require('to-unix-timestamp'); var alias = require('alias'); var clone = require('clone'); /** * Expose `UserVoice` integration. */ var UserVoice = module.exports = integration('UserVoice') .assumesPageview() .global('UserVoice') .global('showClassicWidget') .option('apiKey', '') .option('classic', false) .option('forumId', null) .option('showWidget', true) .option('mode', 'contact') .option('accentColor', '#448dd6') .option('smartvote', true) .option('trigger', null) .option('triggerPosition', 'bottom-right') .option('triggerColor', '#ffffff') .option('triggerBackgroundColor', 'rgba(46, 49, 51, 0.6)') // BACKWARDS COMPATIBILITY: classic options .option('classicMode', 'full') .option('primaryColor', '#cc6d00') .option('linkColor', '#007dbf') .option('defaultMode', 'support') .option('tabLabel', 'Feedback & Support') .option('tabColor', '#cc6d00') .option('tabPosition', 'middle-right') .option('tabInverted', false) .tag('<script src="//widget.uservoice.com/{{ apiKey }}.js">'); /** * When in "classic" mode, on `construct` swap all of the method to point to * their classic counterparts. */ UserVoice.on('construct', function(integration){ if (!integration.options.classic) return; integration.group = undefined; integration.identify = integration.identifyClassic; integration.initialize = integration.initializeClassic; }); /** * Initialize. * * @param {Object} page */ UserVoice.prototype.initialize = function(page){ var options = this.options; var opts = formatOptions(options); push('set', opts); push('autoprompt', {}); if (options.showWidget) { options.trigger ? push('addTrigger', options.trigger, opts) : push('addTrigger', opts); } this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ UserVoice.prototype.loaded = function(){ return !! (window.UserVoice && window.UserVoice.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ UserVoice.prototype.identify = function(identify){ var traits = identify.traits({ created: 'created_at' }); traits = convertDates(traits, unix); push('identify', traits); }; /** * Group. * * @param {Group} group */ UserVoice.prototype.group = function(group){ var traits = group.traits({ created: 'created_at' }); traits = convertDates(traits, unix); push('identify', { account: traits }); }; /** * Initialize (classic). * * @param {Object} options * @param {Function} ready */ UserVoice.prototype.initializeClassic = function(){ var options = this.options; window.showClassicWidget = showClassicWidget; // part of public api if (options.showWidget) showClassicWidget('showTab', formatClassicOptions(options)); this.load(this.ready); }; /** * Identify (classic). * * @param {Identify} identify */ UserVoice.prototype.identifyClassic = function(identify){ push('setCustomFields', identify.traits()); }; /** * Format the options for UserVoice. * * @param {Object} options * @return {Object} */ function formatOptions(options){ return alias(options, { forumId: 'forum_id', accentColor: 'accent_color', smartvote: 'smartvote_enabled', triggerColor: 'trigger_color', triggerBackgroundColor: 'trigger_background_color', triggerPosition: 'trigger_position' }); } /** * Format the classic options for UserVoice. * * @param {Object} options * @return {Object} */ function formatClassicOptions(options){ return alias(options, { forumId: 'forum_id', classicMode: 'mode', primaryColor: 'primary_color', tabPosition: 'tab_position', tabColor: 'tab_color', linkColor: 'link_color', defaultMode: 'default_mode', tabLabel: 'tab_label', tabInverted: 'tab_inverted' }); } /** * Show the classic version of the UserVoice widget. This method is usually part * of UserVoice classic's public API. * * @param {String} type ('showTab' or 'showLightbox') * @param {Object} options (optional) */ function showClassicWidget(type, options){ type = type || 'showLightbox'; push(type, 'classic_widget', options); } }, {"analytics.js-integration":83,"global-queue":167,"convert-dates":173,"to-unix-timestamp":180,"alias":172,"clone":171}], 180: [function(require, module, exports) { /** * Expose `toUnixTimestamp`. */ module.exports = toUnixTimestamp; /** * Convert a `date` into a Unix timestamp. * * @param {Date} * @return {Number} */ function toUnixTimestamp (date) { return Math.floor(date.getTime() / 1000); } }, {}], 78: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_veroq'); var cookie = require('component/cookie'); /** * Expose `Vero` integration. */ var Vero = module.exports = integration('Vero') .global('_veroq') .option('apiKey', '') .tag('<script src="//d3qxef4rp70elm.cloudfront.net/m.js">'); /** * Initialize. * * https://github.com/getvero/vero-api/blob/master/sections/js.md * * @param {Object} page */ Vero.prototype.initialize = function(page){ // clear default cookie so vero parses correctly. // this is for the tests. // basically, they have window.addEventListener('unload') // which then saves their "command_store", which is an array. // so we just want to create that initially so we can reload the tests. if (!cookie('__veroc4')) cookie('__veroc4', '[]'); push('init', { api_key: this.options.apiKey }); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Vero.prototype.loaded = function(){ return !! (window._veroq && window._veroq.push !== Array.prototype.push); }; /** * Page. * * https://www.getvero.com/knowledge-base#/questions/71768-Does-Vero-track-pageviews * * @param {Page} page */ Vero.prototype.page = function(page){ push('trackPageview'); }; /** * Identify. * * https://github.com/getvero/vero-api/blob/master/sections/js.md#user-identification * * @param {Identify} identify */ Vero.prototype.identify = function(identify){ var traits = identify.traits(); var email = identify.email(); var id = identify.userId(); if (!id || !email) return; // both required push('user', traits); }; /** * Track. * * https://github.com/getvero/vero-api/blob/master/sections/js.md#tracking-events * * @param {Track} track */ Vero.prototype.track = function(track){ push('track', track.event(), track.properties()); }; }, {"analytics.js-integration":83,"global-queue":167,"component/cookie":181}], 181: [function(require, module, exports) { /** * Encode. */ var encode = encodeURIComponent; /** * Decode. */ var decode = decodeURIComponent; /** * Set or get cookie `name` with `value` and `options` object. * * @param {String} name * @param {String} value * @param {Object} options * @return {Mixed} * @api public */ module.exports = function(name, value, options){ switch (arguments.length) { case 3: case 2: return set(name, value, options); case 1: return get(name); default: return all(); } }; /** * Set cookie `name` to `value`. * * @param {String} name * @param {String} value * @param {Object} options * @api private */ function set(name, value, options) { options = options || {}; var str = encode(name) + '=' + encode(value); if (null == value) options.maxage = -1; if (options.maxage) { options.expires = new Date(+new Date + options.maxage); } if (options.path) str += '; path=' + options.path; if (options.domain) str += '; domain=' + options.domain; if (options.expires) str += '; expires=' + options.expires.toGMTString(); if (options.secure) str += '; secure'; document.cookie = str; } /** * Return all cookies. * * @return {Object} * @api private */ function all() { return parse(document.cookie); } /** * Get cookie `name`. * * @param {String} name * @return {String} * @api private */ function get(name) { return all()[name]; } /** * Parse cookie `str`. * * @param {String} str * @return {Object} * @api private */ function parse(str) { var obj = {}; var pairs = str.split(/ *; */); var pair; if ('' == pairs[0]) return obj; for (var i = 0; i < pairs.length; ++i) { pair = pairs[i].split('='); obj[decode(pair[0])] = decode(pair[1]); } return obj; } }, {}], 79: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var tick = require('next-tick'); var each = require('each'); /** * Expose `VWO` integration. */ var VWO = module.exports = integration('Visual Website Optimizer') .option('replay', true); /** * Initialize. * * http://v2.visualwebsiteoptimizer.com/tools/get_tracking_code.php */ VWO.prototype.initialize = function(){ if (this.options.replay) this.replay(); this.ready(); }; /** * Replay the experiments the user has seen as traits to all other integrations. * Wait for the next tick to replay so that the `analytics` object and all of * the integrations are fully initialized. */ VWO.prototype.replay = function(){ var analytics = this.analytics; tick(function(){ experiments(function(err, traits){ if (traits) analytics.identify(traits); }); }); }; /** * Get dictionary of experiment keys and variations. * * http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/ * * @param {Function} fn * @return {Object} */ function experiments(fn){ enqueue(function(){ var data = {}; var ids = window._vwo_exp_ids; if (!ids) return fn(); each(ids, function(id){ var name = variation(id); if (name) data['Experiment: ' + id] = name; }); fn(null, data); }); } /** * Add a `fn` to the VWO queue, creating one if it doesn't exist. * * @param {Function} fn */ function enqueue(fn){ window._vis_opt_queue = window._vis_opt_queue || []; window._vis_opt_queue.push(fn); } /** * Get the chosen variation's name from an experiment `id`. * * http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/ * * @param {String} id * @return {String} */ function variation(id){ var experiments = window._vwo_exp; if (!experiments) return null; var experiment = experiments[id]; var variationId = experiment.combination_chosen; return variationId ? experiment.comb_n[variationId] : null; } }, {"analytics.js-integration":83,"next-tick":97,"each":4}], 80: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var useHttps = require('use-https'); /** * Expose `WebEngage` integration. */ var WebEngage = module.exports = integration('WebEngage') .assumesPageview() .global('_weq') .global('webengage') .option('widgetVersion', '4.0') .option('licenseCode', '') .tag('http', '<script src="http://cdn.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">') .tag('https', '<script src="https://ssl.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">'); /** * Initialize. * * @param {Object} page */ WebEngage.prototype.initialize = function(page){ var _weq = window._weq = window._weq || {}; _weq['webengage.licenseCode'] = this.options.licenseCode; _weq['webengage.widgetVersion'] = this.options.widgetVersion; var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ WebEngage.prototype.loaded = function(){ return !! window.webengage; }; }, {"analytics.js-integration":83,"use-https":85}], 81: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var snake = require('to-snake-case'); var isEmail = require('is-email'); var extend = require('extend'); var each = require('each'); var type = require('type'); /** * Expose `Woopra` integration. */ var Woopra = module.exports = integration('Woopra') .global('woopra') .option('domain', '') .option('cookieName', 'wooTracker') .option('cookieDomain', null) .option('cookiePath', '/') .option('ping', true) .option('pingInterval', 12000) .option('idleTimeout', 300000) .option('downloadTracking', true) .option('outgoingTracking', true) .option('outgoingIgnoreSubdomain', true) .option('downloadPause', 200) .option('outgoingPause', 400) .option('ignoreQueryUrl', true) .option('hideCampaign', false) .tag('<script src="//static.woopra.com/js/w.js">'); /** * Initialize. * * http://www.woopra.com/docs/setup/javascript-tracking/ * * @param {Object} page */ Woopra.prototype.initialize = function(page){ (function () {var i, s, z, w = window, d = document, a = arguments, q = 'script', f = ['config', 'track', 'identify', 'visit', 'push', 'call'], c = function () {var i, self = this; self._e = []; for (i = 0; i < f.length; i++) {(function (f) {self[f] = function () {self._e.push([f].concat(Array.prototype.slice.call(arguments, 0))); return self; }; })(f[i]); } }; w._w = w._w || {}; for (i = 0; i < a.length; i++) { w._w[a[i]] = w[a[i]] = w[a[i]] || new c(); } })('woopra'); this.load(this.ready); each(this.options, function(key, value){ key = snake(key); if (null == value) return; if ('' === value) return; window.woopra.config(key, value); }); }; /** * Loaded? * * @return {Boolean} */ Woopra.prototype.loaded = function(){ return !! (window.woopra && window.woopra.loaded); }; /** * Page. * * @param {String} category (optional) */ Woopra.prototype.page = function(page){ var props = page.properties(); var name = page.fullName(); if (name) props.title = name; window.woopra.track('pv', props); }; /** * Identify. * * @param {Identify} identify */ Woopra.prototype.identify = function(identify){ var traits = identify.traits(); if (identify.name()) traits.name = identify.name(); window.woopra.identify(traits).push(); // `push` sends it off async }; /** * Track. * * @param {Track} track */ Woopra.prototype.track = function(track){ window.woopra.track(track.event(), track.properties()); }; }, {"analytics.js-integration":83,"to-snake-case":84,"is-email":162,"extend":122,"each":4,"type":7}], 82: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var tick = require('next-tick'); var bind = require('bind'); var when = require('when'); /** * Expose `Yandex` integration. */ var Yandex = module.exports = integration('Yandex Metrica') .assumesPageview() .global('yandex_metrika_callbacks') .global('Ya') .option('counterId', null) .option('clickmap', false) .option('webvisor', false) .tag('<script src="//mc.yandex.ru/metrika/watch.js">'); /** * Initialize. * * http://api.yandex.com/metrika/ * https://metrica.yandex.com/22522351?step=2#tab=code * * @param {Object} page */ Yandex.prototype.initialize = function(page){ var id = this.options.counterId; var clickmap = this.options.clickmap; var webvisor = this.options.webvisor; push(function(){ window['yaCounter' + id] = new window.Ya.Metrika({ id: id, clickmap: clickmap, webvisor: webvisor }); }); var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, function(){ tick(ready); }); }); }; /** * Loaded? * * @return {Boolean} */ Yandex.prototype.loaded = function(){ return !! (window.Ya && window.Ya.Metrika); }; /** * Push a new callback on the global Yandex queue. * * @param {Function} callback */ function push(callback){ window.yandex_metrika_callbacks = window.yandex_metrika_callbacks || []; window.yandex_metrika_callbacks.push(callback); } }, {"analytics.js-integration":83,"next-tick":97,"bind":95,"when":123}], 3: [function(require, module, exports) { var after = require('after'); var bind = require('bind'); var callback = require('callback'); var canonical = require('canonical'); var clone = require('clone'); var cookie = require('./cookie'); var debug = require('debug'); var defaults = require('defaults'); var each = require('each'); var Emitter = require('emitter'); var group = require('./group'); var is = require('is'); var isEmail = require('is-email'); var isMeta = require('is-meta'); var newDate = require('new-date'); var on = require('event').bind; var prevent = require('prevent'); var querystring = require('querystring'); var size = require('object').length; var store = require('./store'); var url = require('url'); var user = require('./user'); var Facade = require('facade'); var Identify = Facade.Identify; var Group = Facade.Group; var Alias = Facade.Alias; var Track = Facade.Track; var Page = Facade.Page; /** * Expose `Analytics`. */ exports = module.exports = Analytics; /** * Expose `cookie` */ exports.cookie = cookie; exports.store = store; /** * Initialize a new `Analytics` instance. */ function Analytics () { this.Integrations = {}; this._integrations = {}; this._readied = false; this._timeout = 300; this._user = user; // BACKWARDS COMPATIBILITY bind.all(this); var self = this; this.on('initialize', function (settings, options) { if (options.initialPageview) self.page(); }); this.on('initialize', function () { self._parseQuery(); }); } /** * Event Emitter. */ Emitter(Analytics.prototype); /** * Use a `plugin`. * * @param {Function} plugin * @return {Analytics} */ Analytics.prototype.use = function (plugin) { plugin(this); return this; }; /** * Define a new `Integration`. * * @param {Function} Integration * @return {Analytics} */ Analytics.prototype.addIntegration = function (Integration) { var name = Integration.prototype.name; if (!name) throw new TypeError('attempted to add an invalid integration'); this.Integrations[name] = Integration; return this; }; /** * Initialize with the given integration `settings` and `options`. Aliased to * `init` for convenience. * * @param {Object} settings * @param {Object} options (optional) * @return {Analytics} */ Analytics.prototype.init = Analytics.prototype.initialize = function (settings, options) { settings = settings || {}; options = options || {}; this._options(options); this._readied = false; // clean unknown integrations from settings var self = this; each(settings, function (name) { var Integration = self.Integrations[name]; if (!Integration) delete settings[name]; }); // add integrations each(settings, function (name, opts) { var Integration = self.Integrations[name]; var integration = new Integration(clone(opts)); self.add(integration); }); var integrations = this._integrations; // load user now that options are set user.load(); group.load(); // make ready callback var ready = after(size(integrations), function () { self._readied = true; self.emit('ready'); }); // initialize integrations, passing ready each(integrations, function (name, integration) { if (options.initialPageview && integration.options.initialPageview === false) { integration.page = after(2, integration.page); } integration.analytics = self; integration.once('ready', ready); integration.initialize(); }); // backwards compat with angular plugin. // TODO: remove this.initialized = true; this.emit('initialize', settings, options); return this; }; /** * Add an integration. * * @param {Integration} integration */ Analytics.prototype.add = function(integration){ this._integrations[integration.name] = integration; return this; }; /** * Identify a user by optional `id` and `traits`. * * @param {String} id (optional) * @param {Object} traits (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.identify = function (id, traits, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(traits)) fn = traits, options = null, traits = null; if (is.object(id)) options = traits, traits = id, id = user.id(); // clone traits before we manipulate so we don't do anything uncouth, and take // from `user` so that we carryover anonymous traits user.identify(id, traits); id = user.id(); traits = user.traits(); this._invoke('identify', message(Identify, { options: options, traits: traits, userId: id })); // emit this.emit('identify', id, traits, options); this._callback(fn); return this; }; /** * Return the current user. * * @return {Object} */ Analytics.prototype.user = function () { return user; }; /** * Identify a group by optional `id` and `traits`. Or, if no arguments are * supplied, return the current group. * * @param {String} id (optional) * @param {Object} traits (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics or Object} */ Analytics.prototype.group = function (id, traits, options, fn) { if (0 === arguments.length) return group; if (is.fn(options)) fn = options, options = null; if (is.fn(traits)) fn = traits, options = null, traits = null; if (is.object(id)) options = traits, traits = id, id = group.id(); // grab from group again to make sure we're taking from the source group.identify(id, traits); id = group.id(); traits = group.traits(); this._invoke('group', message(Group, { options: options, traits: traits, groupId: id })); this.emit('group', id, traits, options); this._callback(fn); return this; }; /** * Track an `event` that a user has triggered with optional `properties`. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.track = function (event, properties, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(properties)) fn = properties, options = null, properties = null; this._invoke('track', message(Track, { properties: properties, options: options, event: event })); this.emit('track', event, properties, options); this._callback(fn); return this; }; /** * Helper method to track an outbound link that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackClick`. * * @param {Element or Array} links * @param {String or Function} event * @param {Object or Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackClick = Analytics.prototype.trackLink = function (links, event, properties) { if (!links) return this; if (is.element(links)) links = [links]; // always arrays, handles jquery var self = this; each(links, function (el) { if (!is.element(el)) throw new TypeError('Must pass HTMLElement to `analytics.trackLink`.'); on(el, 'click', function (e) { var ev = is.fn(event) ? event(el) : event; var props = is.fn(properties) ? properties(el) : properties; self.track(ev, props); if (el.href && el.target !== '_blank' && !isMeta(e)) { prevent(e); self._callback(function () { window.location.href = el.href; }); } }); }); return this; }; /** * Helper method to track an outbound form that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackSubmit`. * * @param {Element or Array} forms * @param {String or Function} event * @param {Object or Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackSubmit = Analytics.prototype.trackForm = function (forms, event, properties) { if (!forms) return this; if (is.element(forms)) forms = [forms]; // always arrays, handles jquery var self = this; each(forms, function (el) { if (!is.element(el)) throw new TypeError('Must pass HTMLElement to `analytics.trackForm`.'); function handler (e) { prevent(e); var ev = is.fn(event) ? event(el) : event; var props = is.fn(properties) ? properties(el) : properties; self.track(ev, props); self._callback(function () { el.submit(); }); } // support the events happening through jQuery or Zepto instead of through // the normal DOM API, since `el.submit` doesn't bubble up events... var $ = window.jQuery || window.Zepto; if ($) { $(el).submit(handler); } else { on(el, 'submit', handler); } }); return this; }; /** * Trigger a pageview, labeling the current page with an optional `category`, * `name` and `properties`. * * @param {String} category (optional) * @param {String} name (optional) * @param {Object or String} properties (or path) (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.page = function (category, name, properties, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(properties)) fn = properties, options = properties = null; if (is.fn(name)) fn = name, options = properties = name = null; if (is.object(category)) options = name, properties = category, name = category = null; if (is.object(name)) options = properties, properties = name, name = null; if (is.string(category) && !is.string(name)) name = category, category = null; var defs = { path: canonicalPath(), referrer: document.referrer, title: document.title, search: location.search }; if (name) defs.name = name; if (category) defs.category = category; properties = clone(properties) || {}; defaults(properties, defs); properties.url = properties.url || canonicalUrl(properties.search); this._invoke('page', message(Page, { properties: properties, category: category, options: options, name: name })); this.emit('page', category, name, properties, options); this._callback(fn); return this; }; /** * BACKWARDS COMPATIBILITY: convert an old `pageview` to a `page` call. * * @param {String} url (optional) * @param {Object} options (optional) * @return {Analytics} * @api private */ Analytics.prototype.pageview = function (url, options) { var properties = {}; if (url) properties.path = url; this.page(properties); return this; }; /** * Merge two previously unassociated user identities. * * @param {String} to * @param {String} from (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.alias = function (to, from, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(from)) fn = from, options = null, from = null; if (is.object(from)) options = from, from = null; this._invoke('alias', message(Alias, { options: options, from: from, to: to })); this.emit('alias', to, from, options); this._callback(fn); return this; }; /** * Register a `fn` to be fired when all the analytics services are ready. * * @param {Function} fn * @return {Analytics} */ Analytics.prototype.ready = function (fn) { if (!is.fn(fn)) return this; this._readied ? callback.async(fn) : this.once('ready', fn); return this; }; /** * Set the `timeout` (in milliseconds) used for callbacks. * * @param {Number} timeout */ Analytics.prototype.timeout = function (timeout) { this._timeout = timeout; }; /** * Enable or disable debug. * * @param {String or Boolean} str */ Analytics.prototype.debug = function(str){ if (0 == arguments.length || str) { debug.enable('analytics:' + (str || '*')); } else { debug.disable(); } }; /** * Apply options. * * @param {Object} options * @return {Analytics} * @api private */ Analytics.prototype._options = function (options) { options = options || {}; cookie.options(options.cookie); store.options(options.localStorage); user.options(options.user); group.options(options.group); return this; }; /** * Callback a `fn` after our defined timeout period. * * @param {Function} fn * @return {Analytics} * @api private */ Analytics.prototype._callback = function (fn) { callback.async(fn, this._timeout); return this; }; /** * Call `method` with `facade` on all enabled integrations. * * @param {String} method * @param {Facade} facade * @return {Analytics} * @api private */ Analytics.prototype._invoke = function (method, facade) { var options = facade.options(); this.emit('invoke', facade); each(this._integrations, function (name, integration) { if (!facade.enabled(name)) return; integration.invoke.call(integration, method, facade); }); return this; }; /** * Push `args`. * * @param {Array} args * @api private */ Analytics.prototype.push = function(args){ var method = args.shift(); if (!this[method]) return; this[method].apply(this, args); }; /** * Parse the query string for callable methods. * * @return {Analytics} * @api private */ Analytics.prototype._parseQuery = function () { // Identify and track any `ajs_uid` and `ajs_event` parameters in the URL. var q = querystring.parse(window.location.search); if (q.ajs_uid) this.identify(q.ajs_uid); if (q.ajs_event) this.track(q.ajs_event); return this; }; /** * Return the canonical path for the page. * * @return {String} */ function canonicalPath () { var canon = canonical(); if (!canon) return window.location.pathname; var parsed = url.parse(canon); return parsed.pathname; } /** * Return the canonical URL for the page concat the given `search` * and strip the hash. * * @param {String} search * @return {String} */ function canonicalUrl (search) { var canon = canonical(); if (canon) return ~canon.indexOf('?') ? canon : canon + search; var url = window.location.href; var i = url.indexOf('#'); return -1 == i ? url : url.slice(0, i); } /** * Create a new message with `Type` and `msg` * * the function will make sure that the `msg.options` * is merged to `msg` and deletes `msg.options` if it * has `.context / .timestamp / .integrations / .anonymousId`. * * Example: * * message(Identify, { * options: { timestamp: Date, context: Object, integrations: Object }, * traits: { trait: true }, * userId: 123 * }); * * // => * * { * userId: 123, * context: Object, * timestamp: Date, * integrations: Object * traits: { trait: true } * } * * @param {Function} Type * @param {Object} msg * @return {Facade} */ function message(Type, msg){ var ctx = msg.options || {}; if (ctx.timestamp || ctx.integrations || ctx.context || ctx.anonymousId) { msg = defaults(ctx, msg); delete msg.options; } return new Type(msg); } }, {"after":105,"bind":182,"callback":88,"canonical":175,"clone":89,"./cookie":183,"debug":184,"defaults":91,"each":4,"emitter":102,"./group":185,"is":86,"is-email":162,"is-meta":186,"new-date":139,"event":187,"prevent":188,"querystring":189,"object":174,"./store":190,"url":176,"./user":191,"facade":124}], 182: [function(require, module, exports) { try { var bind = require('bind'); } catch (e) { var bind = require('bind-component'); } var bindAll = require('bind-all'); /** * Expose `bind`. */ module.exports = exports = bind; /** * Expose `bindAll`. */ exports.all = bindAll; /** * Expose `bindMethods`. */ exports.methods = bindMethods; /** * Bind `methods` on `obj` to always be called with the `obj` as context. * * @param {Object} obj * @param {String} methods... */ function bindMethods (obj, methods) { methods = [].slice.call(arguments, 1); for (var i = 0, method; method = methods[i]; i++) { obj[method] = bind(obj, obj[method]); } return obj; } }, {"bind":95,"bind-all":96}], 183: [function(require, module, exports) { var debug = require('debug')('analytics.js:cookie'); var bind = require('bind'); var cookie = require('cookie'); var clone = require('clone'); var defaults = require('defaults'); var json = require('json'); var topDomain = require('top-domain'); /** * Initialize a new `Cookie` with `options`. * * @param {Object} options */ function Cookie (options) { this.options(options); } /** * Get or set the cookie options. * * @param {Object} options * @field {Number} maxage (1 year) * @field {String} domain * @field {String} path * @field {Boolean} secure */ Cookie.prototype.options = function (options) { if (arguments.length === 0) return this._options; options = options || {}; var domain = '.' + topDomain(window.location.href); this._options = defaults(options, { maxage: 31536000000, // default to a year path: '/', domain: domain }); // http://curl.haxx.se/rfc/cookie_spec.html // https://publicsuffix.org/list/effective_tld_names.dat // // try setting a dummy cookie with the options // if the cookie isn't set, it probably means // that the domain is on the public suffix list // like myapp.herokuapp.com or localhost / ip. this.set('ajs:test', true); if (!this.get('ajs:test')) { debug('fallback to domain=null'); this._options.domain = null; } this.remove('ajs:test'); }; /** * Set a `key` and `value` in our cookie. * * @param {String} key * @param {Object} value * @return {Boolean} saved */ Cookie.prototype.set = function (key, value) { try { value = json.stringify(value); cookie(key, value, clone(this._options)); return true; } catch (e) { return false; } }; /** * Get a value from our cookie by `key`. * * @param {String} key * @return {Object} value */ Cookie.prototype.get = function (key) { try { var value = cookie(key); value = value ? json.parse(value) : null; return value; } catch (e) { return null; } }; /** * Remove a value from our cookie by `key`. * * @param {String} key * @return {Boolean} removed */ Cookie.prototype.remove = function (key) { try { cookie(key, null, clone(this._options)); return true; } catch (e) { return false; } }; /** * Expose the cookie singleton. */ module.exports = bind.all(new Cookie()); /** * Expose the `Cookie` constructor. */ module.exports.Cookie = Cookie; }, {"debug":184,"bind":182,"cookie":181,"clone":89,"defaults":91,"json":192,"top-domain":193}], 184: [function(require, module, exports) { if ('undefined' == typeof window) { module.exports = require('./lib/debug'); } else { module.exports = require('./debug'); } }, {"./lib/debug":194,"./debug":195}], 194: [function(require, module, exports) { /** * Module dependencies. */ var tty = require('tty'); /** * Expose `debug()` as the module. */ module.exports = debug; /** * Enabled debuggers. */ var names = [] , skips = []; (process.env.DEBUG || '') .split(/[\s,]+/) .forEach(function(name){ name = name.replace('*', '.*?'); if (name[0] === '-') { skips.push(new RegExp('^' + name.substr(1) + '$')); } else { names.push(new RegExp('^' + name + '$')); } }); /** * Colors. */ var colors = [6, 2, 3, 4, 5, 1]; /** * Previous debug() call. */ var prev = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Is stdout a TTY? Colored output is disabled when `true`. */ var isatty = tty.isatty(2); /** * Select a color. * * @return {Number} * @api private */ function color() { return colors[prevColor++ % colors.length]; } /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ function humanize(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; } /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { function disabled(){} disabled.enabled = false; var match = skips.some(function(re){ return re.test(name); }); if (match) return disabled; match = names.some(function(re){ return re.test(name); }); if (!match) return disabled; var c = color(); function colored(fmt) { fmt = coerce(fmt); var curr = new Date; var ms = curr - (prev[name] || curr); prev[name] = curr; fmt = ' \u001b[9' + c + 'm' + name + ' ' + '\u001b[3' + c + 'm\u001b[90m' + fmt + '\u001b[3' + c + 'm' + ' +' + humanize(ms) + '\u001b[0m'; console.error.apply(this, arguments); } function plain(fmt) { fmt = coerce(fmt); fmt = new Date().toUTCString() + ' ' + name + ' ' + fmt; console.error.apply(this, arguments); } colored.enabled = plain.enabled = true; return isatty || process.env.DEBUG_COLORS ? colored : plain; } /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } }, {}], 195: [function(require, module, exports) { /** * Expose `debug()` as the module. */ module.exports = debug; /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { if (!debug.enabled(name)) return function(){}; return function(fmt){ fmt = coerce(fmt); var curr = new Date; var ms = curr - (debug[name] || curr); debug[name] = curr; fmt = name + ' ' + fmt + ' +' + debug.humanize(ms); // This hackery is required for IE8 // where `console.log` doesn't have 'apply' window.console && console.log && Function.prototype.apply.call(console.log, console, arguments); } } /** * The currently active debug mode names. */ debug.names = []; debug.skips = []; /** * Enables a debug mode by name. This can include modes * separated by a colon and wildcards. * * @param {String} name * @api public */ debug.enable = function(name) { try { localStorage.debug = name; } catch(e){} var split = (name || '').split(/[\s,]+/) , len = split.length; for (var i = 0; i < len; i++) { name = split[i].replace('*', '.*?'); if (name[0] === '-') { debug.skips.push(new RegExp('^' + name.substr(1) + '$')); } else { debug.names.push(new RegExp('^' + name + '$')); } } }; /** * Disable debug output. * * @api public */ debug.disable = function(){ debug.enable(''); }; /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ debug.humanize = function(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; }; /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ debug.enabled = function(name) { for (var i = 0, len = debug.skips.length; i < len; i++) { if (debug.skips[i].test(name)) { return false; } } for (var i = 0, len = debug.names.length; i < len; i++) { if (debug.names[i].test(name)) { return true; } } return false; }; /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } // persist try { if (window.localStorage) debug.enable(localStorage.debug); } catch(e){} }, {}], 192: [function(require, module, exports) { var json = window.JSON || {}; var stringify = json.stringify; var parse = json.parse; module.exports = parse && stringify ? JSON : require('json-fallback'); }, {"json-fallback":196}], 196: [function(require, module, exports) { /* json2.js 2014-02-04 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. (function () { 'use strict'; var JSON = module.exports = {}; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function () { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function () { return this.valueOf(); }; } var cx, escapable, gap, indent, meta, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }; JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); }, {}], 193: [function(require, module, exports) { /** * Module dependencies. */ var parse = require('url').parse; /** * Expose `domain` */ module.exports = domain; /** * RegExp */ var regexp = /[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i; /** * Get the top domain. * * Official Grammar: http://tools.ietf.org/html/rfc883#page-56 * Look for tlds with up to 2-6 characters. * * Example: * * domain('http://localhost:3000/baz'); * // => '' * domain('http://dev:3000/baz'); * // => '' * domain('http://127.0.0.1:3000/baz'); * // => '' * domain('http://segment.io/baz'); * // => 'segment.io' * * @param {String} url * @return {String} * @api public */ function domain(url){ var host = parse(url).hostname; var match = host.match(regexp); return match ? match[0] : ''; }; }, {"url":176}], 185: [function(require, module, exports) { var debug = require('debug')('analytics:group'); var Entity = require('./entity'); var inherit = require('inherit'); var bind = require('bind'); /** * Group defaults */ Group.defaults = { persist: true, cookie: { key: 'ajs_group_id' }, localStorage: { key: 'ajs_group_properties' } }; /** * Initialize a new `Group` with `options`. * * @param {Object} options */ function Group (options) { this.defaults = Group.defaults; this.debug = debug; Entity.call(this, options); } /** * Inherit `Entity` */ inherit(Group, Entity); /** * Expose the group singleton. */ module.exports = bind.all(new Group()); /** * Expose the `Group` constructor. */ module.exports.Group = Group; }, {"debug":184,"./entity":197,"inherit":198,"bind":182}], 197: [function(require, module, exports) { var traverse = require('isodate-traverse'); var defaults = require('defaults'); var cookie = require('./cookie'); var store = require('./store'); var extend = require('extend'); var clone = require('clone'); /** * Expose `Entity` */ module.exports = Entity; /** * Initialize new `Entity` with `options`. * * @param {Object} options */ function Entity(options){ this.protocol = window.location.protocol; this.options(options); } /** * Get the storage. * * When .protocol is `file:` or `chrome-extension:` * the method will return the localstorage (store) * otherwise it will return the cookie. * * @return {Object} */ Entity.prototype.storage = function(){ return 'file:' == this.protocol || 'chrome-extension:' == this.protocol ? store : cookie; }; /** * Get or set storage `options`. * * @param {Object} options * @property {Object} cookie * @property {Object} localStorage * @property {Boolean} persist (default: `true`) */ Entity.prototype.options = function (options) { if (arguments.length === 0) return this._options; options || (options = {}); defaults(options, this.defaults || {}); this._options = options; }; /** * Get or set the entity's `id`. * * @param {String} id */ Entity.prototype.id = function (id) { switch (arguments.length) { case 0: return this._getId(); case 1: return this._setId(id); } }; /** * Get the entity's id. * * @return {String} */ Entity.prototype._getId = function () { var storage = this.storage(); var ret = this._options.persist ? storage.get(this._options.cookie.key) : this._id; return ret === undefined ? null : ret; }; /** * Set the entity's `id`. * * @param {String} id */ Entity.prototype._setId = function (id) { var storage = this.storage(); if (this._options.persist) { storage.set(this._options.cookie.key, id); } else { this._id = id; } }; /** * Get or set the entity's `traits`. * * BACKWARDS COMPATIBILITY: aliased to `properties` * * @param {Object} traits */ Entity.prototype.properties = Entity.prototype.traits = function (traits) { switch (arguments.length) { case 0: return this._getTraits(); case 1: return this._setTraits(traits); } }; /** * Get the entity's traits. Always convert ISO date strings into real dates, * since they aren't parsed back from local storage. * * @return {Object} */ Entity.prototype._getTraits = function () { var ret = this._options.persist ? store.get(this._options.localStorage.key) : this._traits; return ret ? traverse(clone(ret)) : {}; }; /** * Set the entity's `traits`. * * @param {Object} traits */ Entity.prototype._setTraits = function (traits) { traits || (traits = {}); if (this._options.persist) { store.set(this._options.localStorage.key, traits); } else { this._traits = traits; } }; /** * Identify the entity with an `id` and `traits`. If we it's the same entity, * extend the existing `traits` instead of overwriting. * * @param {String} id * @param {Object} traits */ Entity.prototype.identify = function (id, traits) { traits || (traits = {}); var current = this.id(); if (current === null || current === id) traits = extend(this.traits(), traits); if (id) this.id(id); this.debug('identify %o, %o', id, traits); this.traits(traits); this.save(); }; /** * Save the entity to local storage and the cookie. * * @return {Boolean} */ Entity.prototype.save = function () { if (!this._options.persist) return false; cookie.set(this._options.cookie.key, this.id()); store.set(this._options.localStorage.key, this.traits()); return true; }; /** * Log the entity out, reseting `id` and `traits` to defaults. */ Entity.prototype.logout = function () { this.id(null); this.traits({}); cookie.remove(this._options.cookie.key); store.remove(this._options.localStorage.key); }; /** * Reset all entity state, logging out and returning options to defaults. */ Entity.prototype.reset = function () { this.logout(); this.options({}); }; /** * Load saved entity `id` or `traits` from storage. */ Entity.prototype.load = function () { this.id(cookie.get(this._options.cookie.key)); this.traits(store.get(this._options.localStorage.key)); }; }, {"isodate-traverse":134,"defaults":91,"./cookie":183,"./store":190,"extend":122,"clone":89}], 190: [function(require, module, exports) { var bind = require('bind'); var defaults = require('defaults'); var store = require('store.js'); /** * Initialize a new `Store` with `options`. * * @param {Object} options */ function Store (options) { this.options(options); } /** * Set the `options` for the store. * * @param {Object} options * @field {Boolean} enabled (true) */ Store.prototype.options = function (options) { if (arguments.length === 0) return this._options; options = options || {}; defaults(options, { enabled : true }); this.enabled = options.enabled && store.enabled; this._options = options; }; /** * Set a `key` and `value` in local storage. * * @param {String} key * @param {Object} value */ Store.prototype.set = function (key, value) { if (!this.enabled) return false; return store.set(key, value); }; /** * Get a value from local storage by `key`. * * @param {String} key * @return {Object} */ Store.prototype.get = function (key) { if (!this.enabled) return null; return store.get(key); }; /** * Remove a value from local storage by `key`. * * @param {String} key */ Store.prototype.remove = function (key) { if (!this.enabled) return false; return store.remove(key); }; /** * Expose the store singleton. */ module.exports = bind.all(new Store()); /** * Expose the `Store` constructor. */ module.exports.Store = Store; }, {"bind":182,"defaults":91,"store.js":199}], 199: [function(require, module, exports) { var json = require('json') , store = {} , win = window , doc = win.document , localStorageName = 'localStorage' , namespace = '__storejs__' , storage; store.disabled = false store.set = function(key, value) {} store.get = function(key) {} store.remove = function(key) {} store.clear = function() {} store.transact = function(key, defaultVal, transactionFn) { var val = store.get(key) if (transactionFn == null) { transactionFn = defaultVal defaultVal = null } if (typeof val == 'undefined') { val = defaultVal || {} } transactionFn(val) store.set(key, val) } store.getAll = function() {} store.serialize = function(value) { return json.stringify(value) } store.deserialize = function(value) { if (typeof value != 'string') { return undefined } try { return json.parse(value) } catch(e) { return value || undefined } } // Functions to encapsulate questionable FireFox 3.6.13 behavior // when about.config::dom.storage.enabled === false // See https://github.com/marcuswestin/store.js/issues#issue/13 function isLocalStorageNameSupported() { try { return (localStorageName in win && win[localStorageName]) } catch(err) { return false } } if (isLocalStorageNameSupported()) { storage = win[localStorageName] store.set = function(key, val) { if (val === undefined) { return store.remove(key) } storage.setItem(key, store.serialize(val)) return val } store.get = function(key) { return store.deserialize(storage.getItem(key)) } store.remove = function(key) { storage.removeItem(key) } store.clear = function() { storage.clear() } store.getAll = function() { var ret = {} for (var i=0; i<storage.length; ++i) { var key = storage.key(i) ret[key] = store.get(key) } return ret } } else if (doc.documentElement.addBehavior) { var storageOwner, storageContainer // Since #userData storage applies only to specific paths, we need to // somehow link our data to a specific path. We choose /favicon.ico // as a pretty safe option, since all browsers already make a request to // this URL anyway and being a 404 will not hurt us here. We wrap an // iframe pointing to the favicon in an ActiveXObject(htmlfile) object // (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx) // since the iframe access rules appear to allow direct access and // manipulation of the document element, even for a 404 page. This // document can be used instead of the current document (which would // have been limited to the current path) to perform #userData storage. try { storageContainer = new ActiveXObject('htmlfile') storageContainer.open() storageContainer.write('<s' + 'cript>document.w=window</s' + 'cript><iframe src="/favicon.ico"></iframe>') storageContainer.close() storageOwner = storageContainer.w.frames[0].document storage = storageOwner.createElement('div') } catch(e) { // somehow ActiveXObject instantiation failed (perhaps some special // security settings or otherwse), fall back to per-path storage storage = doc.createElement('div') storageOwner = doc.body } function withIEStorage(storeFunction) { return function() { var args = Array.prototype.slice.call(arguments, 0) args.unshift(storage) // See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx // and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx storageOwner.appendChild(storage) storage.addBehavior('#default#userData') storage.load(localStorageName) var result = storeFunction.apply(store, args) storageOwner.removeChild(storage) return result } } // In IE7, keys may not contain special chars. See all of https://github.com/marcuswestin/store.js/issues/40 var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g") function ieKeyFix(key) { return key.replace(forbiddenCharsRegex, '___') } store.set = withIEStorage(function(storage, key, val) { key = ieKeyFix(key) if (val === undefined) { return store.remove(key) } storage.setAttribute(key, store.serialize(val)) storage.save(localStorageName) return val }) store.get = withIEStorage(function(storage, key) { key = ieKeyFix(key) return store.deserialize(storage.getAttribute(key)) }) store.remove = withIEStorage(function(storage, key) { key = ieKeyFix(key) storage.removeAttribute(key) storage.save(localStorageName) }) store.clear = withIEStorage(function(storage) { var attributes = storage.XMLDocument.documentElement.attributes storage.load(localStorageName) for (var i=0, attr; attr=attributes[i]; i++) { storage.removeAttribute(attr.name) } storage.save(localStorageName) }) store.getAll = withIEStorage(function(storage) { var attributes = storage.XMLDocument.documentElement.attributes var ret = {} for (var i=0, attr; attr=attributes[i]; ++i) { var key = ieKeyFix(attr.name) ret[attr.name] = store.deserialize(storage.getAttribute(key)) } return ret }) } try { store.set(namespace, namespace) if (store.get(namespace) != namespace) { store.disabled = true } store.remove(namespace) } catch(e) { store.disabled = true } store.enabled = !store.disabled module.exports = store; }, {"json":192}], 198: [function(require, module, exports) { module.exports = function(a, b){ var fn = function(){}; fn.prototype = b.prototype; a.prototype = new fn; a.prototype.constructor = a; }; }, {}], 186: [function(require, module, exports) { module.exports = function isMeta (e) { if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return true; // Logic that handles checks for the middle mouse button, based // on [jQuery](https://github.com/jquery/jquery/blob/master/src/event.js#L466). var which = e.which, button = e.button; if (!which && button !== undefined) { return (!button & 1) && (!button & 2) && (button & 4); } else if (which === 2) { return true; } return false; }; }, {}], 187: [function(require, module, exports) { /** * Bind `el` event `type` to `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.bind = function(el, type, fn, capture){ if (el.addEventListener) { el.addEventListener(type, fn, capture || false); } else { el.attachEvent('on' + type, fn); } return fn; }; /** * Unbind `el` event `type`'s callback `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.unbind = function(el, type, fn, capture){ if (el.removeEventListener) { el.removeEventListener(type, fn, capture || false); } else { el.detachEvent('on' + type, fn); } return fn; }; }, {}], 188: [function(require, module, exports) { /** * prevent default on the given `e`. * * examples: * * anchor.onclick = prevent; * anchor.onclick = function(e){ * if (something) return prevent(e); * }; * * @param {Event} e */ module.exports = function(e){ e = e || window.event return e.preventDefault ? e.preventDefault() : e.returnValue = false; }; }, {}], 189: [function(require, module, exports) { /** * Module dependencies. */ var encode = encodeURIComponent; var decode = decodeURIComponent; var trim = require('trim'); var type = require('type'); /** * Parse the given query `str`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(str){ if ('string' != typeof str) return {}; str = trim(str); if ('' == str) return {}; if ('?' == str.charAt(0)) str = str.slice(1); var obj = {}; var pairs = str.split('&'); for (var i = 0; i < pairs.length; i++) { var parts = pairs[i].split('='); var key = decode(parts[0]); var m; if (m = /(\w+)\[(\d+)\]/.exec(key)) { obj[m[1]] = obj[m[1]] || []; obj[m[1]][m[2]] = decode(parts[1]); continue; } obj[parts[0]] = null == parts[1] ? '' : decode(parts[1]); } return obj; }; /** * Stringify the given `obj`. * * @param {Object} obj * @return {String} * @api public */ exports.stringify = function(obj){ if (!obj) return ''; var pairs = []; for (var key in obj) { var value = obj[key]; if ('array' == type(value)) { for (var i = 0; i < value.length; ++i) { pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i])); } continue; } pairs.push(encode(key) + '=' + encode(obj[key])); } return pairs.join('&'); }; }, {"trim":163,"type":7}], 191: [function(require, module, exports) { var debug = require('debug')('analytics:user'); var Entity = require('./entity'); var inherit = require('inherit'); var bind = require('bind'); var cookie = require('./cookie'); /** * User defaults */ User.defaults = { persist: true, cookie: { key: 'ajs_user_id', oldKey: 'ajs_user' }, localStorage: { key: 'ajs_user_traits' } }; /** * Initialize a new `User` with `options`. * * @param {Object} options */ function User (options) { this.defaults = User.defaults; this.debug = debug; Entity.call(this, options); } /** * Inherit `Entity` */ inherit(User, Entity); /** * Load saved user `id` or `traits` from storage. */ User.prototype.load = function () { if (this._loadOldCookie()) return; Entity.prototype.load.call(this); }; /** * BACKWARDS COMPATIBILITY: Load the old user from the cookie. * * @return {Boolean} * @api private */ User.prototype._loadOldCookie = function () { var user = cookie.get(this._options.cookie.oldKey); if (!user) return false; this.id(user.id); this.traits(user.traits); cookie.remove(this._options.cookie.oldKey); return true; }; /** * Expose the user singleton. */ module.exports = bind.all(new User()); /** * Expose the `User` constructor. */ module.exports.User = User; }, {"debug":184,"./entity":197,"inherit":198,"bind":182,"./cookie":183}], 5: [function(require, module, exports) { module.exports = '2.3.17'; }, {}]}, {}, {"1":"analytics"})
app/components/IssueIcon/index.js
Dmitry-N-Medvedev/motor-collection
import React from 'react'; function IssueIcon(props) { return ( <svg height="1em" width="0.875em" className={props.className} > <path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7S10.14 13.7 7 13.7 1.3 11.14 1.3 8s2.56-5.7 5.7-5.7m0-1.3C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7S10.86 1 7 1z m1 3H6v5h2V4z m0 6H6v2h2V10z" /> </svg> ); } IssueIcon.propTypes = { className: React.PropTypes.string, }; export default IssueIcon;
js/src/views/Settings/Proxy/proxy.js
kushti/mpt
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React, { Component } from 'react'; import { Container, ContainerTitle } from '../../../ui'; import layout from '../layout.css'; import styles from './proxy.css'; export default class Proxy extends Component { render () { const proxyurl = 'http://127.0.0.1:8080/proxy/proxy.pac'; return ( <Container> <ContainerTitle title='Proxy' /> <div className={ layout.layout }> <div className={ layout.overview }> <div>The proxy setup allows you to access Parity and all associated decentralized applications via memororable addresses.</div> </div> <div className={ layout.details }> <div className={ styles.details }> <div>Instead of accessing Parity via the IP address and port, you will be able to access it via the .parity subdomain, by visiting <span className={ layout.console }>http://home.parity/</span>. To setup subdomain-based routing, you need to add the relevant proxy entries to your browser,</div> <div className={ layout.center }><a href={ proxyurl } target='_blank'>{ proxyurl }</a></div> <div>To learn how to configure the proxy, instructions are provided for <a href='https://blogs.msdn.microsoft.com/ieinternals/2013/10/11/understanding-web-proxy-configuration/' target='_blank'>Windows</a>, <a href='https://support.apple.com/kb/PH18553?locale=en_US' target='_blank'>Max OS X</a> or <a href='http://xmodulo.com/how-to-set-up-proxy-auto-config-on-ubuntu-desktop.html' target='_blank'>Ubuntu</a>.</div> </div> </div> </div> </Container> ); } }
ajax/libs/react-bootstrap-typeahead/0.8.4/react-bootstrap-typeahead.min.js
sreym/cdnjs
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports.ReactBootstrapTypeahead=t(require("react"),require("react-dom")):e.ReactBootstrapTypeahead=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,exports,t){"use strict";var n=t(28);e.exports=n},function(t,exports){t.exports=e},function(e,exports,t){var n,r;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ !function(){"use strict";function t(){for(var e=[],n=0;n<arguments.length;n++){var r=arguments[n];if(r){var i=typeof r;if("string"===i||"number"===i)e.push(r);else if(Array.isArray(r))e.push(t.apply(null,r));else if("object"===i)for(var s in r)o.call(r,s)&&r[s]&&e.push(s)}}return e.join(" ")}var o={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=t:(n=[],r=function(){return t}.apply(exports,n),!(void 0!==r&&(e.exports=r)))}()},function(e,exports){"use strict";e.exports={BACKSPACE:8,TAB:9,RETURN:13,ESC:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40}},function(e,exports,t){function n(e,t){for(var n=e.length;n--;)if(r(e[n][0],t))return n;return-1}var r=t(60);e.exports=n},function(e,exports){e.exports=t},function(e,exports){var t=Array.isArray;e.exports=t},function(e,exports){function t(e){return!!e&&"object"==typeof e}e.exports=t},function(e,exports,t){var n=t(16),r=Object.keys,o=n(r,Object);e.exports=o},function(e,exports){function t(e){return e}e.exports=t},function(e,exports){function t(e){return r.call(e)}var n=Object.prototype,r=n.toString;e.exports=t},function(e,exports){function t(){this.__data__=[]}e.exports=t},function(e,exports,t){function n(e){var t=this.__data__,n=r(t,e);if(n<0)return!1;var o=t.length-1;return n==o?t.pop():i.call(t,n,1),!0}var r=t(4),o=Array.prototype,i=o.splice;e.exports=n},function(e,exports,t){function n(e){var t=this.__data__,n=r(t,e);return n<0?void 0:t[n][1]}var r=t(4);e.exports=n},function(e,exports,t){function n(e){return r(this.__data__,e)>-1}var r=t(4);e.exports=n},function(e,exports,t){function n(e,t){var n=this.__data__,o=r(n,e);return o<0?n.push([e,t]):n[o][1]=t,this}var r=t(4);e.exports=n},function(e,exports){function t(e,t){return function(n){return e(t(n))}}e.exports=t},function(e,exports,t){function n(e){return null!=e&&i(r(e))&&!o(e)}var r=t(54),o=t(19),i=t(67);e.exports=n},function(e,exports,t){function n(e,t){return r(e,t)}var r=t(44);e.exports=n},function(e,exports,t){function n(e){var t=r(e)?a.call(e):"";return t==o||t==i}var r=t(20),o="[object Function]",i="[object GeneratorFunction]",s=Object.prototype,a=s.toString;e.exports=n},function(e,exports){function t(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=t},function(e,exports){function t(){}e.exports=t},function(e,exports,t){var n=t(39),r=t(42),o=t(46),i=t(49),s=t(59),a=i(function(e,t){return null==e?{}:o(e,n(r(t,1),s))});e.exports=a},function(e,exports,t){var n,r;!function(o){"use strict";function i(e,t,n){return function(e){var r=t.createClass({statics:{getClass:function(){return e.getClass?e.getClass():e}},getInstance:function(){return this.refs.instance},__outsideClickHandler:function(e){},componentDidMount:function(){var e=this.getInstance();if("function"!=typeof e.handleClickOutside)throw new Error("Component lacks a handleClickOutside(event) function for processing outside click events.");var t=this.__outsideClickHandler=d(n.findDOMNode(e),e,this.props.outsideClickIgnoreClass||l,this.props.preventDefault||!1,this.props.stopPropagation||!1),r=a.length;a.push(this),u[r]=t,this.props.disableOnClickOutside||this.enableOnClickOutside()},componentWillReceiveProps:function(e){this.props.disableOnClickOutside&&!e.disableOnClickOutside?this.enableOnClickOutside():!this.props.disableOnClickOutside&&e.disableOnClickOutside&&this.disableOnClickOutside()},componentWillUnmount:function(){this.disableOnClickOutside(),this.__outsideClickHandler=!1;var e=a.indexOf(this);e>-1&&(u[e]&&u.splice(e,1),a.splice(e,1))},enableOnClickOutside:function(){var e=this.__outsideClickHandler;if("undefined"!=typeof document){var t=this.props.eventTypes||p;t.forEach||(t=[t]),t.forEach(function(t){document.addEventListener(t,e)})}},disableOnClickOutside:function(){var e=this.__outsideClickHandler;if("undefined"!=typeof document){var t=this.props.eventTypes||p;t.forEach||(t=[t]),t.forEach(function(t){document.removeEventListener(t,e)})}},render:function(){var n=this.props,r={ref:"instance"};return Object.keys(this.props).forEach(function(e){r[e]=n[e]}),t.createElement(e,r)}});return function(e,t){var n=e.displayName||e.name||"Component";t.displayName="OnClickOutside("+n+")"}(e,r),r}}function s(o,i){n=[t(1),t(5)],r=function(e,t){return i(o,e,t)}.apply(exports,n),!(void 0!==r&&(e.exports=r))}var a=[],u=[],l="ignore-react-onclickoutside",p=["mousedown","touchstart"],c=function(e,t,n){return e===t||(e.correspondingElement?e.correspondingElement.classList.contains(n):e.classList.contains(n))},d=function(e,t,n,r,o){return function(i){r&&i.preventDefault(),o&&i.stopPropagation();for(var s=i.target,a=!1;s.parentNode;){if(a=c(s,e,n))return;s=s.parentNode}s===document&&t.handleClickOutside.bind(t,i)()}};s(o,i)}(this)},function(e,exports,t){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(exports,"__esModule",{value:!0});var r=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},o=t(2),i=n(o),s=t(1),a=n(s),u=function(e){return a.default.createElement("ul",r({},e,{className:(0,i.default)("dropdown-menu",e.className)}),e.children)};exports.default=u},function(e,exports,t){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(exports,"__esModule",{value:!0});var r=t(21),o=n(r),i=t(2),s=n(i),a=t(32),u=n(a),l=t(1),p=n(l),c=t(5),d=p.default.createClass({displayName:"MenuItem",getDefaultProps:function(){return{onClick:o.default}},componentWillReceiveProps:function(e){e.active&&(0,u.default)((0,c.findDOMNode)(this))},render:function(){var e=this.props,t=e.active,n=e.children,r=e.className,o=e.disabled;return p.default.createElement("li",{className:(0,s.default)({active:t,disabled:o},r)},p.default.createElement("a",{href:"#",onClick:this._handleClick},n))},_handleClick:function(e){var t=this.props,n=t.disabled,r=t.onClick;e.preventDefault(),!n&&r(e)}});exports.default=d},function(e,exports,t){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(exports,"__esModule",{value:!0});var r=t(1),o=n(r),i=t(5),s=t(2),a=n(s),u=t(3),l=n(u),p=t(23),c=n(p),d=o.default.createClass({displayName:"Token",propTypes:{onRemove:r.PropTypes.func},getInitialState:function(){return{selected:!1}},render:function(){return this.props.onRemove&&!this.props.disabled?this._renderRemoveableToken():this._renderToken()},_renderRemoveableToken:function(){return o.default.createElement("div",{className:(0,a.default)("token","token-removeable",{"token-selected":this.state.selected},this.props.className),onBlur:this._handleBlur,onClick:this._handleSelect,onFocus:this._handleSelect,onKeyDown:this._handleKeyDown,tabIndex:0},this.props.children,o.default.createElement("span",{className:"close-button",onClick:this._handleRemove,role:"button"},"×"))},_renderToken:function(){var e=this.props,t=e.className,n=e.disabled,r=e.href,i=(0,a.default)("token",t);return r?o.default.createElement("a",{className:i,disabled:n,href:r},this.props.children):o.default.createElement("div",{className:i,disabled:n},this.props.children)},_handleBlur:function(e){(0,i.findDOMNode)(this).blur(),this.setState({selected:!1})},_handleKeyDown:function(e){switch(e.keyCode){case l.default.BACKSPACE:this.state.selected&&(e.preventDefault(),this._handleRemove())}},handleClickOutside:function(e){this._handleBlur()},_handleRemove:function(e){this.props.onRemove&&this.props.onRemove()},_handleSelect:function(e){e.stopPropagation(),this.setState({selected:!0})}});exports.default=(0,c.default)(d)},function(e,exports,t){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(exports,"__esModule",{value:!0});var r=t(75),o=n(r),i=t(1),s=n(i),a=t(26),u=n(a),l=t(2),p=n(l),c=t(5),d=t(3),f=s.default.createClass({displayName:"TokenizerInput",propTypes:{disabled:i.PropTypes.bool,labelKey:i.PropTypes.string,placeholder:i.PropTypes.string,selected:i.PropTypes.array},getInitialState:function(){return{isFocused:!1}},render:function(){var e=this.props,t=e.disabled,n=e.placeholder,r=e.selected,i=e.text;return s.default.createElement("div",{className:(0,p.default)("bootstrap-tokenizer","clearfix","form-control",{focus:this.state.isFocused}),disabled:t,onClick:this._handleInputFocus,onFocus:this._handleInputFocus,style:{cursor:"text",height:"auto"},tabIndex:-1},r.map(this._renderToken),s.default.createElement(o.default,{className:"bootstrap-tokenizer-input",disabled:t,inputStyle:{backgroundColor:"inherit",border:0,boxShadow:"none",cursor:"inherit",outline:"none",padding:0},onBlur:this._handleBlur,onChange:this._handleChange,onFocus:this.props.onFocus,onKeyDown:this._handleKeydown,placeholder:r.length?null:n,ref:"input",type:"text",value:i}))},blur:function(){this.refs.input.blur()},focus:function(){this._handleInputFocus()},_renderToken:function(e,t){var n=this.props,r=n.disabled,o=n.labelKey,i=n.onRemove;return s.default.createElement(u.default,{disabled:r,key:t,onRemove:function(){return i(e)}},e[o])},_handleBlur:function(e){this.setState({isFocused:!1}),this.props.onBlur(e)},_handleChange:function(e){this.props.onChange(e.target.value)},_handleKeydown:function(e){switch(e.keyCode){case d.BACKSPACE:var t=(0,c.findDOMNode)(this.refs.input);if(t&&t.contains(document.activeElement)&&!this.props.text){var n=t.previousSibling;n&&n.focus()}}this.props.onKeyDown(e)},_handleInputFocus:function(e){return this.props.disabled?void e.target.blur():(this.refs.input.focus(),void this.setState({isFocused:!0}))}});exports.default=f},function(e,exports,t){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}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}Object.defineProperty(exports,"__esModule",{value:!0});var o=t(22),i=n(o),s=t(21),a=n(s),u=t(18),l=n(u),p=t(66),c=n(p),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},f=t(1),h=n(f),v=t(27),y=n(v),g=t(29),m=n(g),b=t(30),x=n(b),_=t(31),C=n(_),P=t(23),T=n(P),O=t(3),w=h.default.createClass({displayName:"Typeahead",propTypes:{align:f.PropTypes.oneOf(["justify","left","right"]),allowNew:f.PropTypes.bool,defaultSelected:f.PropTypes.array,disabled:f.PropTypes.bool,emptyLabel:f.PropTypes.string,labelKey:f.PropTypes.string,maxHeight:f.PropTypes.number,minLength:f.PropTypes.number,multiple:f.PropTypes.bool,newSelectionPrefix:f.PropTypes.string,onBlur:f.PropTypes.func,onChange:f.PropTypes.func,onInputChange:f.PropTypes.func,options:f.PropTypes.array.isRequired,paginateResults:f.PropTypes.number,paginationText:f.PropTypes.string,placeholder:f.PropTypes.string,renderMenuItemChildren:f.PropTypes.func,selected:f.PropTypes.array},getDefaultProps:function(){return{allowNew:!1,defaultSelected:[],labelKey:"label",onBlur:a.default,onChange:a.default,onInputChange:a.default,minLength:0,multiple:!1,selected:[]}},getInitialState:function(){var e=this.props.defaultSelected,t=this.props.selected.slice();return(0,c.default)(e)||(t=e),{activeIndex:-1,selected:t,showMenu:!1,text:""}},componentWillReceiveProps:function(e){var t=e.multiple,n=e.selected;(0,l.default)(n,this.props.selected)||this.setState({selected:n}),t!==this.props.multiple&&this.setState({text:""})},render:function(){var e=this.props,t=e.options,n=r(e,["options"]),o=this.state,i=o.selected,s=o.text,a=(0,C.default)(t,s,i,n);return h.default.createElement("div",{className:"bootstrap-typeahead open",style:{position:"relative"}},this._renderInput(a),this._renderMenu(a))},blur:function(){this.refs.input.blur()},clear:function(){var e=this.getInitialState(),t=e.activeIndex,n=e.showMenu,r=[],o="";this.setState({activeIndex:t,selected:r,showMenu:n,text:o}),this.props.onChange(r),this.props.onInputChange(o)},focus:function(){this.refs.input.focus()},_renderInput:function(e){var t=this,n=this.props,r=n.labelKey,o=n.multiple,s=this.state,a=s.activeIndex,u=s.selected,l=s.text,p=o?y.default:m.default,c=(0,i.default)(this.props,["disabled","placeholder"]);return h.default.createElement(p,d({},c,{activeIndex:a,labelKey:r,onAdd:this._handleAddOption,onBlur:this._handleBlur,onChange:this._handleTextChange,onFocus:this._handleFocus,onKeyDown:function(n){return t._handleKeydown(e,n)},onRemove:this._handleRemoveOption,options:e,ref:"input",selected:u.slice(),text:l}))},_renderMenu:function(e){var t=this.props,n=t.labelKey,r=t.minLength,o=this.state,s=o.activeIndex,a=o.showMenu,u=o.text;if(!(a&&u.length>=r))return null;var l=(0,i.default)(this.props,["align","emptyLabel","maxHeight","newSelectionPrefix","paginationText","renderMenuItemChildren"]);return h.default.createElement(x.default,d({},l,{activeIndex:s,initialResultCount:this.props.paginateResults,labelKey:n,onClick:this._handleAddOption,options:e,text:u}))},_handleBlur:function(e){this.props.onBlur(e)},_handleFocus:function(){this.setState({showMenu:!0})},_handleTextChange:function(e){var t=this.getInitialState(),n=t.activeIndex;this.setState({activeIndex:n,showMenu:!0,text:e}),this.props.onInputChange(e)},_handleKeydown:function(e,t){var n=this.state.activeIndex;switch(t.keyCode){case O.UP:case O.DOWN:if(!this.state.showMenu)return;t.preventDefault(),n+=t.keyCode===O.UP?-1:1,n===e.length?n=-1:n===-2&&(n=e.length-1),this.setState({activeIndex:n});break;case O.ESC:case O.TAB:t.keyCode===O.ESC&&t.preventDefault(),this._hideDropdown();break;case O.RETURN:if(t.preventDefault(),this.state.showMenu){var r=e[n];r&&this._handleAddOption(r)}}},_handleAddOption:function(e){var t=this.props,n=t.multiple,r=t.labelKey,o=t.onChange,i=t.onInputChange,s=void 0,a=void 0;n?(s=this.state.selected.concat(e),a=""):(s=[e],a=e[r]),this.setState({selected:s,text:a}),this._hideDropdown(),o(s),i(a)},_handleRemoveOption:function(e){var t=this.state.selected.slice();t=t.filter(function(t){return!(0,l.default)(t,e)}),this.focus(),this.setState({selected:t}),this._hideDropdown(),this.props.onChange(t)},handleClickOutside:function(e){this._hideDropdown()},_hideDropdown:function(){var e=this.getInitialState(),t=e.activeIndex,n=e.showMenu;this.setState({activeIndex:t,showMenu:n})}});exports.default=(0,T.default)(w)},function(e,exports,t){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(exports,"__esModule",{value:!0});var r=t(22),o=n(r),i=t(63),s=n(i),a=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},u=t(1),l=n(u),p=t(2),c=n(p),d=t(3),f=l.default.createClass({displayName:"TypeaheadInput",propTypes:{disabled:u.PropTypes.bool,labelKey:u.PropTypes.string,onBlur:u.PropTypes.func,onChange:u.PropTypes.func,onFocus:u.PropTypes.func,options:u.PropTypes.array,placeholder:u.PropTypes.string,selected:u.PropTypes.array,text:u.PropTypes.string},getInitialState:function(){return{isFocused:!1}},componentDidUpdate:function(e,t){if(this.props.activeIndex!==e.activeIndex){var n=this._getInputText();this.refs.input.selectionStart=n.length}},render:function(){var e=this.props,t=e.className,n=e.disabled,r=e.selected,i=(0,o.default)(this.props,["disabled","onFocus","placeholder"]);return l.default.createElement("div",{className:(0,c.default)("bootstrap-typeahead-input",t),onClick:this._handleInputFocus,onFocus:this._handleInputFocus,style:{outline:"none"},tabIndex:-1},l.default.createElement("input",a({},i,{className:(0,c.default)("bootstrap-typeahead-input-main","form-control",{"has-selection":!!r.length}),onBlur:this._handleBlur,onChange:this._handleChange,onKeyDown:this._handleKeydown,ref:"input",style:{backgroundColor:!n&&"transparent",display:"block",position:"relative",zIndex:1},type:"text",value:this._getInputText()})),l.default.createElement("input",{className:"bootstrap-typeahead-input-hint form-control",style:{borderColor:"transparent",bottom:0,boxShadow:"none",display:"block",opacity:.6,position:"absolute",top:0,width:"100%",zIndex:0},tabIndex:-1,type:"text",value:this._getHintText()}))},blur:function(){this.refs.input.blur()},focus:function(){this._handleInputFocus()},_getHintText:function(){var e=this.props,t=e.activeIndex,n=e.options,r=e.labelKey,o=e.selected,i=e.text,a=(0,s.default)(n),u=a&&a[r];return this.state.isFocused&&i&&t===-1&&!o.length&&u&&0===u.toLowerCase().indexOf(i.toLowerCase())?i+u.slice(i.length,u.length):""},_getInputText:function(){var e=this.props,t=e.activeIndex,n=e.labelKey,r=e.options,o=e.selected,i=e.text,a=!!o.length&&(0,s.default)(o);return a?a[n]:t>=0?r[t][n]:i},_handleBlur:function(e){this.setState({isFocused:!1}),this.props.onBlur(e)},_handleChange:function(e){var t=this.props,n=t.onRemove,r=t.selected;!!r.length&&n((0,s.default)(r)),this.props.onChange(e.target.value)},_handleInputFocus:function(e){this.setState({isFocused:!0}),this.refs.input.focus()},_handleKeydown:function(e){var t=this.props,n=t.activeIndex,r=t.options,o=t.onAdd,i=t.selected,a=t.text;switch(e.keyCode){case d.RIGHT:case d.TAB:var u=this.refs.input.selectionStart,l=!!this._getHintText();if((l||n!==-1)&&!i.length&&(e.keyCode!==d.RIGHT||u===a.length)){e.preventDefault();var p=l?(0,s.default)(r):r[n];o&&o(p)}}this.props.onKeyDown(e)}});exports.default=f},function(e,exports,t){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(exports,"__esModule",{value:!0});var r=t(2),o=n(r),i=t(73),s=n(i),a=t(1),u=n(a),l=t(24),p=n(l),c=t(25),d=n(c),f=u.default.createClass({displayName:"TypeaheadMenu",propTypes:{activeIndex:a.PropTypes.number,align:a.PropTypes.oneOf(["justify","left","right"]),emptyLabel:a.PropTypes.string,initialResultCount:a.PropTypes.number,labelKey:a.PropTypes.string.isRequired,maxHeight:a.PropTypes.number,newSelectionPrefix:a.PropTypes.string,options:a.PropTypes.array,paginationText:a.PropTypes.string,renderMenuItemChildren:a.PropTypes.func,text:a.PropTypes.string.isRequired},getDefaultProps:function(){return{align:"justify",emptyLabel:"No matches found.",initialResultCount:100,maxHeight:300,newSelectionPrefix:"New selection: ",paginationText:"Display additional results..."}},getInitialState:function(){return{resultCount:this.props.initialResultCount}},render:function(){var e=this.props,t=e.align,n=e.emptyLabel,r=e.maxHeight,i=e.options,s=i.slice(0,this.state.resultCount||i.length),a=s.length?s.map(this._renderMenuItem):u.default.createElement(d.default,{disabled:!0},n);return u.default.createElement(p.default,{className:(0,o.default)("bootstrap-typeahead-menu",{"dropdown-menu-justify":"justify"===t,"dropdown-menu-right":"right"===t}),style:{maxHeight:r+"px",overflow:"auto"}},a,this._renderPaginationMenuItem(s))},_renderMenuItem:function(e,t){var n=this.props,r=n.activeIndex,o=n.labelKey,i=n.newSelectionPrefix,a=n.onClick,l=n.renderMenuItemChildren,p=n.text,c={active:t===r,key:t,onClick:function(){return a(e)}};return e.customOption?u.default.createElement(d.default,c,i,u.default.createElement(s.default,{search:p},e[o])):l?u.default.createElement(d.default,c,l(this.props,e,t)):u.default.createElement(d.default,c,u.default.createElement(s.default,{search:p},e[o]))},_renderPaginationMenuItem:function(e){var t=this.props,n=t.options,r=t.paginationText;if(e.length<n.length)return[u.default.createElement("li",{className:"divider",key:"pagination-item-divider",role:"separator"}),u.default.createElement(d.default,{className:"bootstrap-typeahead-menu-paginator",key:"pagination-item",onClick:this._handlePagination},r)]},_handlePagination:function(e){var t=this.state.resultCount+this.props.initialResultCount;this.setState({resultCount:t})}});exports.default=f},function(e,exports,t){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function r(){var e=arguments.length<=0||void 0===arguments[0]?[]:arguments[0],t=arguments.length<=1||void 0===arguments[1]?"":arguments[1],n=arguments.length<=2||void 0===arguments[2]?[]:arguments[2],r=arguments.length<=3||void 0===arguments[3]?{}:arguments[3],o=r.allowNew,s=r.labelKey,u=r.minLength,p=r.multiple;if(t.length<u)return[];var c=!1,d=e.filter(function(e){var r=e[s];if(!r||"string"!=typeof r)throw new Error("One or more options does not have a valid label string. Please check the `labelKey` prop to ensure that it matches the correct option key and provides a string for filtering and display.");return r===t&&(c=!0),!(r.toLowerCase().indexOf(t.toLowerCase())===-1||p&&(0,l.default)(n,function(t){return(0,a.default)(t,e)}))});if(o&&t.trim()&&(!d.length||!c)){var f={id:(0,i.default)("new-id-"),customOption:!0};f[s]=t,d.push(f)}return d}Object.defineProperty(exports,"__esModule",{value:!0});var o=t(72),i=n(o),s=t(18),a=n(s),u=t(61),l=n(u);exports.default=r},function(e,exports){"use strict";function t(e){if(Element.prototype.scrollIntoViewIfNeeded)return void e.scrollIntoViewIfNeeded();var t=e.getBoundingClientRect(),n=e.parentNode,r=n.getBoundingClientRect(),o=window.getComputedStyle(n,null),i=parseInt(o.getPropertyValue("border-top-width"));(t.top<r.top||t.bottom>r.bottom)&&(n.scrollTop=e.offsetTop-n.offsetTop-n.clientHeight/2-i+e.clientHeight/2)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=t},function(e,exports){e.exports=function(e){var t={},n=arguments[1];if("string"==typeof n){n={};for(var r=1;r<arguments.length;r++)n[arguments[r]]=!0}for(var o in e)n[o]||(t[o]=e[o]);return t}},function(e,exports){"use strict";var t=/[|\\{}()[\]^$+*?.]/g;e.exports=function(e){if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(t,"\\$&")}},function(e,exports,t){function n(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var r=t(11),o=t(12),i=t(13),s=t(14),a=t(15);n.prototype.clear=r,n.prototype.delete=o,n.prototype.get=i,n.prototype.has=s,n.prototype.set=a,e.exports=n},function(e,exports,t){function n(e){var t=-1,n=e?e.length:0;for(this.__data__=new r;++t<n;)this.add(e[t])}var r=t(35),o=t(57),i=t(58);n.prototype.add=n.prototype.push=o,n.prototype.has=i,e.exports=n},function(e,exports,t){function n(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var r=t(11),o=t(12),i=t(13),s=t(14),a=t(15);n.prototype.clear=r,n.prototype.delete=o,n.prototype.get=i,n.prototype.has=s,n.prototype.set=a,e.exports=n},function(e,exports){function t(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}e.exports=t},function(e,exports){function t(e,t){for(var n=-1,r=e?e.length:0,o=Array(r);++n<r;)o[n]=t(e[n],n,e);return o}e.exports=t},function(e,exports){function t(e,t){for(var n=-1,r=e?e.length:0;++n<r;)if(t(e[n],n,e))return!0;return!1}e.exports=t},function(e,exports){function t(e,t,n,r){for(var o=e.length,i=n+(r?1:-1);r?i--:++i<o;)if(t(e[i],i,e))return i;return-1}e.exports=t},function(e,exports){function t(e){return e&&e.length?e[0]:void 0}e.exports=t},function(e,exports,t){function n(e,t){return null!=e&&(i.call(e,t)||"object"==typeof e&&t in e&&null===r(e))}var r=t(55),o=Object.prototype,i=o.hasOwnProperty;e.exports=n},function(e,exports,t){function n(e,t,s,a,u){return e===t||(null==e||null==t||!o(e)&&!i(t)?e!==e&&t!==t:r(e,t,n,s,a,u))}var r=t(45),o=t(20),i=t(7);e.exports=n},function(e,exports,t){function n(e,t,n,v,g,m){var b=u(e),x=u(t),_=f,C=f;b||(_=a(e),_=_==d?h:_),x||(C=a(t),C=C==d?h:C);var P=_==h&&!l(e),T=C==h&&!l(t),O=_==C;if(O&&!P)return m||(m=new r),b||p(e)?o(e,t,n,v,g,m):i(e,t,_,n,v,g,m);if(!(g&c)){var w=P&&y.call(e,"__wrapped__"),S=T&&y.call(t,"__wrapped__");if(w||S){var I=w?e.value():e,k=S?t.value():t;return m||(m=new r),n(I,k,v,g,m)}}return!!O&&(m||(m=new r),s(e,t,n,v,g,m))}var r=t(37),o=t(51),i=t(52),s=t(53),a=t(10),u=t(6),l=t(56),p=t(69),c=2,d="[object Arguments]",f="[object Array]",h="[object Object]",v=Object.prototype,y=v.hasOwnProperty;e.exports=n},function(e,exports,t){function n(e,t){return e=Object(e),r(e,t,function(t,n){return n in e})}var r=t(47);e.exports=n},function(e,exports){function t(e,t,n){for(var r=-1,o=t.length,i={};++r<o;){var s=t[r],a=e[s];n(a,s)&&(i[s]=a)}return i}e.exports=t},function(e,exports){function t(e){return function(t){return null==t?void 0:t[e]}}e.exports=t},function(e,exports,t){function n(e,t){return t=o(void 0===t?e.length-1:t,0),function(){for(var n=arguments,i=-1,s=o(n.length-t,0),a=Array(s);++i<s;)a[i]=n[t+i];i=-1;for(var u=Array(t+1);++i<t;)u[i]=n[i];return u[t]=a,r(e,this,u)}}var r=t(38),o=Math.max;e.exports=n},function(e,exports,t){function n(e){return function(t,n,s){var a=Object(t);if(!o(t)){var u=r(n,3);t=i(t),n=function(e){return u(a[e],e,a)}}var l=e(t,n,s);return l>-1?a[u?t[l]:l]:void 0}}var r=t(9),o=t(17),i=t(8);e.exports=n},function(e,exports,t){function n(e,t,n,a,u,l){var p=u&s,c=e.length,d=t.length;if(c!=d&&!(p&&d>c))return!1;var f=l.get(e);if(f&&l.get(t))return f==t;var h=-1,v=!0,y=u&i?new r:void 0;for(l.set(e,t),l.set(t,e);++h<c;){var g=e[h],m=t[h];if(a)var b=p?a(m,g,h,t,e,l):a(g,m,h,e,t,l);if(void 0!==b){if(b)continue;v=!1;break}if(y){if(!o(t,function(e,t){if(!y.has(t)&&(g===e||n(g,e,a,u,l)))return y.add(t)})){v=!1;break}}else if(g!==m&&!n(g,m,a,u,l)){v=!1;break}}return l.delete(e),l.delete(t),v}var r=t(36),o=t(40),i=1,s=2;e.exports=n},function(e,exports){function t(e,t){return e===t||e!==e&&t!==t}e.exports=t},function(e,exports,t){function n(e,t,n,s,a,u){var l=a&i,p=o(e),c=p.length,d=o(t),f=d.length;if(c!=f&&!l)return!1;for(var h=c;h--;){var v=p[h];if(!(l?v in t:r(t,v)))return!1}var y=u.get(e);if(y&&u.get(t))return y==t;var g=!0;u.set(e,t),u.set(t,e);for(var m=l;++h<c;){v=p[h];var b=e[v],x=t[v];if(s)var _=l?s(x,b,v,t,e,u):s(b,x,v,e,t,u);if(!(void 0===_?b===x||n(b,x,s,a,u):_)){g=!1;break}m||(m="constructor"==v)}if(g&&!m){var C=e.constructor,P=t.constructor;C!=P&&"constructor"in e&&"constructor"in t&&!("function"==typeof C&&C instanceof C&&"function"==typeof P&&P instanceof P)&&(g=!1)}return u.delete(e),u.delete(t),g}var r=t(43),o=t(8),i=2;e.exports=n},function(e,exports,t){var n=t(48),r=n("length");e.exports=r},function(e,exports,t){var n=t(16),r=Object.getPrototypeOf,o=n(r,Object);e.exports=o},function(e,exports){function t(){return!1}e.exports=t},function(e,exports){function t(e){return this.__data__.set(e,n),this}var n="__lodash_hash_undefined__";e.exports=t},function(e,exports){function t(e){return this.__data__.has(e)}e.exports=t},function(e,exports){function t(e){return e}e.exports=t},function(e,exports){function t(e,t){return e===t||e!==e&&t!==t}e.exports=t},function(e,exports,t){var n=t(50),r=t(62),o=n(r);e.exports=o},function(e,exports,t){function n(e,t,n){var a=e?e.length:0;if(!a)return-1;var u=null==n?0:i(n);return u<0&&(u=s(a+u,0)),r(e,o(t,3),u)}var r=t(41),o=t(9),i=t(70),s=Math.max;e.exports=n},function(e,exports){function t(e){return e&&e.length?e[0]:void 0}e.exports=t},function(e,exports){function t(){return!1}e.exports=t},function(e,exports){function t(){return!1}e.exports=t},function(e,exports,t){function n(e){if(s(e)&&(i(e)||p(e)||u(e.splice)||o(e)||a(e)))return!e.length;if(l(e)){var t=r(e);if(t==d||t==f)return!e.size}for(var n in e)if(v.call(e,n))return!1;return!(g&&c(e).length)}var r=t(10),o=t(64),i=t(6),s=t(17),a=t(65),u=t(19),l=t(7),p=t(68),c=t(8),d="[object Map]",f="[object Set]",h=Object.prototype,v=h.hasOwnProperty,y=h.propertyIsEnumerable,g=!y.call({valueOf:1},"valueOf");e.exports=n},function(e,exports){function t(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=n}var n=9007199254740991;e.exports=t},function(e,exports,t){function n(e){return"string"==typeof e||!r(e)&&o(e)&&a.call(e)==i}var r=t(6),o=t(7),i="[object String]",s=Object.prototype,a=s.toString;e.exports=n},function(e,exports){function t(){return!1}e.exports=t},function(e,exports){function t(e){return e}e.exports=t},function(e,exports){function t(e){return e}e.exports=t},function(e,exports,t){function n(e){var t=++o;return r(e)+t}var r=t(71),o=0;e.exports=n},function(e,exports,t){var n=t(1),r=t(74),o=t(34),i=t(33),s=n.createClass({displayName:"Highlighter",count:0,propTypes:{search:n.PropTypes.oneOfType([n.PropTypes.string,n.PropTypes.number,n.PropTypes.bool,r]).isRequired,caseSensitive:n.PropTypes.bool,matchElement:n.PropTypes.string,matchClass:n.PropTypes.string,matchStyle:n.PropTypes.object},getDefaultProps:function(){return{caseSensitive:!1,matchElement:"strong",matchClass:"highlight",matchStyle:{}}},render:function(){var e=i(this.props,"search","caseSensitive","matchElement","matchClass","matchStyle");return n.createElement("span",e,this.renderElement(this.props.children))},renderElement:function(e){if(this.isScalar()&&this.hasSearch()){var t=this.getSearch();return this.highlightChildren(e,t)}return this.props.children},isScalar:function(){return/string|number|boolean/.test(typeof this.props.children)},hasSearch:function(){return"undefined"!=typeof this.props.search&&this.props.search},getSearch:function(){if(this.props.search instanceof RegExp)return this.props.search;var e="";this.props.caseSensitive||(e+="i");var t=this.props.search;return"string"==typeof this.props.search&&(t=o(t)),new RegExp(t,e)},getMatchBoundaries:function(e,t){var n=t.exec(e);if(n)return{first:n.index,last:n.index+n[0].length}},highlightChildren:function(e,t){for(var n=[],r=this.props.matchElement,o=e;o;){if(!t.test(o))return n.push(this.renderPlain(o)),n;var i=this.getMatchBoundaries(o,t),s=o.slice(0,i.first);s&&n.push(this.renderPlain(s));var a=o.slice(i.first,i.last);a&&n.push(this.renderHighlight(a,r)),o=o.slice(i.last)}return n},renderPlain:function(e){return this.count++,n.DOM.span({key:this.count},e)},renderHighlight:function(e){return this.count++,n.DOM[this.props.matchElement]({key:this.count,className:this.props.matchClass,style:this.props.matchStyle},e)}});e.exports=s},function(e,exports){var t=function(e,t,n,r){if(!(e[t]instanceof RegExp)){var o=typeof e[t];return new Error("Invalid "+r+" `"+t+"` of type `"+o+"` "+("supplied to `"+n+"`, expected `RegExp`."))}};e.exports=t},function(e,exports,t){"use strict";var n=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},r=t(1),o={position:"absolute",top:0,left:0,visibility:"hidden",height:0,overflow:"scroll",whiteSpace:"pre"},i=r.createClass({displayName:"AutosizeInput",propTypes:{className:r.PropTypes.string,defaultValue:r.PropTypes.any,inputClassName:r.PropTypes.string,inputStyle:r.PropTypes.object,minWidth:r.PropTypes.oneOfType([r.PropTypes.number,r.PropTypes.string]),onChange:r.PropTypes.func,placeholder:r.PropTypes.string,placeholderIsMinWidth:r.PropTypes.bool,style:r.PropTypes.object,value:r.PropTypes.any},getDefaultProps:function(){return{minWidth:1}},getInitialState:function(){return{inputWidth:this.props.minWidth}},componentDidMount:function(){this.copyInputStyles(),this.updateInputWidth()},componentDidUpdate:function(){this.updateInputWidth()},copyInputStyles:function(){if(this.isMounted()&&window.getComputedStyle){var e=window.getComputedStyle(this.refs.input);if(e){var t=this.refs.sizer;if(t.style.fontSize=e.fontSize,t.style.fontFamily=e.fontFamily,t.style.fontWeight=e.fontWeight,t.style.fontStyle=e.fontStyle,t.style.letterSpacing=e.letterSpacing,this.props.placeholder){var n=this.refs.placeholderSizer;n.style.fontSize=e.fontSize,n.style.fontFamily=e.fontFamily,n.style.fontWeight=e.fontWeight,n.style.fontStyle=e.fontStyle,n.style.letterSpacing=e.letterSpacing}}}},updateInputWidth:function(){if(this.isMounted()&&"undefined"!=typeof this.refs.sizer.scrollWidth){var e=void 0;e=this.props.placeholder&&(!this.props.value||this.props.value&&this.props.placeholderIsMinWidth)?Math.max(this.refs.sizer.scrollWidth,this.refs.placeholderSizer.scrollWidth)+2:this.refs.sizer.scrollWidth+2,e<this.props.minWidth&&(e=this.props.minWidth),e!==this.state.inputWidth&&this.setState({inputWidth:e})}},getInput:function(){return this.refs.input},focus:function(){this.refs.input.focus()},blur:function(){this.refs.input.blur()},select:function(){this.refs.input.select()},render:function(){ var e=this.props.defaultValue||this.props.value||"",t=this.props.style||{};t.display||(t.display="inline-block");var i=n({},this.props.inputStyle);i.width=this.state.inputWidth+"px",i.boxSizing="content-box";var s=n({},this.props);return s.className=this.props.inputClassName,s.style=i,delete s.inputClassName,delete s.inputStyle,delete s.minWidth,delete s.placeholderIsMinWidth,r.createElement("div",{className:this.props.className,style:t},r.createElement("input",n({},s,{ref:"input"})),r.createElement("div",{ref:"sizer",style:o},e),this.props.placeholder?r.createElement("div",{ref:"placeholderSizer",style:o},this.props.placeholder):null)}});e.exports=i}])});
src/components/blog/more-button.js
joefraley/ratticusscript
'use strict' import { Link } from 'react-router' import React from 'react' export const MoreButton = ({ post, type }) => { if (!post) return null else return <Link to={ `/posts/${post}` }>Keep reading more like this...</Link> }
node_modules/react-native/Libraries/Text/Text.js
horizon-z40/RN-homework
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Text * @flow */ 'use strict'; const NativeMethodsMixin = require('react/lib/NativeMethodsMixin'); const Platform = require('Platform'); const React = require('React'); const ReactNativeViewAttributes = require('ReactNativeViewAttributes'); const StyleSheetPropType = require('StyleSheetPropType'); const TextStylePropTypes = require('TextStylePropTypes'); const Touchable = require('Touchable'); const createReactNativeComponentClass = require('react/lib/createReactNativeComponentClass'); const merge = require('merge'); const stylePropType = StyleSheetPropType(TextStylePropTypes); const viewConfig = { validAttributes: merge(ReactNativeViewAttributes.UIView, { isHighlighted: true, numberOfLines: true, ellipsizeMode: true, allowFontScaling: true, selectable: true, }), uiViewClassName: 'RCTText', }; /** * A React component for displaying text. * * `Text` supports nesting, styling, and touch handling. * * In the following example, the nested title and body text will inherit the `fontFamily` from *`styles.baseText`, but the title provides its own additional styles. The title and body will * stack on top of each other on account of the literal newlines: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, Text, StyleSheet } from 'react-native'; * * class TextInANest extends Component { * constructor(props) { * super(props); * this.state = { * titleText: "Bird's Nest", * bodyText: 'This is not really a bird nest.' * }; * } * * render() { * return ( * <Text style={styles.baseText}> * <Text style={styles.titleText} onPress={this.onPressTitle}> * {this.state.titleText}<br /><br /> * </Text> * <Text numberOfLines={5}> * {this.state.bodyText} * </Text> * </Text> * ); * } * } * * const styles = StyleSheet.create({ * baseText: { * fontFamily: 'Cochin', * }, * titleText: { * fontSize: 20, * fontWeight: 'bold', * }, * }); * * // App registration and rendering * AppRegistry.registerComponent('TextInANest', () => TextInANest); * ``` */ const Text = React.createClass({ propTypes: { /** * This can be one of the following values: * * - `head` - The line is displayed so that the end fits in the container and the missing text * at the beginning of the line is indicated by an ellipsis glyph. e.g., "...wxyz" * - `middle` - The line is displayed so that the beginning and end fit in the container and the * missing text in the middle is indicated by an ellipsis glyph. "ab...yz" * - `tail` - The line is displayed so that the beginning fits in the container and the * missing text at the end of the line is indicated by an ellipsis glyph. e.g., "abcd..." * - `clip` - Lines are not drawn past the edge of the text container. * * The default is `tail`. * * `numberOfLines` must be set in conjunction with this prop. * * > `clip` is working only for iOS */ ellipsizeMode: React.PropTypes.oneOf(['head', 'middle', 'tail', 'clip']), /** * Used to truncate the text with an ellipsis after computing the text * layout, including line wrapping, such that the total number of lines * does not exceed this number. * * This prop is commonly used with `ellipsizeMode`. */ numberOfLines: React.PropTypes.number, /** * Invoked on mount and layout changes with * * `{nativeEvent: {layout: {x, y, width, height}}}` */ onLayout: React.PropTypes.func, /** * This function is called on press. * * e.g., `onPress={() => console.log('1st')}`` */ onPress: React.PropTypes.func, /** * This function is called on long press. * * e.g., `onLongPress={this.increaseSize}>`` */ onLongPress: React.PropTypes.func, /** * Lets the user select text, to use the native copy and paste functionality. * * @platform android */ selectable: React.PropTypes.bool, /** * When `true`, no visual change is made when text is pressed down. By * default, a gray oval highlights the text on press down. * * @platform ios */ suppressHighlighting: React.PropTypes.bool, style: stylePropType, /** * Used to locate this view in end-to-end tests. */ testID: React.PropTypes.string, /** * Specifies whether fonts should scale to respect Text Size accessibility setting on iOS. The * default is `true`. * * @platform ios */ allowFontScaling: React.PropTypes.bool, /** * When set to `true`, indicates that the view is an accessibility element. The default value * for a `Text` element is `true`. * * See the * [Accessibility guide](/react-native/docs/accessibility.html#accessible-ios-android) * for more information. */ accessible: React.PropTypes.bool, }, getDefaultProps(): Object { return { accessible: true, allowFontScaling: true, ellipsizeMode: 'tail', }; }, getInitialState: function(): Object { return merge(Touchable.Mixin.touchableGetInitialState(), { isHighlighted: false, }); }, mixins: [NativeMethodsMixin], viewConfig: viewConfig, getChildContext(): Object { return {isInAParentText: true}; }, childContextTypes: { isInAParentText: React.PropTypes.bool }, contextTypes: { isInAParentText: React.PropTypes.bool }, /** * Only assigned if touch is needed. */ _handlers: (null: ?Object), _hasPressHandler(): boolean { return !!this.props.onPress || !!this.props.onLongPress; }, /** * These are assigned lazily the first time the responder is set to make plain * text nodes as cheap as possible. */ touchableHandleActivePressIn: (null: ?Function), touchableHandleActivePressOut: (null: ?Function), touchableHandlePress: (null: ?Function), touchableHandleLongPress: (null: ?Function), touchableGetPressRectOffset: (null: ?Function), render(): ReactElement<any> { let newProps = this.props; if (this.props.onStartShouldSetResponder || this._hasPressHandler()) { if (!this._handlers) { this._handlers = { onStartShouldSetResponder: (): bool => { const shouldSetFromProps = this.props.onStartShouldSetResponder && this.props.onStartShouldSetResponder(); const setResponder = shouldSetFromProps || this._hasPressHandler(); if (setResponder && !this.touchableHandleActivePressIn) { // Attach and bind all the other handlers only the first time a touch // actually happens. for (const key in Touchable.Mixin) { if (typeof Touchable.Mixin[key] === 'function') { (this: any)[key] = Touchable.Mixin[key].bind(this); } } this.touchableHandleActivePressIn = () => { if (this.props.suppressHighlighting || !this._hasPressHandler()) { return; } this.setState({ isHighlighted: true, }); }; this.touchableHandleActivePressOut = () => { if (this.props.suppressHighlighting || !this._hasPressHandler()) { return; } this.setState({ isHighlighted: false, }); }; this.touchableHandlePress = () => { this.props.onPress && this.props.onPress(); }; this.touchableHandleLongPress = () => { this.props.onLongPress && this.props.onLongPress(); }; this.touchableGetPressRectOffset = function(): RectOffset { return PRESS_RECT_OFFSET; }; } return setResponder; }, onResponderGrant: function(e: SyntheticEvent, dispatchID: string) { this.touchableHandleResponderGrant(e, dispatchID); this.props.onResponderGrant && this.props.onResponderGrant.apply(this, arguments); }.bind(this), onResponderMove: function(e: SyntheticEvent) { this.touchableHandleResponderMove(e); this.props.onResponderMove && this.props.onResponderMove.apply(this, arguments); }.bind(this), onResponderRelease: function(e: SyntheticEvent) { this.touchableHandleResponderRelease(e); this.props.onResponderRelease && this.props.onResponderRelease.apply(this, arguments); }.bind(this), onResponderTerminate: function(e: SyntheticEvent) { this.touchableHandleResponderTerminate(e); this.props.onResponderTerminate && this.props.onResponderTerminate.apply(this, arguments); }.bind(this), onResponderTerminationRequest: function(): bool { // Allow touchable or props.onResponderTerminationRequest to deny // the request var allowTermination = this.touchableHandleResponderTerminationRequest(); if (allowTermination && this.props.onResponderTerminationRequest) { allowTermination = this.props.onResponderTerminationRequest.apply(this, arguments); } return allowTermination; }.bind(this), }; } newProps = { ...this.props, ...this._handlers, isHighlighted: this.state.isHighlighted, }; } if (Touchable.TOUCH_TARGET_DEBUG && newProps.onPress) { newProps = { ...newProps, style: [this.props.style, {color: 'magenta'}], }; } if (this.context.isInAParentText) { return <RCTVirtualText {...newProps} />; } else { return <RCTText {...newProps} />; } }, }); type RectOffset = { top: number; left: number; right: number; bottom: number; } var PRESS_RECT_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; var RCTText = createReactNativeComponentClass(viewConfig); var RCTVirtualText = RCTText; if (Platform.OS === 'android') { RCTVirtualText = createReactNativeComponentClass({ validAttributes: merge(ReactNativeViewAttributes.UIView, { isHighlighted: true, }), uiViewClassName: 'RCTVirtualText', }); } module.exports = Text;
src/Spin/index.js
lenxeon/react-ui
import React from 'react' import PropTypes from '../utils/proptypes' import Plane from './Plane' import DoubleBounce from './DoubleBounce' import Wave from './Wave' import Pulse from './Pulse' import ChasingDots from './ChasingDots' import ThreeBounce from './ThreeBounce' import Circle from './Circle' import CubeGrid from './CubeGrid' import FadingCircle from './FadingCircle' import FoldingCube from './FoldingCube' import SimpleCircle from './SimpleCircle' import ChaseCircle from './ChaseCircle' const spins = { 'plane': Plane, 'double-bounce': DoubleBounce, 'wave': Wave, 'pulse': Pulse, 'dots': ChasingDots, 'three-bounce': ThreeBounce, 'circle': Circle, 'cube-grid': CubeGrid, 'fading-circle': FadingCircle, 'folding-cube': FoldingCube, 'simple-circle': SimpleCircle, 'chase-circle': ChaseCircle } export default function Spin (props) { const { type } = props const Component = spins[type] return <Component {...props} /> } Spin.propTypes = { size: PropTypes.number_string, type: PropTypes.oneOf([ 'plane', 'double-bounce', 'wave', 'pulse', 'dots', 'three-bounce', 'circle', 'cube-grid', 'fading-circle', 'folding-cube', 'simple-circle', 'chase-circle' ]) } Spin.defaultProps = { color: '#ccc', size: 40 }
example/pages/msg/index.js
woshisbb43/coinMessageWechat
import React from 'react'; import { Link } from 'react-router-dom'; import { Button } from '../../../build/packages'; import Page from '../../component/page'; const MsgDemo = () => ( <Page className="msg" title="Msg" subTitle="提示页" spacing> <Button component={Link} to="/msg/success">Success Message</Button> <Button component={Link} to="/msg/fail">Warn Message</Button> </Page> ); export default MsgDemo;
Libraries/Text/Text.js
Maxwell2022/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Text * @flow */ 'use strict'; const ColorPropType = require('ColorPropType'); const EdgeInsetsPropType = require('EdgeInsetsPropType'); const NativeMethodsMixin = require('NativeMethodsMixin'); const Platform = require('Platform'); const React = require('React'); const PropTypes = require('prop-types'); const ReactNativeViewAttributes = require('ReactNativeViewAttributes'); const StyleSheetPropType = require('StyleSheetPropType'); const TextStylePropTypes = require('TextStylePropTypes'); const Touchable = require('Touchable'); const createReactNativeComponentClass = require('createReactNativeComponentClass'); const mergeFast = require('mergeFast'); const processColor = require('processColor'); const stylePropType = StyleSheetPropType(TextStylePropTypes); const viewConfig = { validAttributes: mergeFast(ReactNativeViewAttributes.UIView, { isHighlighted: true, numberOfLines: true, ellipsizeMode: true, allowFontScaling: true, selectable: true, selectionColor: true, adjustsFontSizeToFit: true, minimumFontScale: true, textBreakStrategy: true, }), uiViewClassName: 'RCTText', }; /** * A React component for displaying text. * * `Text` supports nesting, styling, and touch handling. * * In the following example, the nested title and body text will inherit the `fontFamily` from *`styles.baseText`, but the title provides its own additional styles. The title and body will * stack on top of each other on account of the literal newlines: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, Text, StyleSheet } from 'react-native'; * * class TextInANest extends Component { * constructor(props) { * super(props); * this.state = { * titleText: "Bird's Nest", * bodyText: 'This is not really a bird nest.' * }; * } * * render() { * return ( * <Text style={styles.baseText}> * <Text style={styles.titleText} onPress={this.onPressTitle}> * {this.state.titleText}{'\n'}{'\n'} * </Text> * <Text numberOfLines={5}> * {this.state.bodyText} * </Text> * </Text> * ); * } * } * * const styles = StyleSheet.create({ * baseText: { * fontFamily: 'Cochin', * }, * titleText: { * fontSize: 20, * fontWeight: 'bold', * }, * }); * * // App registration and rendering * AppRegistry.registerComponent('TextInANest', () => TextInANest); * ``` */ // $FlowFixMe(>=0.41.0) const Text = React.createClass({ propTypes: { /** * When `numberOfLines` is set, this prop defines how text will be truncated. * `numberOfLines` must be set in conjunction with this prop. * * This can be one of the following values: * * - `head` - The line is displayed so that the end fits in the container and the missing text * at the beginning of the line is indicated by an ellipsis glyph. e.g., "...wxyz" * - `middle` - The line is displayed so that the beginning and end fit in the container and the * missing text in the middle is indicated by an ellipsis glyph. "ab...yz" * - `tail` - The line is displayed so that the beginning fits in the container and the * missing text at the end of the line is indicated by an ellipsis glyph. e.g., "abcd..." * - `clip` - Lines are not drawn past the edge of the text container. * * The default is `tail`. * * > `clip` is working only for iOS */ ellipsizeMode: PropTypes.oneOf(['head', 'middle', 'tail', 'clip']), /** * Used to truncate the text with an ellipsis after computing the text * layout, including line wrapping, such that the total number of lines * does not exceed this number. * * This prop is commonly used with `ellipsizeMode`. */ numberOfLines: PropTypes.number, /** * Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced` * The default value is `highQuality`. * @platform android */ textBreakStrategy: PropTypes.oneOf(['simple', 'highQuality', 'balanced']), /** * Invoked on mount and layout changes with * * `{nativeEvent: {layout: {x, y, width, height}}}` */ onLayout: PropTypes.func, /** * This function is called on press. * * e.g., `onPress={() => console.log('1st')}` */ onPress: PropTypes.func, /** * This function is called on long press. * * e.g., `onLongPress={this.increaseSize}>` */ onLongPress: PropTypes.func, /** * When the scroll view is disabled, this defines how far your touch may * move off of the button, before deactivating the button. Once deactivated, * try moving it back and you'll see that the button is once again * reactivated! Move it back and forth several times while the scroll view * is disabled. Ensure you pass in a constant to reduce memory allocations. */ pressRetentionOffset: EdgeInsetsPropType, /** * Lets the user select text, to use the native copy and paste functionality. */ selectable: PropTypes.bool, /** * The highlight color of the text. * @platform android */ selectionColor: ColorPropType, /** * When `true`, no visual change is made when text is pressed down. By * default, a gray oval highlights the text on press down. * @platform ios */ suppressHighlighting: PropTypes.bool, style: stylePropType, /** * Used to locate this view in end-to-end tests. */ testID: PropTypes.string, /** * Used to locate this view from native code. * @platform android */ nativeID: PropTypes.string, /** * Specifies whether fonts should scale to respect Text Size accessibility settings. The * default is `true`. */ allowFontScaling: PropTypes.bool, /** * When set to `true`, indicates that the view is an accessibility element. The default value * for a `Text` element is `true`. * * See the * [Accessibility guide](docs/accessibility.html#accessible-ios-android) * for more information. */ accessible: PropTypes.bool, /** * Specifies whether font should be scaled down automatically to fit given style constraints. * @platform ios */ adjustsFontSizeToFit: PropTypes.bool, /** * Specifies smallest possible scale a font can reach when adjustsFontSizeToFit is enabled. (values 0.01-1.0). * @platform ios */ minimumFontScale: PropTypes.number, /** * Specifies the disabled state of the text view for testing purposes * @platform android */ disabled: PropTypes.bool, }, getDefaultProps(): Object { return { accessible: true, allowFontScaling: true, ellipsizeMode: 'tail', disabled: false, }; }, getInitialState: function(): Object { return mergeFast(Touchable.Mixin.touchableGetInitialState(), { isHighlighted: false, }); }, mixins: [NativeMethodsMixin], viewConfig: viewConfig, getChildContext(): Object { return {isInAParentText: true}; }, childContextTypes: { isInAParentText: PropTypes.bool }, contextTypes: { isInAParentText: PropTypes.bool }, /** * Only assigned if touch is needed. */ _handlers: (null: ?Object), _hasPressHandler(): boolean { return !!this.props.onPress || !!this.props.onLongPress; }, /** * These are assigned lazily the first time the responder is set to make plain * text nodes as cheap as possible. */ touchableHandleActivePressIn: (null: ?Function), touchableHandleActivePressOut: (null: ?Function), touchableHandlePress: (null: ?Function), touchableHandleLongPress: (null: ?Function), touchableGetPressRectOffset: (null: ?Function), render(): React.Element<any> { let newProps = this.props; if (this.props.onStartShouldSetResponder || this._hasPressHandler()) { if (!this._handlers) { this._handlers = { onStartShouldSetResponder: (): bool => { const shouldSetFromProps = this.props.onStartShouldSetResponder && // $FlowFixMe(>=0.41.0) this.props.onStartShouldSetResponder(); const setResponder = shouldSetFromProps || this._hasPressHandler(); if (setResponder && !this.touchableHandleActivePressIn) { // Attach and bind all the other handlers only the first time a touch // actually happens. for (const key in Touchable.Mixin) { if (typeof Touchable.Mixin[key] === 'function') { (this: any)[key] = Touchable.Mixin[key].bind(this); } } this.touchableHandleActivePressIn = () => { if (this.props.suppressHighlighting || !this._hasPressHandler()) { return; } this.setState({ isHighlighted: true, }); }; this.touchableHandleActivePressOut = () => { if (this.props.suppressHighlighting || !this._hasPressHandler()) { return; } this.setState({ isHighlighted: false, }); }; this.touchableHandlePress = (e: SyntheticEvent) => { this.props.onPress && this.props.onPress(e); }; this.touchableHandleLongPress = (e: SyntheticEvent) => { this.props.onLongPress && this.props.onLongPress(e); }; this.touchableGetPressRectOffset = function(): RectOffset { return this.props.pressRetentionOffset || PRESS_RECT_OFFSET; }; } // $FlowFixMe(>=0.41.0) return setResponder; }, onResponderGrant: function(e: SyntheticEvent, dispatchID: string) { // $FlowFixMe(>=0.41.0) this.touchableHandleResponderGrant(e, dispatchID); this.props.onResponderGrant && // $FlowFixMe(>=0.41.0) this.props.onResponderGrant.apply(this, arguments); }.bind(this), onResponderMove: function(e: SyntheticEvent) { // $FlowFixMe(>=0.41.0) this.touchableHandleResponderMove(e); this.props.onResponderMove && // $FlowFixMe(>=0.41.0) this.props.onResponderMove.apply(this, arguments); }.bind(this), onResponderRelease: function(e: SyntheticEvent) { // $FlowFixMe(>=0.41.0) this.touchableHandleResponderRelease(e); this.props.onResponderRelease && // $FlowFixMe(>=0.41.0) this.props.onResponderRelease.apply(this, arguments); }.bind(this), onResponderTerminate: function(e: SyntheticEvent) { // $FlowFixMe(>=0.41.0) this.touchableHandleResponderTerminate(e); this.props.onResponderTerminate && // $FlowFixMe(>=0.41.0) this.props.onResponderTerminate.apply(this, arguments); }.bind(this), onResponderTerminationRequest: function(): bool { // Allow touchable or props.onResponderTerminationRequest to deny // the request // $FlowFixMe(>=0.41.0) var allowTermination = this.touchableHandleResponderTerminationRequest(); if (allowTermination && this.props.onResponderTerminationRequest) { // $FlowFixMe(>=0.41.0) allowTermination = this.props.onResponderTerminationRequest.apply(this, arguments); } return allowTermination; }.bind(this), }; } newProps = { ...this.props, ...this._handlers, isHighlighted: this.state.isHighlighted, }; } if (newProps.selectionColor != null) { newProps = { ...newProps, selectionColor: processColor(newProps.selectionColor) }; } if (Touchable.TOUCH_TARGET_DEBUG && newProps.onPress) { newProps = { ...newProps, style: [this.props.style, {color: 'magenta'}], }; } if (this.context.isInAParentText) { return <RCTVirtualText {...newProps} />; } else { return <RCTText {...newProps} />; } }, }); type RectOffset = { top: number, left: number, right: number, bottom: number, } var PRESS_RECT_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; var RCTText = createReactNativeComponentClass(viewConfig); var RCTVirtualText = RCTText; if (Platform.OS === 'android') { RCTVirtualText = createReactNativeComponentClass({ validAttributes: mergeFast(ReactNativeViewAttributes.UIView, { isHighlighted: true, }), uiViewClassName: 'RCTVirtualText', }); } module.exports = Text;
src/addons/transitions/ReactCSSTransitionGroup.js
orzyang/react
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * @providesModule ReactCSSTransitionGroup */ 'use strict'; var React = require('React'); var assign = require('Object.assign'); var ReactTransitionGroup = React.createFactory( require('ReactTransitionGroup') ); var ReactCSSTransitionGroupChild = React.createFactory( require('ReactCSSTransitionGroupChild') ); function createTransitionTimeoutPropValidator(transitionType) { var timeoutPropName = 'transition' + transitionType + 'Timeout'; var enabledPropName = 'transition' + transitionType; return function(props) { // If the transition is enabled if (props[enabledPropName]) { // If no timeout duration is provided if (!props[timeoutPropName]) { return new Error( timeoutPropName + ' wasn\'t supplied to ReactCSSTransitionGroup: ' + 'this can cause unreliable animations and won\'t be supported in ' + 'a future version of React. See ' + 'https://fb.me/react-animation-transition-group-timeout for more ' + 'information.' ); // If the duration isn't a number } else if (typeof props[timeoutPropName] !== 'number') { return new Error(timeoutPropName + ' must be a number (in milliseconds)'); } } }; } var ReactCSSTransitionGroup = React.createClass({ displayName: 'ReactCSSTransitionGroup', propTypes: { transitionName: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.shape({ enter: React.PropTypes.string, leave: React.PropTypes.string, active: React.PropTypes.string, }), React.PropTypes.shape({ enter: React.PropTypes.string, enterActive: React.PropTypes.string, leave: React.PropTypes.string, leaveActive: React.PropTypes.string, appear: React.PropTypes.string, appearActive: React.PropTypes.string, }), ]).isRequired, transitionAppear: React.PropTypes.bool, transitionEnter: React.PropTypes.bool, transitionLeave: React.PropTypes.bool, transitionAppearTimeout: createTransitionTimeoutPropValidator('Appear'), transitionEnterTimeout: createTransitionTimeoutPropValidator('Enter'), transitionLeaveTimeout: createTransitionTimeoutPropValidator('Leave'), }, getDefaultProps: function() { return { transitionAppear: false, transitionEnter: true, transitionLeave: true, }; }, _wrapChild: function(child) { // We need to provide this childFactory so that // ReactCSSTransitionGroupChild can receive updates to name, enter, and // leave while it is leaving. return ReactCSSTransitionGroupChild( { name: this.props.transitionName, appear: this.props.transitionAppear, enter: this.props.transitionEnter, leave: this.props.transitionLeave, appearTimeout: this.props.transitionAppearTimeout, enterTimeout: this.props.transitionEnterTimeout, leaveTimeout: this.props.transitionLeaveTimeout, }, child ); }, render: function() { return ( ReactTransitionGroup( assign({}, this.props, {childFactory: this._wrapChild}) ) ); }, }); module.exports = ReactCSSTransitionGroup;
frontend/src/containers/RegisterAccount/RegisterAccount.js
webrecorder/webrecorder
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import querystring from 'querystring'; import { connect } from 'react-redux'; import { withRouter } from 'react-router'; import { Button } from 'react-bootstrap'; import { apiPath, supportEmail } from 'config'; import { apiFetch } from 'helpers/utils'; import { showModal } from 'store/modules/userLogin'; import './style.scss'; class RegisterAccount extends Component { static propTypes = { history: PropTypes.object, location: PropTypes.object, match: PropTypes.object, toggleLogin: PropTypes.func }; constructor(props) { super(props); const qs = querystring.parse(props.location.search.replace('?', '')); this.state = { submitted: false, error: false, success: false, username: qs.username }; } finalizeRegistration = () => { const { match } = this.props; const reg = match.params.registration; const validateApi = `${apiPath}/auth/validate`; document.cookie = `valreg=${reg}; Max-Age=60; Path=${validateApi}`; const data = { reg }; this.setState({ submitted: true }); // call user registration endpoint apiFetch(`/auth/validate?username=${this.state.username}`, data, { method: 'POST' }) .then(res => res.json()) .then((result) => { if (result.error) { this.setState({ error: result.error }); } else { this.setState({ success: true }); } }); } goHome = () => { this.props.history.replace('/'); } render() { const { error, submitted, success } = this.state; const finished = error || success; return ( <div className="verification"> { !submitted && <React.Fragment> <h4>Please click the button to complete your registration:</h4> <Button size="lg" variant="primary" onClick={this.finalizeRegistration}>Complete Registration</Button> </React.Fragment> } { submitted && !finished && <h4>Validating Registration...</h4> } { finished && error === 'invalid_code' && <React.Fragment> <h4>Error Validating Registration</h4> <p>Please try the link again or contact <a href={`mailto:${supportEmail}`}>{supportEmail}</a> if the problem persists.</p> </React.Fragment> } { finished && error === 'already_registered' && <React.Fragment> <h4>This user has already been verified.</h4> <Button size="lig" variant="primary" onClick={this.props.toggleLogin}>Login</Button> </React.Fragment> } { finished && success && <React.Fragment> <h4>Thank you {this.state.username}, your email is now verified.</h4> <Button size="lg" variant="primary" onClick={this.goHome}>Proceed to Homepage</Button> </React.Fragment> } </div> ); } } const mapDispatchToProps = (dispatch) => { return { toggleLogin: () => dispatch(showModal(true, false)) }; }; export default withRouter(connect( () => ({}), mapDispatchToProps )(RegisterAccount));
ajax/libs/react-swipe/2.0.10/react-swipe.min.js
tholu/cdnjs
!function(e,o){"undefined"!=typeof module&&module.exports?module.exports=o(require("react/addons"),require("swipe-js-iso")):e.ReactSwipe=o(e.React,e.Swipe)}(this,function(e,o){var i={container:{overflow:"hidden",visibility:"hidden",position:"relative"},wrapper:{overflow:"hidden",position:"relative"},child:{"float":"left",width:"100%",position:"relative"}},t=e.createClass({propTypes:{startSlide:e.PropTypes.number,slideToIndex:e.PropTypes.number,shouldUpdate:e.PropTypes.func,speed:e.PropTypes.number,auto:e.PropTypes.number,continuous:e.PropTypes.bool,disableScroll:e.PropTypes.bool,stopPropagation:e.PropTypes.bool,callback:e.PropTypes.func,transitionEnd:e.PropTypes.func},componentDidMount:function(){this.isMounted()&&(this.swipe=o(this.getDOMNode(),this.props))},componentDidUpdate:function(){(this.props.slideToIndex||0===this.props.slideToIndex)&&this.swipe.slide(this.props.slideToIndex)},componentWillUnmount:function(){this.swipe.kill(),delete this.swipe},shouldComponentUpdate:function(e){return this.props.slideToIndex!==e.slideToIndex||"undefined"!=typeof this.props.shouldUpdate&&!this.props.shouldUpdate(e)},render:function(){return e.createElement("div",e.__spread({},this.props,{style:i.container}),e.createElement("div",{style:i.wrapper},e.Children.map(this.props.children,function(o){return e.addons.cloneWithProps(o,{style:i.child})})))}});return t});
src/ChessboardOptionEditor.js
yo35/rpb-chessboard
/****************************************************************************** * * * This file is part of RPB Chessboard, a WordPress plugin. * * Copyright (C) 2013-2022 Yoann Le Montagner <yo35 -at- melix.net> * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * 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 General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ******************************************************************************/ import './public-path'; import PropTypes from 'prop-types'; import React from 'react'; import { ComboboxControl, RadioControl, RangeControl, ToggleControl } from '@wordpress/components'; const i18n = RPBChessboard.i18n; /** * Combox-box to select the colorset or the pieceset. */ function SetCodeControl({ label, value, available, onChange }) { let options = [ { value: '', label: '<' + i18n.FEN_EDITOR_USE_DEFAULT + '>' } ]; Object.keys(available).sort().forEach(key => options.push({ value: key, label: available[key] })); return <ComboboxControl label={label} value={value} options={options} onChange={onChange} />; } SetCodeControl.propTypes = { label: PropTypes.string.isRequired, value: PropTypes.string.isRequired, available: PropTypes.arrayOf(PropTypes.object).isRequired, onChange: PropTypes.func.isRequired, }; /** * Components to customize the square size, the coordinate visibility, and the colorset/pieceset. */ export default function ChessboardOptionEditor(props) { // Square-size controls. let isDefaultSize = props.squareSize === 0; let squareSizeControl = isDefaultSize ? undefined : <RangeControl label={i18n.FEN_EDITOR_CONTROL_SQUARE_SIZE} value={props.squareSize} min={RPBChessboard.availableSquareSize.min} max={RPBChessboard.availableSquareSize.max} step={1} onChange={props.onSquareSizeChanged} />; return (<> <ToggleControl label={i18n.FEN_EDITOR_CONTROL_FLIP} checked={props.flipped} onChange={() => props.onFlipChanged()} /> <ToggleControl label={i18n.FEN_EDITOR_CONTROL_USE_DEFAULT_SIZE} checked={isDefaultSize} onChange={() => props.onSquareSizeChanged(isDefaultSize ? props.defaultSquareSize : 0)} /> {squareSizeControl} <RadioControl label={i18n.FEN_EDITOR_CONTROL_COORDINATES} selected={props.coordinateVisible} onChange={props.onCoordinateVisibleChanged} options={[ { label: i18n.FEN_EDITOR_USE_DEFAULT, value: '' }, { label: i18n.FEN_EDITOR_OPTION_HIDDEN, value: 'false' }, { label: i18n.FEN_EDITOR_OPTION_VISIBLE, value: 'true' }, ]} /> <SetCodeControl label={i18n.FEN_EDITOR_CONTROL_COLORSET} value={props.colorset} available={RPBChessboard.availableColorsets} onChange={props.onColorsetChanged} /> <SetCodeControl label={i18n.FEN_EDITOR_CONTROL_PIECESET} value={props.pieceset} available={RPBChessboard.availablePiecesets} onChange={props.onPiecesetChanged} /> </>); } ChessboardOptionEditor.propTypes = { defaultSquareSize: PropTypes.number.isRequired, flipped: PropTypes.bool.isRequired, squareSize: PropTypes.number.isRequired, // 0 means "use default" coordinateVisible: PropTypes.string.isRequired, // not a boolean since it can be '' (meaning "use default") colorset: PropTypes.string.isRequired, pieceset: PropTypes.string.isRequired, onFlipChanged: PropTypes.func.isRequired, onSquareSizeChanged: PropTypes.func.isRequired, onCoordinateVisibleChanged: PropTypes.func.isRequired, onColorsetChanged: PropTypes.func.isRequired, onPiecesetChanged: PropTypes.func.isRequired, };
blueocean-material-icons/src/js/components/svg-icons/action/settings-phone.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionSettingsPhone = (props) => ( <SvgIcon {...props}> <path d="M13 9h-2v2h2V9zm4 0h-2v2h2V9zm3 6.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.58l2.2-2.21c.28-.27.36-.66.25-1.01C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 9v2h2V9h-2z"/> </SvgIcon> ); ActionSettingsPhone.displayName = 'ActionSettingsPhone'; ActionSettingsPhone.muiName = 'SvgIcon'; export default ActionSettingsPhone;
example9/src/components/Profile.js
JoeTheDave/Talk-ReactUpAndRunning
//Profile.js import React from 'react'; class Profile extends React.Component{ constructor (props) { super(props); } render() { return ( <div className="profile-component"> <img src={this.props.person.image} /> <div>{this.props.person.name}</div> </div> ); } } export default Profile;
site/src/site.js
MunGell/elemental
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, Link, IndexRoute } from'react-router'; import { createHistory, useBasename } from 'history'; const NavItems = [ { value: '/css', label: 'CSS' }, { value: '/grid', label: 'Grid' }, { value: '/buttons', label: 'Buttons' }, { value: '/glyphs', label: 'Glyphs' }, { value: '/forms', label: 'Forms' }, { value: '/spinner', label: 'Spinner' }, { value: '/modal', label: 'Modal' }, { value: '/misc', label: 'Misc' } // { value: 'date-picker', label: 'Date Picker' } ]; const PageNav = React.createClass({ getInitialState () { return { mobileMenuIsVisible: false, windowHeight: window.innerHeight, windowWidth: window.innerWidth }; }, componentDidMount () { window.addEventListener('resize', this.handleResize); }, componentWillUnmount () { window.removeEventListener('resize', this.handleResize); }, handleResize () { this.setState({ windowHeight: window.innerHeight, windowWidth: window.innerWidth }); }, toggleMenu () { this.setState({ mobileMenuIsVisible: !this.state.mobileMenuIsVisible }); }, render () { var self = this; var height = (this.state.windowWidth < 768) ? this.state.windowHeight : 'auto'; var menuClass = this.state.mobileMenuIsVisible ? 'primary-nav-menu is-visible' : 'primary-nav-menu is-hidden'; var menuItems = NavItems.map(function(item) { return ( <Link key={item.value} className="primary-nav__item" activeClassName="active" onClick={self.toggleMenu} to={item.value}> <span className="primary-nav__item-inner">{item.label}</span> </Link> ); }); return ( <nav className="primary-nav"> <Link to="/home" className="primary-nav__brand special" title="Home"> <img src="./images/elemental-logo-paths.svg" className="primary-nav__brand-src" /> </Link> {/*<Link to="home">Home</Link>*/} <button onClick={this.toggleMenu} className="primary-nav__item primary-nav-menu-trigger"> <span className="primary-nav-menu-trigger-icon octicon octicon-navicon" /> <span className="primary-nav-menu-trigger-label">{this.state.mobileMenuIsVisible ? 'Close' : 'Menu'}</span> </button> <div className={menuClass} style={{ height }}> <div className="primary-nav-menu-inner"> {menuItems} </div> </div> <a href="https://github.com/elementalui/elemental" target="_blank" title="View on GitHub" className="primary-nav__brand right"> <img src="./images/github-logo.svg" className="primary-nav__brand-src" /> </a> </nav> ); } }); const App = React.createClass({ render () { return ( <div className="page-wrapper"> <PageNav /> <div className="page-body"> {this.props.children} </div> <div className="page-footer"> <div className="demo-container container"> Copyright &copy; 2015 &middot; (MIT) License &middot; Built by <a href="http://www.thinkmill.com.au" target="_blank">Thinkmill</a>, initially for integration with <a href="http://www.keystonejs.com" target="_blank">KeystoneJS</a> </div> </div> </div> ); } }); const basepath = (window.location.pathname.slice(0, 10) === '/elemental') ? '/elemental' : ''; const history = createHistory(); ReactDOM.render( <Router history={history} onUpdate={() => window.scrollTo(0, 0)}> <Route path="/" component={App}> <IndexRoute component={require('./pages/Home')} /> <Route path="home" component={require('./pages/Home')} /> <Route path="css" component={require('./pages/CSS')} /> <Route path="grid" component={require('./pages/Grid')} /> <Route path="buttons" component={require('./pages/Buttons')} /> <Route path="glyphs" component={require('./pages/Glyphs')} /> <Route path="forms" component={require('./pages/Forms')} /> <Route path="spinner" component={require('./pages/Spinner')} /> <Route path="modal" component={require('./pages/Modal')} /> <Route path="misc" component={require('./pages/Misc')} /> <Route path="*" component={require('./pages/Home')} /> </Route> </Router>, document.getElementById('app') );
node_modules/react-bootstrap/lib/ButtonToolbar.js
ctkou/letsgo
'use strict'; var _extends = require('babel-runtime/helpers/extends')['default']; var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default']; exports.__esModule = true; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = require('./utils/bootstrapUtils'); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _Button = require('./Button'); var _Button2 = _interopRequireDefault(_Button); var ButtonToolbar = _react2['default'].createClass({ displayName: 'ButtonToolbar', propTypes: { bsSize: _Button2['default'].propTypes.bsSize }, getDefaultProps: function getDefaultProps() { return { bsClass: 'btn-toolbar' }; }, render: function render() { var classes = _utilsBootstrapUtils2['default'].getClassSet(this.props); return _react2['default'].createElement( 'div', _extends({}, this.props, { role: 'toolbar', className: _classnames2['default'](this.props.className, classes) }), this.props.children ); } }); exports['default'] = ButtonToolbar; module.exports = exports['default'];
src/InputPicker/test/InputPickerStylesSpec.js
suitejs/suite
import React from 'react'; import ReactDOM from 'react-dom'; import InputPicker from '../index'; import Button from '../../Button'; import { createTestContainer, getDOMNode, getStyle, toRGB, getDefaultPalette, inChrome } from '@test/testUtils'; import '../styles/index'; const data = [ { label: 'Eugenia', value: 'Eugenia', role: 'Master' }, { label: <span>Kariane</span>, value: 'Kariane', role: 'Developer' }, { label: 'Louisa', value: 'Louisa', role: 'Master' } ]; const { H700 } = getDefaultPalette(); describe('InputPicker styles', () => { it('Should render correct toggle styles', () => { const instanceRef = React.createRef(); ReactDOM.render(<InputPicker ref={instanceRef} data={data} />, createTestContainer()); const dom = getDOMNode(instanceRef.current); const toggleDom = dom.querySelector('.rs-picker-toggle'); const toggleInputDom = dom.querySelector('.rs-picker-search-input'); inChrome && assert.equal(getStyle(dom, 'border'), `1px solid ${toRGB('#e5e5ea')}`, 'Picker border'); assert.equal(getStyle(dom, 'backgroundColor'), `${toRGB('#fff')}`, 'Toggle background color'); assert.equal(getStyle(toggleDom, 'height'), '34px', 'Toggle height'); inChrome && assert.equal(getStyle(toggleInputDom, 'border-style'), 'none', 'Toggle input border'); }); it('Should render correct large size', () => { const instanceRef = React.createRef(); ReactDOM.render( <InputPicker toggleComponentClass={Button} size="lg" ref={instanceRef} data={data} />, createTestContainer() ); const dom = getDOMNode(instanceRef.current); assert.equal(getStyle(dom, 'height'), '42px', 'Toggle height'); }); it('Should render correct middle size ', () => { const instanceRef = React.createRef(); ReactDOM.render( <InputPicker toggleComponentClass={Button} size="md" ref={instanceRef} data={data} />, createTestContainer() ); const dom = getDOMNode(instanceRef.current); assert.equal(getStyle(dom, 'height'), '36px', 'Toggle height'); }); it('Should render correct small size ', () => { const instanceRef = React.createRef(); ReactDOM.render( <InputPicker toggleComponentClass={Button} size="sm" ref={instanceRef} data={data} />, createTestContainer() ); const dom = getDOMNode(instanceRef.current); assert.equal(getStyle(dom, 'height'), '30px', 'Toggle height'); }); it('Should render correct xsmall size ', () => { const instanceRef = React.createRef(); ReactDOM.render( <InputPicker toggleComponentClass={Button} size="xs" ref={instanceRef} data={data} />, createTestContainer() ); const dom = getDOMNode(instanceRef.current); assert.equal(getStyle(dom, 'height'), '24px', 'Toggle height'); }); it('Should render correct toggle styles when open', done => { const instanceRef = React.createRef(); let dom; ReactDOM.render( <InputPicker ref={instanceRef} data={data} open onOpen={() => { inChrome && assert.equal(getStyle(dom, 'border'), `1px solid ${H700}`, 'Picker active border'); done(); }} // For the test set transition to none. style={{ transition: 'none' }} />, createTestContainer() ); dom = getDOMNode(instanceRef.current); }); });
src/app/Translator.js
steemit/steemit.com
import React from 'react'; import { connect } from 'react-redux'; import { IntlProvider, addLocaleData } from 'react-intl'; import en from 'react-intl/locale-data/en'; import es from 'react-intl/locale-data/es'; import ru from 'react-intl/locale-data/ru'; import fr from 'react-intl/locale-data/fr'; import it from 'react-intl/locale-data/it'; import ko from 'react-intl/locale-data/ko'; import zh from 'react-intl/locale-data/zh'; import pl from 'react-intl/locale-data/pl'; import ja from 'react-intl/locale-data/ja'; import { DEFAULT_LANGUAGE } from 'app/client_config'; import tt from 'counterpart'; addLocaleData([...en, ...es, ...ru, ...fr, ...it, ...ko, ...zh, ...pl, ...ja]); tt.registerTranslations('en', require('counterpart/locales/en')); tt.registerTranslations('en', require('app/locales/en.json')); tt.registerTranslations('es', require('app/locales/counterpart/es')); tt.registerTranslations('es', require('app/locales/es.json')); tt.registerTranslations('ru', require('counterpart/locales/ru')); tt.registerTranslations('ru', require('app/locales/ru.json')); tt.registerTranslations('fr', require('app/locales/counterpart/fr')); tt.registerTranslations('fr', require('app/locales/fr.json')); tt.registerTranslations('it', require('app/locales/counterpart/it')); tt.registerTranslations('it', require('app/locales/it.json')); tt.registerTranslations('ko', require('app/locales/counterpart/ko')); tt.registerTranslations('ko', require('app/locales/ko.json')); tt.registerTranslations('zh', require('app/locales/counterpart/zh')); tt.registerTranslations('zh', require('app/locales/zh.json')); tt.registerTranslations('pl', require('app/locales/counterpart/pl')); tt.registerTranslations('pl', require('app/locales/pl.json')); tt.registerTranslations('ja', require('app/locales/counterpart/ja')); tt.registerTranslations('ja', require('app/locales/ja.json')); if (process.env.NODE_ENV === 'production') { tt.setFallbackLocale('en'); } class Translator extends React.Component { render() { const language = this.props.locale; tt.setLocale(language); return ( <IntlProvider // to ensure dynamic language change, "key" property with same "locale" info must be added // see: https://github.com/yahoo/react-intl/wiki/Components#multiple-intl-contexts key={language} locale={language} defaultLocale={DEFAULT_LANGUAGE} > {this.props.children} </IntlProvider> ); } } export default connect((state, ownProps) => { const locale = state.app.getIn(['user_preferences', 'locale']); return { ...ownProps, locale }; })(Translator); export const FormattedHTMLMessage = ({ id, params, className }) => ( <div className={'FormattedHTMLMessage' + (className ? ` ${className}` : '')} dangerouslySetInnerHTML={{ __html: tt(id, params) }} /> );
examples/backbone_marionette/node_modules/backbone/backbone.js
theflimflam/todomvc
// Backbone.js 1.1.2 // (c) 2010-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Backbone may be freely distributed under the MIT license. // For all details and documentation: // http://backbonejs.org (function(root, factory) { // Set up Backbone appropriately for the environment. Start with AMD. if (typeof define === 'function' && define.amd) { define(['underscore', 'jquery', 'exports'], function(_, $, exports) { // Export global even in AMD case in case this script is loaded with // others that may still expect a global Backbone. root.Backbone = factory(root, exports, _, $); }); // Next for Node.js or CommonJS. jQuery may not be needed as a module. } else if (typeof exports !== 'undefined') { var _ = require('underscore'); factory(root, exports, _); // Finally, as a browser global. } else { root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$)); } }(this, function(root, Backbone, _, $) { // Initial Setup // ------------- // Save the previous value of the `Backbone` variable, so that it can be // restored later on, if `noConflict` is used. var previousBackbone = root.Backbone; // Create local references to array methods we'll want to use later. var array = []; var push = array.push; var slice = array.slice; var splice = array.splice; // Current version of the library. Keep in sync with `package.json`. Backbone.VERSION = '1.1.2'; // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns // the `$` variable. Backbone.$ = $; // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable // to its previous owner. Returns a reference to this Backbone object. Backbone.noConflict = function() { root.Backbone = previousBackbone; return this; }; // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and // set a `X-Http-Method-Override` header. Backbone.emulateHTTP = false; // Turn on `emulateJSON` to support legacy servers that can't deal with direct // `application/json` requests ... will encode the body as // `application/x-www-form-urlencoded` instead and will send the model in a // form param named `model`. Backbone.emulateJSON = false; // Backbone.Events // --------------- // A module that can be mixed in to *any object* in order to provide it with // custom events. You may bind with `on` or remove with `off` callback // functions to an event; `trigger`-ing an event fires all callbacks in // succession. // // var object = {}; // _.extend(object, Backbone.Events); // object.on('expand', function(){ alert('expanded'); }); // object.trigger('expand'); // var Events = Backbone.Events = { // Bind an event to a `callback` function. Passing `"all"` will bind // the callback to all events fired. on: function(name, callback, context) { if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({callback: callback, context: context, ctx: context || this}); return this; }, // Bind an event to only be triggered a single time. After the first time // the callback is invoked, it will be removed. once: function(name, callback, context) { if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function() { self.off(name, once); callback.apply(this, arguments); }); once._callback = callback; return this.on(name, once, context); }, // Remove one or many callbacks. If `context` is null, removes all // callbacks with that function. If `callback` is null, removes all // callbacks for the event. If `name` is null, removes all bound // callbacks for all events. off: function(name, callback, context) { var retain, ev, events, names, i, l, j, k; if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; if (!name && !callback && !context) { this._events = void 0; return this; } names = name ? [name] : _.keys(this._events); for (i = 0, l = names.length; i < l; i++) { name = names[i]; if (events = this._events[name]) { this._events[name] = retain = []; if (callback || context) { for (j = 0, k = events.length; j < k; j++) { ev = events[j]; if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) { retain.push(ev); } } } if (!retain.length) delete this._events[name]; } } return this; }, // Trigger one or many events, firing all bound callbacks. Callbacks are // passed the same arguments as `trigger` is, apart from the event name // (unless you're listening on `"all"`, which will cause your callback to // receive the true name of the event as the first argument). trigger: function(name) { if (!this._events) return this; var args = slice.call(arguments, 1); if (!eventsApi(this, 'trigger', name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); if (allEvents) triggerEvents(allEvents, arguments); return this; }, // Tell this object to stop listening to either specific events ... or // to every object it's currently listening to. stopListening: function(obj, name, callback) { var listeningTo = this._listeningTo; if (!listeningTo) return this; var remove = !name && !callback; if (!callback && typeof name === 'object') callback = this; if (obj) (listeningTo = {})[obj._listenId] = obj; for (var id in listeningTo) { obj = listeningTo[id]; obj.off(name, callback, this); if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id]; } return this; } }; // Regular expression used to split event strings. var eventSplitter = /\s+/; // Implement fancy features of the Events API such as multiple event // names `"change blur"` and jQuery-style event maps `{change: action}` // in terms of the existing API. var eventsApi = function(obj, action, name, rest) { if (!name) return true; // Handle event maps. if (typeof name === 'object') { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } return false; } // Handle space separated event names. if (eventSplitter.test(name)) { var names = name.split(eventSplitter); for (var i = 0, l = names.length; i < l; i++) { obj[action].apply(obj, [names[i]].concat(rest)); } return false; } return true; }; // A difficult-to-believe, but optimized internal dispatch function for // triggering events. Tries to keep the usual cases speedy (most internal // Backbone events have 3 arguments). var triggerEvents = function(events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; } }; var listenMethods = {listenTo: 'on', listenToOnce: 'once'}; // Inversion-of-control versions of `on` and `once`. Tell *this* object to // listen to an event in another object ... keeping track of what it's // listening to. _.each(listenMethods, function(implementation, method) { Events[method] = function(obj, name, callback) { var listeningTo = this._listeningTo || (this._listeningTo = {}); var id = obj._listenId || (obj._listenId = _.uniqueId('l')); listeningTo[id] = obj; if (!callback && typeof name === 'object') callback = this; obj[implementation](name, callback, this); return this; }; }); // Aliases for backwards compatibility. Events.bind = Events.on; Events.unbind = Events.off; // Allow the `Backbone` object to serve as a global event bus, for folks who // want global "pubsub" in a convenient place. _.extend(Backbone, Events); // Backbone.Model // -------------- // Backbone **Models** are the basic data object in the framework -- // frequently representing a row in a table in a database on your server. // A discrete chunk of data and a bunch of useful, related methods for // performing computations and transformations on that data. // Create a new model with the specified attributes. A client id (`cid`) // is automatically generated and assigned for you. var Model = Backbone.Model = function(attributes, options) { var attrs = attributes || {}; options || (options = {}); this.cid = _.uniqueId('c'); this.attributes = {}; if (options.collection) this.collection = options.collection; if (options.parse) attrs = this.parse(attrs, options) || {}; attrs = _.defaults({}, attrs, _.result(this, 'defaults')); this.set(attrs, options); this.changed = {}; this.initialize.apply(this, arguments); }; // Attach all inheritable methods to the Model prototype. _.extend(Model.prototype, Events, { // A hash of attributes whose current and previous value differ. changed: null, // The value returned during the last failed validation. validationError: null, // The default name for the JSON `id` attribute is `"id"`. MongoDB and // CouchDB users may want to set this to `"_id"`. idAttribute: 'id', // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Return a copy of the model's `attributes` object. toJSON: function(options) { return _.clone(this.attributes); }, // Proxy `Backbone.sync` by default -- but override this if you need // custom syncing semantics for *this* particular model. sync: function() { return Backbone.sync.apply(this, arguments); }, // Get the value of an attribute. get: function(attr) { return this.attributes[attr]; }, // Get the HTML-escaped value of an attribute. escape: function(attr) { return _.escape(this.get(attr)); }, // Returns `true` if the attribute contains a value that is not null // or undefined. has: function(attr) { return this.get(attr) != null; }, // Set a hash of model attributes on the object, firing `"change"`. This is // the core primitive operation of a model, updating the data and notifying // anyone who needs to know about the change in state. The heart of the beast. set: function(key, val, options) { var attr, attrs, unset, changes, silent, changing, prev, current; if (key == null) return this; // Handle both `"key", value` and `{key: value}` -style arguments. if (typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options || (options = {}); // Run validation. if (!this._validate(attrs, options)) return false; // Extract attributes and options. unset = options.unset; silent = options.silent; changes = []; changing = this._changing; this._changing = true; if (!changing) { this._previousAttributes = _.clone(this.attributes); this.changed = {}; } current = this.attributes, prev = this._previousAttributes; // Check for changes of `id`. if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; // For each `set` attribute, update or delete the current value. for (attr in attrs) { val = attrs[attr]; if (!_.isEqual(current[attr], val)) changes.push(attr); if (!_.isEqual(prev[attr], val)) { this.changed[attr] = val; } else { delete this.changed[attr]; } unset ? delete current[attr] : current[attr] = val; } // Trigger all relevant attribute changes. if (!silent) { if (changes.length) this._pending = options; for (var i = 0, l = changes.length; i < l; i++) { this.trigger('change:' + changes[i], this, current[changes[i]], options); } } // You might be wondering why there's a `while` loop here. Changes can // be recursively nested within `"change"` events. if (changing) return this; if (!silent) { while (this._pending) { options = this._pending; this._pending = false; this.trigger('change', this, options); } } this._pending = false; this._changing = false; return this; }, // Remove an attribute from the model, firing `"change"`. `unset` is a noop // if the attribute doesn't exist. unset: function(attr, options) { return this.set(attr, void 0, _.extend({}, options, {unset: true})); }, // Clear all attributes on the model, firing `"change"`. clear: function(options) { var attrs = {}; for (var key in this.attributes) attrs[key] = void 0; return this.set(attrs, _.extend({}, options, {unset: true})); }, // Determine if the model has changed since the last `"change"` event. // If you specify an attribute name, determine if that attribute has changed. hasChanged: function(attr) { if (attr == null) return !_.isEmpty(this.changed); return _.has(this.changed, attr); }, // Return an object containing all the attributes that have changed, or // false if there are no changed attributes. Useful for determining what // parts of a view need to be updated and/or what attributes need to be // persisted to the server. Unset attributes will be set to undefined. // You can also pass an attributes object to diff against the model, // determining if there *would be* a change. changedAttributes: function(diff) { if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; var val, changed = false; var old = this._changing ? this._previousAttributes : this.attributes; for (var attr in diff) { if (_.isEqual(old[attr], (val = diff[attr]))) continue; (changed || (changed = {}))[attr] = val; } return changed; }, // Get the previous value of an attribute, recorded at the time the last // `"change"` event was fired. previous: function(attr) { if (attr == null || !this._previousAttributes) return null; return this._previousAttributes[attr]; }, // Get all of the attributes of the model at the time of the previous // `"change"` event. previousAttributes: function() { return _.clone(this._previousAttributes); }, // Fetch the model from the server. If the server's representation of the // model differs from its current attributes, they will be overridden, // triggering a `"change"` event. fetch: function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { if (!model.set(model.parse(resp, options), options)) return false; if (success) success(model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Set a hash of model attributes, and sync the model to the server. // If the server returns an attributes hash that differs, the model's // state will be `set` again. save: function(key, val, options) { var attrs, method, xhr, attributes = this.attributes; // Handle both `"key", value` and `{key: value}` -style arguments. if (key == null || typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options = _.extend({validate: true}, options); // If we're not waiting and attributes exist, save acts as // `set(attr).save(null, opts)` with validation. Otherwise, check if // the model will be valid when the attributes, if any, are set. if (attrs && !options.wait) { if (!this.set(attrs, options)) return false; } else { if (!this._validate(attrs, options)) return false; } // Set temporary attributes if `{wait: true}`. if (attrs && options.wait) { this.attributes = _.extend({}, attributes, attrs); } // After a successful server-side save, the client is (optionally) // updated with the server-side state. if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { // Ensure attributes are restored during synchronous saves. model.attributes = attributes; var serverAttrs = model.parse(resp, options); if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) { return false; } if (success) success(model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); if (method === 'patch') options.attrs = attrs; xhr = this.sync(method, this, options); // Restore attributes. if (attrs && options.wait) this.attributes = attributes; return xhr; }, // Destroy this model on the server if it was already persisted. // Optimistically removes the model from its collection, if it has one. // If `wait: true` is passed, waits for the server to respond before removal. destroy: function(options) { options = options ? _.clone(options) : {}; var model = this; var success = options.success; var destroy = function() { model.trigger('destroy', model, model.collection, options); }; options.success = function(resp) { if (options.wait || model.isNew()) destroy(); if (success) success(model, resp, options); if (!model.isNew()) model.trigger('sync', model, resp, options); }; if (this.isNew()) { options.success(); return false; } wrapError(this, options); var xhr = this.sync('delete', this, options); if (!options.wait) destroy(); return xhr; }, // Default URL for the model's representation on the server -- if you're // using Backbone's restful methods, override this to change the endpoint // that will be called. url: function() { var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); if (this.isNew()) return base; return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id); }, // **parse** converts a response into the hash of attributes to be `set` on // the model. The default implementation is just to pass the response along. parse: function(resp, options) { return resp; }, // Create a new model with identical attributes to this one. clone: function() { return new this.constructor(this.attributes); }, // A model is new if it has never been saved to the server, and lacks an id. isNew: function() { return !this.has(this.idAttribute); }, // Check if the model is currently in a valid state. isValid: function(options) { return this._validate({}, _.extend(options || {}, { validate: true })); }, // Run validation against the next complete set of model attributes, // returning `true` if all is well. Otherwise, fire an `"invalid"` event. _validate: function(attrs, options) { if (!options.validate || !this.validate) return true; attrs = _.extend({}, this.attributes, attrs); var error = this.validationError = this.validate(attrs, options) || null; if (!error) return true; this.trigger('invalid', this, error, _.extend(options, {validationError: error})); return false; } }); // Underscore methods that we want to implement on the Model. var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit']; // Mix in each Underscore method as a proxy to `Model#attributes`. _.each(modelMethods, function(method) { Model.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.attributes); return _[method].apply(_, args); }; }); // Backbone.Collection // ------------------- // If models tend to represent a single row of data, a Backbone Collection is // more analagous to a table full of data ... or a small slice or page of that // table, or a collection of rows that belong together for a particular reason // -- all of the messages in this particular folder, all of the documents // belonging to this particular author, and so on. Collections maintain // indexes of their models, both in order, and for lookup by `id`. // Create a new **Collection**, perhaps to contain a specific type of `model`. // If a `comparator` is specified, the Collection will maintain // its models in sort order, as they're added and removed. var Collection = Backbone.Collection = function(models, options) { options || (options = {}); if (options.model) this.model = options.model; if (options.comparator !== void 0) this.comparator = options.comparator; this._reset(); this.initialize.apply(this, arguments); if (models) this.reset(models, _.extend({silent: true}, options)); }; // Default options for `Collection#set`. var setOptions = {add: true, remove: true, merge: true}; var addOptions = {add: true, remove: false}; // Define the Collection's inheritable methods. _.extend(Collection.prototype, Events, { // The default model for a collection is just a **Backbone.Model**. // This should be overridden in most cases. model: Model, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // The JSON representation of a Collection is an array of the // models' attributes. toJSON: function(options) { return this.map(function(model){ return model.toJSON(options); }); }, // Proxy `Backbone.sync` by default. sync: function() { return Backbone.sync.apply(this, arguments); }, // Add a model, or list of models to the set. add: function(models, options) { return this.set(models, _.extend({merge: false}, options, addOptions)); }, // Remove a model, or a list of models from the set. remove: function(models, options) { var singular = !_.isArray(models); models = singular ? [models] : _.clone(models); options || (options = {}); var i, l, index, model; for (i = 0, l = models.length; i < l; i++) { model = models[i] = this.get(models[i]); if (!model) continue; delete this._byId[model.id]; delete this._byId[model.cid]; index = this.indexOf(model); this.models.splice(index, 1); this.length--; if (!options.silent) { options.index = index; model.trigger('remove', model, this, options); } this._removeReference(model, options); } return singular ? models[0] : models; }, // Update a collection by `set`-ing a new list of models, adding new ones, // removing models that are no longer present, and merging models that // already exist in the collection, as necessary. Similar to **Model#set**, // the core operation for updating the data contained by the collection. set: function(models, options) { options = _.defaults({}, options, setOptions); if (options.parse) models = this.parse(models, options); var singular = !_.isArray(models); models = singular ? (models ? [models] : []) : _.clone(models); var i, l, id, model, attrs, existing, sort; var at = options.at; var targetModel = this.model; var sortable = this.comparator && (at == null) && options.sort !== false; var sortAttr = _.isString(this.comparator) ? this.comparator : null; var toAdd = [], toRemove = [], modelMap = {}; var add = options.add, merge = options.merge, remove = options.remove; var order = !sortable && add && remove ? [] : false; // Turn bare objects into model references, and prevent invalid models // from being added. for (i = 0, l = models.length; i < l; i++) { attrs = models[i] || {}; if (attrs instanceof Model) { id = model = attrs; } else { id = attrs[targetModel.prototype.idAttribute || 'id']; } // If a duplicate is found, prevent it from being added and // optionally merge it into the existing model. if (existing = this.get(id)) { if (remove) modelMap[existing.cid] = true; if (merge) { attrs = attrs === model ? model.attributes : attrs; if (options.parse) attrs = existing.parse(attrs, options); existing.set(attrs, options); if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; } models[i] = existing; // If this is a new, valid model, push it to the `toAdd` list. } else if (add) { model = models[i] = this._prepareModel(attrs, options); if (!model) continue; toAdd.push(model); this._addReference(model, options); } // Do not add multiple models with the same `id`. model = existing || model; if (order && (model.isNew() || !modelMap[model.id])) order.push(model); modelMap[model.id] = true; } // Remove nonexistent models if appropriate. if (remove) { for (i = 0, l = this.length; i < l; ++i) { if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model); } if (toRemove.length) this.remove(toRemove, options); } // See if sorting is needed, update `length` and splice in new models. if (toAdd.length || (order && order.length)) { if (sortable) sort = true; this.length += toAdd.length; if (at != null) { for (i = 0, l = toAdd.length; i < l; i++) { this.models.splice(at + i, 0, toAdd[i]); } } else { if (order) this.models.length = 0; var orderedModels = order || toAdd; for (i = 0, l = orderedModels.length; i < l; i++) { this.models.push(orderedModels[i]); } } } // Silently sort the collection if appropriate. if (sort) this.sort({silent: true}); // Unless silenced, it's time to fire all appropriate add/sort events. if (!options.silent) { for (i = 0, l = toAdd.length; i < l; i++) { (model = toAdd[i]).trigger('add', model, this, options); } if (sort || (order && order.length)) this.trigger('sort', this, options); } // Return the added (or merged) model (or models). return singular ? models[0] : models; }, // When you have more items than you want to add or remove individually, // you can reset the entire set with a new list of models, without firing // any granular `add` or `remove` events. Fires `reset` when finished. // Useful for bulk operations and optimizations. reset: function(models, options) { options || (options = {}); for (var i = 0, l = this.models.length; i < l; i++) { this._removeReference(this.models[i], options); } options.previousModels = this.models; this._reset(); models = this.add(models, _.extend({silent: true}, options)); if (!options.silent) this.trigger('reset', this, options); return models; }, // Add a model to the end of the collection. push: function(model, options) { return this.add(model, _.extend({at: this.length}, options)); }, // Remove a model from the end of the collection. pop: function(options) { var model = this.at(this.length - 1); this.remove(model, options); return model; }, // Add a model to the beginning of the collection. unshift: function(model, options) { return this.add(model, _.extend({at: 0}, options)); }, // Remove a model from the beginning of the collection. shift: function(options) { var model = this.at(0); this.remove(model, options); return model; }, // Slice out a sub-array of models from the collection. slice: function() { return slice.apply(this.models, arguments); }, // Get a model from the set by id. get: function(obj) { if (obj == null) return void 0; return this._byId[obj] || this._byId[obj.id] || this._byId[obj.cid]; }, // Get the model at the given index. at: function(index) { return this.models[index]; }, // Return models with matching attributes. Useful for simple cases of // `filter`. where: function(attrs, first) { if (_.isEmpty(attrs)) return first ? void 0 : []; return this[first ? 'find' : 'filter'](function(model) { for (var key in attrs) { if (attrs[key] !== model.get(key)) return false; } return true; }); }, // Return the first model with matching attributes. Useful for simple cases // of `find`. findWhere: function(attrs) { return this.where(attrs, true); }, // Force the collection to re-sort itself. You don't need to call this under // normal circumstances, as the set will maintain sort order as each item // is added. sort: function(options) { if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); options || (options = {}); // Run sort based on type of `comparator`. if (_.isString(this.comparator) || this.comparator.length === 1) { this.models = this.sortBy(this.comparator, this); } else { this.models.sort(_.bind(this.comparator, this)); } if (!options.silent) this.trigger('sort', this, options); return this; }, // Pluck an attribute from each model in the collection. pluck: function(attr) { return _.invoke(this.models, 'get', attr); }, // Fetch the default set of models for this collection, resetting the // collection when they arrive. If `reset: true` is passed, the response // data will be passed through the `reset` method instead of `set`. fetch: function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var success = options.success; var collection = this; options.success = function(resp) { var method = options.reset ? 'reset' : 'set'; collection[method](resp, options); if (success) success(collection, resp, options); collection.trigger('sync', collection, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Create a new instance of a model in this collection. Add the model to the // collection immediately, unless `wait: true` is passed, in which case we // wait for the server to agree. create: function(model, options) { options = options ? _.clone(options) : {}; if (!(model = this._prepareModel(model, options))) return false; if (!options.wait) this.add(model, options); var collection = this; var success = options.success; options.success = function(model, resp) { if (options.wait) collection.add(model, options); if (success) success(model, resp, options); }; model.save(null, options); return model; }, // **parse** converts a response into a list of models to be added to the // collection. The default implementation is just to pass it through. parse: function(resp, options) { return resp; }, // Create a new collection with an identical list of models as this one. clone: function() { return new this.constructor(this.models); }, // Private method to reset all internal state. Called when the collection // is first initialized or reset. _reset: function() { this.length = 0; this.models = []; this._byId = {}; }, // Prepare a hash of attributes (or other model) to be added to this // collection. _prepareModel: function(attrs, options) { if (attrs instanceof Model) return attrs; options = options ? _.clone(options) : {}; options.collection = this; var model = new this.model(attrs, options); if (!model.validationError) return model; this.trigger('invalid', this, model.validationError, options); return false; }, // Internal method to create a model's ties to a collection. _addReference: function(model, options) { this._byId[model.cid] = model; if (model.id != null) this._byId[model.id] = model; if (!model.collection) model.collection = this; model.on('all', this._onModelEvent, this); }, // Internal method to sever a model's ties to a collection. _removeReference: function(model, options) { if (this === model.collection) delete model.collection; model.off('all', this._onModelEvent, this); }, // Internal method called every time a model in the set fires an event. // Sets need to update their indexes when models change ids. All other // events simply proxy through. "add" and "remove" events that originate // in other collections are ignored. _onModelEvent: function(event, model, collection, options) { if ((event === 'add' || event === 'remove') && collection !== this) return; if (event === 'destroy') this.remove(model, options); if (model && event === 'change:' + model.idAttribute) { delete this._byId[model.previous(model.idAttribute)]; if (model.id != null) this._byId[model.id] = model; } this.trigger.apply(this, arguments); } }); // Underscore methods that we want to implement on the Collection. // 90% of the core usefulness of Backbone Collections is actually implemented // right here: var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl', 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', 'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle', 'lastIndexOf', 'isEmpty', 'chain', 'sample']; // Mix in each Underscore method as a proxy to `Collection#models`. _.each(methods, function(method) { Collection.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.models); return _[method].apply(_, args); }; }); // Underscore methods that take a property name as an argument. var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy']; // Use attributes instead of properties. _.each(attributeMethods, function(method) { Collection.prototype[method] = function(value, context) { var iterator = _.isFunction(value) ? value : function(model) { return model.get(value); }; return _[method](this.models, iterator, context); }; }); // Backbone.View // ------------- // Backbone Views are almost more convention than they are actual code. A View // is simply a JavaScript object that represents a logical chunk of UI in the // DOM. This might be a single item, an entire list, a sidebar or panel, or // even the surrounding frame which wraps your whole app. Defining a chunk of // UI as a **View** allows you to define your DOM events declaratively, without // having to worry about render order ... and makes it easy for the view to // react to specific changes in the state of your models. // Creating a Backbone.View creates its initial element outside of the DOM, // if an existing element is not provided... var View = Backbone.View = function(options) { this.cid = _.uniqueId('view'); options || (options = {}); _.extend(this, _.pick(options, viewOptions)); this._ensureElement(); this.initialize.apply(this, arguments); this.delegateEvents(); }; // Cached regex to split keys for `delegate`. var delegateEventSplitter = /^(\S+)\s*(.*)$/; // List of view options to be merged as properties. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; // Set up all inheritable **Backbone.View** properties and methods. _.extend(View.prototype, Events, { // The default `tagName` of a View's element is `"div"`. tagName: 'div', // jQuery delegate for element lookup, scoped to DOM elements within the // current view. This should be preferred to global lookups where possible. $: function(selector) { return this.$el.find(selector); }, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // **render** is the core function that your view should override, in order // to populate its element (`this.el`), with the appropriate HTML. The // convention is for **render** to always return `this`. render: function() { return this; }, // Remove this view by taking the element out of the DOM, and removing any // applicable Backbone.Events listeners. remove: function() { this.$el.remove(); this.stopListening(); return this; }, // Change the view's element (`this.el` property), including event // re-delegation. setElement: function(element, delegate) { if (this.$el) this.undelegateEvents(); this.$el = element instanceof Backbone.$ ? element : Backbone.$(element); this.el = this.$el[0]; if (delegate !== false) this.delegateEvents(); return this; }, // Set callbacks, where `this.events` is a hash of // // *{"event selector": "callback"}* // // { // 'mousedown .title': 'edit', // 'click .button': 'save', // 'click .open': function(e) { ... } // } // // pairs. Callbacks will be bound to the view, with `this` set properly. // Uses event delegation for efficiency. // Omitting the selector binds the event to `this.el`. // This only works for delegate-able events: not `focus`, `blur`, and // not `change`, `submit`, and `reset` in Internet Explorer. delegateEvents: function(events) { if (!(events || (events = _.result(this, 'events')))) return this; this.undelegateEvents(); for (var key in events) { var method = events[key]; if (!_.isFunction(method)) method = this[events[key]]; if (!method) continue; var match = key.match(delegateEventSplitter); var eventName = match[1], selector = match[2]; method = _.bind(method, this); eventName += '.delegateEvents' + this.cid; if (selector === '') { this.$el.on(eventName, method); } else { this.$el.on(eventName, selector, method); } } return this; }, // Clears all callbacks previously bound to the view with `delegateEvents`. // You usually don't need to use this, but may wish to if you have multiple // Backbone views attached to the same DOM element. undelegateEvents: function() { this.$el.off('.delegateEvents' + this.cid); return this; }, // Ensure that the View has a DOM element to render into. // If `this.el` is a string, pass it through `$()`, take the first // matching element, and re-assign it to `el`. Otherwise, create // an element from the `id`, `className` and `tagName` properties. _ensureElement: function() { if (!this.el) { var attrs = _.extend({}, _.result(this, 'attributes')); if (this.id) attrs.id = _.result(this, 'id'); if (this.className) attrs['class'] = _.result(this, 'className'); var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs); this.setElement($el, false); } else { this.setElement(_.result(this, 'el'), false); } } }); // Backbone.sync // ------------- // Override this function to change the manner in which Backbone persists // models to the server. You will be passed the type of request, and the // model in question. By default, makes a RESTful Ajax request // to the model's `url()`. Some possible customizations could be: // // * Use `setTimeout` to batch rapid-fire updates into a single request. // * Send up the models as XML instead of JSON. // * Persist models via WebSockets instead of Ajax. // // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests // as `POST`, with a `_method` parameter containing the true HTTP method, // as well as all requests with the body as `application/x-www-form-urlencoded` // instead of `application/json` with the model in a param named `model`. // Useful when interfacing with server-side languages like **PHP** that make // it difficult to read the body of `PUT` requests. Backbone.sync = function(method, model, options) { var type = methodMap[method]; // Default options, unless specified. _.defaults(options || (options = {}), { emulateHTTP: Backbone.emulateHTTP, emulateJSON: Backbone.emulateJSON }); // Default JSON-request options. var params = {type: type, dataType: 'json'}; // Ensure that we have a URL. if (!options.url) { params.url = _.result(model, 'url') || urlError(); } // Ensure that we have the appropriate request data. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { params.contentType = 'application/json'; params.data = JSON.stringify(options.attrs || model.toJSON(options)); } // For older servers, emulate JSON by encoding the request into an HTML-form. if (options.emulateJSON) { params.contentType = 'application/x-www-form-urlencoded'; params.data = params.data ? {model: params.data} : {}; } // For older servers, emulate HTTP by mimicking the HTTP method with `_method` // And an `X-HTTP-Method-Override` header. if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { params.type = 'POST'; if (options.emulateJSON) params.data._method = type; var beforeSend = options.beforeSend; options.beforeSend = function(xhr) { xhr.setRequestHeader('X-HTTP-Method-Override', type); if (beforeSend) return beforeSend.apply(this, arguments); }; } // Don't process data on a non-GET request. if (params.type !== 'GET' && !options.emulateJSON) { params.processData = false; } // If we're sending a `PATCH` request, and we're in an old Internet Explorer // that still has ActiveX enabled by default, override jQuery to use that // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. if (params.type === 'PATCH' && noXhrPatch) { params.xhr = function() { return new ActiveXObject("Microsoft.XMLHTTP"); }; } // Make the request, allowing the user to override any Ajax options. var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); model.trigger('request', model, xhr, options); return xhr; }; var noXhrPatch = typeof window !== 'undefined' && !!window.ActiveXObject && !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent); // Map from CRUD to HTTP for our default `Backbone.sync` implementation. var methodMap = { 'create': 'POST', 'update': 'PUT', 'patch': 'PATCH', 'delete': 'DELETE', 'read': 'GET' }; // Set the default implementation of `Backbone.ajax` to proxy through to `$`. // Override this if you'd like to use a different library. Backbone.ajax = function() { return Backbone.$.ajax.apply(Backbone.$, arguments); }; // Backbone.Router // --------------- // Routers map faux-URLs to actions, and fire events when routes are // matched. Creating a new one sets its `routes` hash, if not set statically. var Router = Backbone.Router = function(options) { options || (options = {}); if (options.routes) this.routes = options.routes; this._bindRoutes(); this.initialize.apply(this, arguments); }; // Cached regular expressions for matching named param parts and splatted // parts of route strings. var optionalParam = /\((.*?)\)/g; var namedParam = /(\(\?)?:\w+/g; var splatParam = /\*\w+/g; var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; // Set up all inheritable **Backbone.Router** properties and methods. _.extend(Router.prototype, Events, { // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Manually bind a single named route to a callback. For example: // // this.route('search/:query/p:num', 'search', function(query, num) { // ... // }); // route: function(route, name, callback) { if (!_.isRegExp(route)) route = this._routeToRegExp(route); if (_.isFunction(name)) { callback = name; name = ''; } if (!callback) callback = this[name]; var router = this; Backbone.history.route(route, function(fragment) { var args = router._extractParameters(route, fragment); router.execute(callback, args); router.trigger.apply(router, ['route:' + name].concat(args)); router.trigger('route', name, args); Backbone.history.trigger('route', router, name, args); }); return this; }, // Execute a route handler with the provided parameters. This is an // excellent place to do pre-route setup or post-route cleanup. execute: function(callback, args) { if (callback) callback.apply(this, args); }, // Simple proxy to `Backbone.history` to save a fragment into the history. navigate: function(fragment, options) { Backbone.history.navigate(fragment, options); return this; }, // Bind all defined routes to `Backbone.history`. We have to reverse the // order of the routes here to support behavior where the most general // routes can be defined at the bottom of the route map. _bindRoutes: function() { if (!this.routes) return; this.routes = _.result(this, 'routes'); var route, routes = _.keys(this.routes); while ((route = routes.pop()) != null) { this.route(route, this.routes[route]); } }, // Convert a route string into a regular expression, suitable for matching // against the current location hash. _routeToRegExp: function(route) { route = route.replace(escapeRegExp, '\\$&') .replace(optionalParam, '(?:$1)?') .replace(namedParam, function(match, optional) { return optional ? match : '([^/?]+)'; }) .replace(splatParam, '([^?]*?)'); return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); }, // Given a route, and a URL fragment that it matches, return the array of // extracted decoded parameters. Empty or unmatched parameters will be // treated as `null` to normalize cross-browser behavior. _extractParameters: function(route, fragment) { var params = route.exec(fragment).slice(1); return _.map(params, function(param, i) { // Don't decode the search params. if (i === params.length - 1) return param || null; return param ? decodeURIComponent(param) : null; }); } }); // Backbone.History // ---------------- // Handles cross-browser history management, based on either // [pushState](http://diveintohtml5.info/history.html) and real URLs, or // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) // and URL fragments. If the browser supports neither (old IE, natch), // falls back to polling. var History = Backbone.History = function() { this.handlers = []; _.bindAll(this, 'checkUrl'); // Ensure that `History` can be used outside of the browser. if (typeof window !== 'undefined') { this.location = window.location; this.history = window.history; } }; // Cached regex for stripping a leading hash/slash and trailing space. var routeStripper = /^[#\/]|\s+$/g; // Cached regex for stripping leading and trailing slashes. var rootStripper = /^\/+|\/+$/g; // Cached regex for detecting MSIE. var isExplorer = /msie [\w.]+/; // Cached regex for removing a trailing slash. var trailingSlash = /\/$/; // Cached regex for stripping urls of hash. var pathStripper = /#.*$/; // Has the history handling already been started? History.started = false; // Set up all inheritable **Backbone.History** properties and methods. _.extend(History.prototype, Events, { // The default interval to poll for hash changes, if necessary, is // twenty times a second. interval: 50, // Are we at the app root? atRoot: function() { return this.location.pathname.replace(/[^\/]$/, '$&/') === this.root; }, // Gets the true hash value. Cannot use location.hash directly due to bug // in Firefox where location.hash will always be decoded. getHash: function(window) { var match = (window || this).location.href.match(/#(.*)$/); return match ? match[1] : ''; }, // Get the cross-browser normalized URL fragment, either from the URL, // the hash, or the override. getFragment: function(fragment, forcePushState) { if (fragment == null) { if (this._hasPushState || !this._wantsHashChange || forcePushState) { fragment = decodeURI(this.location.pathname + this.location.search); var root = this.root.replace(trailingSlash, ''); if (!fragment.indexOf(root)) fragment = fragment.slice(root.length); } else { fragment = this.getHash(); } } return fragment.replace(routeStripper, ''); }, // Start the hash change handling, returning `true` if the current URL matches // an existing route, and `false` otherwise. start: function(options) { if (History.started) throw new Error("Backbone.history has already been started"); History.started = true; // Figure out the initial configuration. Do we need an iframe? // Is pushState desired ... is it available? this.options = _.extend({root: '/'}, this.options, options); this.root = this.options.root; this._wantsHashChange = this.options.hashChange !== false; this._wantsPushState = !!this.options.pushState; this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); var fragment = this.getFragment(); var docMode = document.documentMode; var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); // Normalize root to always include a leading and trailing slash. this.root = ('/' + this.root + '/').replace(rootStripper, '/'); if (oldIE && this._wantsHashChange) { var frame = Backbone.$('<iframe src="javascript:0" tabindex="-1">'); this.iframe = frame.hide().appendTo('body')[0].contentWindow; this.navigate(fragment); } // Depending on whether we're using pushState or hashes, and whether // 'onhashchange' is supported, determine how we check the URL state. if (this._hasPushState) { Backbone.$(window).on('popstate', this.checkUrl); } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) { Backbone.$(window).on('hashchange', this.checkUrl); } else if (this._wantsHashChange) { this._checkUrlInterval = setInterval(this.checkUrl, this.interval); } // Determine if we need to change the base url, for a pushState link // opened by a non-pushState browser. this.fragment = fragment; var loc = this.location; // Transition from hashChange to pushState or vice versa if both are // requested. if (this._wantsHashChange && this._wantsPushState) { // If we've started off with a route from a `pushState`-enabled // browser, but we're currently in a browser that doesn't support it... if (!this._hasPushState && !this.atRoot()) { this.fragment = this.getFragment(null, true); this.location.replace(this.root + '#' + this.fragment); // Return immediately as browser will do redirect to new url return true; // Or if we've started out with a hash-based route, but we're currently // in a browser where it could be `pushState`-based instead... } else if (this._hasPushState && this.atRoot() && loc.hash) { this.fragment = this.getHash().replace(routeStripper, ''); this.history.replaceState({}, document.title, this.root + this.fragment); } } if (!this.options.silent) return this.loadUrl(); }, // Disable Backbone.history, perhaps temporarily. Not useful in a real app, // but possibly useful for unit testing Routers. stop: function() { Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl); if (this._checkUrlInterval) clearInterval(this._checkUrlInterval); History.started = false; }, // Add a route to be tested when the fragment changes. Routes added later // may override previous routes. route: function(route, callback) { this.handlers.unshift({route: route, callback: callback}); }, // Checks the current URL to see if it has changed, and if it has, // calls `loadUrl`, normalizing across the hidden iframe. checkUrl: function(e) { var current = this.getFragment(); if (current === this.fragment && this.iframe) { current = this.getFragment(this.getHash(this.iframe)); } if (current === this.fragment) return false; if (this.iframe) this.navigate(current); this.loadUrl(); }, // Attempt to load the current URL fragment. If a route succeeds with a // match, returns `true`. If no defined routes matches the fragment, // returns `false`. loadUrl: function(fragment) { fragment = this.fragment = this.getFragment(fragment); return _.any(this.handlers, function(handler) { if (handler.route.test(fragment)) { handler.callback(fragment); return true; } }); }, // Save a fragment into the hash history, or replace the URL state if the // 'replace' option is passed. You are responsible for properly URL-encoding // the fragment in advance. // // The options object can contain `trigger: true` if you wish to have the // route callback be fired (not usually desirable), or `replace: true`, if // you wish to modify the current URL without adding an entry to the history. navigate: function(fragment, options) { if (!History.started) return false; if (!options || options === true) options = {trigger: !!options}; var url = this.root + (fragment = this.getFragment(fragment || '')); // Strip the hash for matching. fragment = fragment.replace(pathStripper, ''); if (this.fragment === fragment) return; this.fragment = fragment; // Don't include a trailing slash on the root. if (fragment === '' && url !== '/') url = url.slice(0, -1); // If pushState is available, we use it to set the fragment as a real URL. if (this._hasPushState) { this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); // If hash changes haven't been explicitly disabled, update the hash // fragment to store history. } else if (this._wantsHashChange) { this._updateHash(this.location, fragment, options.replace); if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) { // Opening and closing the iframe tricks IE7 and earlier to push a // history entry on hash-tag change. When replace is true, we don't // want this. if(!options.replace) this.iframe.document.open().close(); this._updateHash(this.iframe.location, fragment, options.replace); } // If you've told us that you explicitly don't want fallback hashchange- // based history, then `navigate` becomes a page refresh. } else { return this.location.assign(url); } if (options.trigger) return this.loadUrl(fragment); }, // Update the hash location, either replacing the current entry, or adding // a new one to the browser history. _updateHash: function(location, fragment, replace) { if (replace) { var href = location.href.replace(/(javascript:|#).*$/, ''); location.replace(href + '#' + fragment); } else { // Some browsers require that `hash` contains a leading #. location.hash = '#' + fragment; } } }); // Create the default Backbone.history. Backbone.history = new History; // Helpers // ------- // Helper function to correctly set up the prototype chain, for subclasses. // Similar to `goog.inherits`, but uses a hash of prototype properties and // class properties to be extended. var extend = function(protoProps, staticProps) { var parent = this; var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent's constructor. if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function(){ return parent.apply(this, arguments); }; } // Add static properties to the constructor function, if supplied. _.extend(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function. var Surrogate = function(){ this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate; // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps) _.extend(child.prototype, protoProps); // Set a convenience property in case the parent's prototype is needed // later. child.__super__ = parent.prototype; return child; }; // Set up inheritance for the model, collection, router, view and history. Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend; // Throw an error when a URL is needed, and none is supplied. var urlError = function() { throw new Error('A "url" property or function must be specified'); }; // Wrap an optional error callback with a fallback error event. var wrapError = function(model, options) { var error = options.error; options.error = function(resp) { if (error) error(model, resp, options); model.trigger('error', model, resp, options); }; }; return Backbone; }));
client/components/header.js
chesterhow/leaderboard
import React, { Component } from 'react'; import AddForm from './add_form'; class Header extends Component { constructor(props) { super(props); this.state = { showAddForm: false }; this.toggleForm = this.toggleForm.bind(this); } addListing(listing) { Meteor.call('listings.insert', listing); } toggleForm() { this.setState({ showAddForm: !this.state.showAddForm }); } render() { return ( <div className="header"> <div className="header-container"> <div className="header-box"> <p className="header-title">Leaderboard</p> </div> <div className="header-box"> <input className="button header-button" type="button" value="ADD" onClick={this.toggleForm} /> </div> </div> {(this.state.showAddForm) ? ( <AddForm toggleForm={this.toggleForm} addListing={this.addListing} /> ) : null} </div> ); } } export default Header;
server/sonar-web/src/main/js/apps/component-measures/components/IconTreemap.js
Builders-SonarSource/sonarqube-bis
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; export default function IconTreemap () { return ( <svg className="measure-tab-icon" viewBox="0 0 448 448" fillRule="evenodd" clipRule="evenodd" strokeLinejoin="round" strokeMiterlimit="1.414"> <path d="M0 0h224v448H0zM256 0h192v256H256zM256 288h192v160H256z"/> </svg> ); }
src/client/components/UserMenuWidget/UserMenuWidget.js
vidaaudrey/trippian
import log from '../../log' import React from 'react' import { Link } from 'react-router' import store from '../../redux/store' import { FormattedMessage } from 'react-intl' const UserMenuWidget = ({ displayName, isAdmin, picture, isAuthed }) => { // const { // } = store.getState().appState.get('user') return ( <li className="dropdown"> <a href="#" className="dropdown-toggle" data-toggle="dropdown"> <FormattedMessage id="UserMenuWdiget.welcomeMessage" description="welcomeMessage" defaultMessage="Hello"/> <span className="circle-image nav-user-avatar"> <img src={picture} alt={displayName} /> </span> <b className="caret"></b> </a> <ul className="dropdown-menu"> <li> <Link to='dashboard'> <FormattedMessage id="app-pages.user-dashboard" description="the link for user dashboard" defaultMessage="User Dashboard"/> </Link> </li> {isAdmin && <li><Link to='admin'>Settings</Link></li>} {isAuthed && <li><Link to="login/logout">Logout </Link></li>} </ul> </li> ) } UserMenuWidget.displayName = 'UserMenuWidget' export default UserMenuWidget
ajax/libs/react-select/1.2.0/react-select.js
extend1994/cdnjs
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react-input-autosize'), require('classnames'), require('prop-types'), require('react'), require('react-dom')) : typeof define === 'function' && define.amd ? define(['react-input-autosize', 'classnames', 'prop-types', 'react', 'react-dom'], factory) : (global.Select = factory(global.AutosizeInput,global.classNames,global.PropTypes,global.React,global.ReactDOM)); }(this, (function (AutosizeInput,classNames,PropTypes,React,reactDom) { 'use strict'; AutosizeInput = AutosizeInput && AutosizeInput.hasOwnProperty('default') ? AutosizeInput['default'] : AutosizeInput; classNames = classNames && classNames.hasOwnProperty('default') ? classNames['default'] : classNames; PropTypes = PropTypes && PropTypes.hasOwnProperty('default') ? PropTypes['default'] : PropTypes; var React__default = 'default' in React ? React['default'] : React; var arrowRenderer = function arrowRenderer(_ref) { var onMouseDown = _ref.onMouseDown; return React__default.createElement('span', { className: 'Select-arrow', onMouseDown: onMouseDown }); }; arrowRenderer.propTypes = { onMouseDown: PropTypes.func }; var clearRenderer = function clearRenderer() { return React__default.createElement('span', { className: 'Select-clear', dangerouslySetInnerHTML: { __html: '&times;' } }); }; var map = [{ 'base': 'A', 'letters': /[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g }, { 'base': 'AA', 'letters': /[\uA732]/g }, { 'base': 'AE', 'letters': /[\u00C6\u01FC\u01E2]/g }, { 'base': 'AO', 'letters': /[\uA734]/g }, { 'base': 'AU', 'letters': /[\uA736]/g }, { 'base': 'AV', 'letters': /[\uA738\uA73A]/g }, { 'base': 'AY', 'letters': /[\uA73C]/g }, { 'base': 'B', 'letters': /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g }, { 'base': 'C', 'letters': /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g }, { 'base': 'D', 'letters': /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g }, { 'base': 'DZ', 'letters': /[\u01F1\u01C4]/g }, { 'base': 'Dz', 'letters': /[\u01F2\u01C5]/g }, { 'base': 'E', 'letters': /[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g }, { 'base': 'F', 'letters': /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g }, { 'base': 'G', 'letters': /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g }, { 'base': 'H', 'letters': /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g }, { 'base': 'I', 'letters': /[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g }, { 'base': 'J', 'letters': /[\u004A\u24BF\uFF2A\u0134\u0248]/g }, { 'base': 'K', 'letters': /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g }, { 'base': 'L', 'letters': /[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g }, { 'base': 'LJ', 'letters': /[\u01C7]/g }, { 'base': 'Lj', 'letters': /[\u01C8]/g }, { 'base': 'M', 'letters': /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g }, { 'base': 'N', 'letters': /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g }, { 'base': 'NJ', 'letters': /[\u01CA]/g }, { 'base': 'Nj', 'letters': /[\u01CB]/g }, { 'base': 'O', 'letters': /[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g }, { 'base': 'OI', 'letters': /[\u01A2]/g }, { 'base': 'OO', 'letters': /[\uA74E]/g }, { 'base': 'OU', 'letters': /[\u0222]/g }, { 'base': 'P', 'letters': /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g }, { 'base': 'Q', 'letters': /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g }, { 'base': 'R', 'letters': /[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g }, { 'base': 'S', 'letters': /[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g }, { 'base': 'T', 'letters': /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g }, { 'base': 'TZ', 'letters': /[\uA728]/g }, { 'base': 'U', 'letters': /[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g }, { 'base': 'V', 'letters': /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g }, { 'base': 'VY', 'letters': /[\uA760]/g }, { 'base': 'W', 'letters': /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g }, { 'base': 'X', 'letters': /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g }, { 'base': 'Y', 'letters': /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g }, { 'base': 'Z', 'letters': /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g }, { 'base': 'a', 'letters': /[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g }, { 'base': 'aa', 'letters': /[\uA733]/g }, { 'base': 'ae', 'letters': /[\u00E6\u01FD\u01E3]/g }, { 'base': 'ao', 'letters': /[\uA735]/g }, { 'base': 'au', 'letters': /[\uA737]/g }, { 'base': 'av', 'letters': /[\uA739\uA73B]/g }, { 'base': 'ay', 'letters': /[\uA73D]/g }, { 'base': 'b', 'letters': /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g }, { 'base': 'c', 'letters': /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g }, { 'base': 'd', 'letters': /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g }, { 'base': 'dz', 'letters': /[\u01F3\u01C6]/g }, { 'base': 'e', 'letters': /[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g }, { 'base': 'f', 'letters': /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g }, { 'base': 'g', 'letters': /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g }, { 'base': 'h', 'letters': /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g }, { 'base': 'hv', 'letters': /[\u0195]/g }, { 'base': 'i', 'letters': /[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g }, { 'base': 'j', 'letters': /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g }, { 'base': 'k', 'letters': /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g }, { 'base': 'l', 'letters': /[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g }, { 'base': 'lj', 'letters': /[\u01C9]/g }, { 'base': 'm', 'letters': /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g }, { 'base': 'n', 'letters': /[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g }, { 'base': 'nj', 'letters': /[\u01CC]/g }, { 'base': 'o', 'letters': /[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g }, { 'base': 'oi', 'letters': /[\u01A3]/g }, { 'base': 'ou', 'letters': /[\u0223]/g }, { 'base': 'oo', 'letters': /[\uA74F]/g }, { 'base': 'p', 'letters': /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g }, { 'base': 'q', 'letters': /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g }, { 'base': 'r', 'letters': /[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g }, { 'base': 's', 'letters': /[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g }, { 'base': 't', 'letters': /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g }, { 'base': 'tz', 'letters': /[\uA729]/g }, { 'base': 'u', 'letters': /[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g }, { 'base': 'v', 'letters': /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g }, { 'base': 'vy', 'letters': /[\uA761]/g }, { 'base': 'w', 'letters': /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g }, { 'base': 'x', 'letters': /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g }, { 'base': 'y', 'letters': /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g }, { 'base': 'z', 'letters': /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g }]; var stripDiacritics = function stripDiacritics(str) { for (var i = 0; i < map.length; i++) { str = str.replace(map[i].letters, map[i].base); } return str; }; var trim = function trim(str) { return str.replace(/^\s+|\s+$/g, ''); }; var isValid = function isValid(value) { return typeof value !== 'undefined' && value !== null && value !== ''; }; var filterOptions = function filterOptions(options, filterValue, excludeOptions, props) { if (props.ignoreAccents) { filterValue = stripDiacritics(filterValue); } if (props.ignoreCase) { filterValue = filterValue.toLowerCase(); } if (props.trimFilter) { filterValue = trim(filterValue); } if (excludeOptions) excludeOptions = excludeOptions.map(function (i) { return i[props.valueKey]; }); return options.filter(function (option) { if (excludeOptions && excludeOptions.indexOf(option[props.valueKey]) > -1) return false; if (props.filterOption) return props.filterOption.call(undefined, option, filterValue); if (!filterValue) return true; var value = option[props.valueKey]; var label = option[props.labelKey]; var hasValue = isValid(value); var hasLabel = isValid(label); if (!hasValue && !hasLabel) { return false; } var valueTest = hasValue ? String(value) : null; var labelTest = hasLabel ? String(label) : null; if (props.ignoreAccents) { if (valueTest && props.matchProp !== 'label') valueTest = stripDiacritics(valueTest); if (labelTest && props.matchProp !== 'value') labelTest = stripDiacritics(labelTest); } if (props.ignoreCase) { if (valueTest && props.matchProp !== 'label') valueTest = valueTest.toLowerCase(); if (labelTest && props.matchProp !== 'value') labelTest = labelTest.toLowerCase(); } return props.matchPos === 'start' ? valueTest && props.matchProp !== 'label' && valueTest.substr(0, filterValue.length) === filterValue || labelTest && props.matchProp !== 'value' && labelTest.substr(0, filterValue.length) === filterValue : valueTest && props.matchProp !== 'label' && valueTest.indexOf(filterValue) >= 0 || labelTest && props.matchProp !== 'value' && labelTest.indexOf(filterValue) >= 0; }); }; var menuRenderer = function menuRenderer(_ref) { var focusedOption = _ref.focusedOption, focusOption = _ref.focusOption, inputValue = _ref.inputValue, instancePrefix = _ref.instancePrefix, onFocus = _ref.onFocus, onOptionRef = _ref.onOptionRef, onSelect = _ref.onSelect, optionClassName = _ref.optionClassName, optionComponent = _ref.optionComponent, optionRenderer = _ref.optionRenderer, options = _ref.options, removeValue = _ref.removeValue, selectValue = _ref.selectValue, valueArray = _ref.valueArray, valueKey = _ref.valueKey; var Option = optionComponent; return options.map(function (option, i) { var isSelected = valueArray && valueArray.some(function (x) { return x[valueKey] === option[valueKey]; }); var isFocused = option === focusedOption; var optionClass = classNames(optionClassName, { 'Select-option': true, 'is-selected': isSelected, 'is-focused': isFocused, 'is-disabled': option.disabled }); return React__default.createElement( Option, { className: optionClass, focusOption: focusOption, inputValue: inputValue, instancePrefix: instancePrefix, isDisabled: option.disabled, isFocused: isFocused, isSelected: isSelected, key: 'option-' + i + '-' + option[valueKey], onFocus: onFocus, onSelect: onSelect, option: option, optionIndex: i, ref: function ref(_ref2) { onOptionRef(_ref2, isFocused); }, removeValue: removeValue, selectValue: selectValue }, optionRenderer(option, i, inputValue) ); }); }; menuRenderer.propTypes = { focusOption: PropTypes.func, focusedOption: PropTypes.object, inputValue: PropTypes.string, instancePrefix: PropTypes.string, onFocus: PropTypes.func, onOptionRef: PropTypes.func, onSelect: PropTypes.func, optionClassName: PropTypes.string, optionComponent: PropTypes.func, optionRenderer: PropTypes.func, options: PropTypes.array, removeValue: PropTypes.func, selectValue: PropTypes.func, valueArray: PropTypes.array, valueKey: PropTypes.string }; var blockEvent = (function (event) { event.preventDefault(); event.stopPropagation(); if (event.target.tagName !== 'A' || !('href' in event.target)) { return; } if (event.target.target) { window.open(event.target.href, event.target.target); } else { window.location.href = event.target.href; } }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var asyncGenerator = function () { function AwaitValue(value) { this.value = value; } function AsyncGenerator(gen) { var front, back; function send(key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg); var value = result.value; if (value instanceof AwaitValue) { Promise.resolve(value.value).then(function (arg) { resume("next", arg); }, function (arg) { resume("throw", arg); }); } else { settle(result.done ? "return" : "normal", result.value); } } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: true }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; if (typeof gen.return !== "function") { this.return = undefined; } } if (typeof Symbol === "function" && Symbol.asyncIterator) { AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; }; } AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }; AsyncGenerator.prototype.throw = function (arg) { return this._invoke("throw", arg); }; AsyncGenerator.prototype.return = function (arg) { return this._invoke("return", arg); }; return { wrap: function (fn) { return function () { return new AsyncGenerator(fn.apply(this, arguments)); }; }, await: function (value) { return new AwaitValue(value); } }; }(); 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 defineProperty = function (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; }; 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 Option = function (_React$Component) { inherits(Option, _React$Component); function Option(props) { classCallCheck(this, Option); var _this = possibleConstructorReturn(this, (Option.__proto__ || Object.getPrototypeOf(Option)).call(this, props)); _this.handleMouseDown = _this.handleMouseDown.bind(_this); _this.handleMouseEnter = _this.handleMouseEnter.bind(_this); _this.handleMouseMove = _this.handleMouseMove.bind(_this); _this.handleTouchStart = _this.handleTouchStart.bind(_this); _this.handleTouchEnd = _this.handleTouchEnd.bind(_this); _this.handleTouchMove = _this.handleTouchMove.bind(_this); _this.onFocus = _this.onFocus.bind(_this); return _this; } createClass(Option, [{ key: 'handleMouseDown', value: function handleMouseDown(event) { event.preventDefault(); event.stopPropagation(); this.props.onSelect(this.props.option, event); } }, { key: 'handleMouseEnter', value: function handleMouseEnter(event) { this.onFocus(event); } }, { key: 'handleMouseMove', value: function handleMouseMove(event) { this.onFocus(event); } }, { key: 'handleTouchEnd', value: function handleTouchEnd(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; this.handleMouseDown(event); } }, { key: 'handleTouchMove', value: function handleTouchMove() { // Set a flag that the view is being dragged this.dragging = true; } }, { key: 'handleTouchStart', value: function handleTouchStart() { // Set a flag that the view is not being dragged this.dragging = false; } }, { key: 'onFocus', value: function onFocus(event) { if (!this.props.isFocused) { this.props.onFocus(this.props.option, event); } } }, { key: 'render', value: function render() { var _props = this.props, option = _props.option, instancePrefix = _props.instancePrefix, optionIndex = _props.optionIndex; var className = classNames(this.props.className, option.className); return option.disabled ? React__default.createElement( 'div', { className: className, onMouseDown: blockEvent, onClick: blockEvent }, this.props.children ) : React__default.createElement( 'div', { className: className, style: option.style, role: 'option', 'aria-label': option.label, onMouseDown: this.handleMouseDown, onMouseEnter: this.handleMouseEnter, onMouseMove: this.handleMouseMove, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove, onTouchEnd: this.handleTouchEnd, id: instancePrefix + '-option-' + optionIndex, title: option.title }, this.props.children ); } }]); return Option; }(React__default.Component); Option.propTypes = { children: PropTypes.node, className: PropTypes.string, // className (based on mouse position) instancePrefix: PropTypes.string.isRequired, // unique prefix for the ids (used for aria) isDisabled: PropTypes.bool, // the option is disabled isFocused: PropTypes.bool, // the option is focused isSelected: PropTypes.bool, // the option is selected onFocus: PropTypes.func, // method to handle mouseEnter on option element onSelect: PropTypes.func, // method to handle click on option element onUnfocus: PropTypes.func, // method to handle mouseLeave on option element option: PropTypes.object.isRequired, // object that is base for that option optionIndex: PropTypes.number // index of the option, used to generate unique ids for aria }; var Value = function (_React$Component) { inherits(Value, _React$Component); function Value(props) { classCallCheck(this, Value); var _this = possibleConstructorReturn(this, (Value.__proto__ || Object.getPrototypeOf(Value)).call(this, props)); _this.handleMouseDown = _this.handleMouseDown.bind(_this); _this.onRemove = _this.onRemove.bind(_this); _this.handleTouchEndRemove = _this.handleTouchEndRemove.bind(_this); _this.handleTouchMove = _this.handleTouchMove.bind(_this); _this.handleTouchStart = _this.handleTouchStart.bind(_this); return _this; } createClass(Value, [{ key: 'handleMouseDown', value: function handleMouseDown(event) { if (event.type === 'mousedown' && event.button !== 0) { return; } if (this.props.onClick) { event.stopPropagation(); this.props.onClick(this.props.value, event); return; } if (this.props.value.href) { event.stopPropagation(); } } }, { key: 'onRemove', value: function onRemove(event) { event.preventDefault(); event.stopPropagation(); this.props.onRemove(this.props.value); } }, { key: 'handleTouchEndRemove', value: function handleTouchEndRemove(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Fire the mouse events this.onRemove(event); } }, { key: 'handleTouchMove', value: function handleTouchMove() { // Set a flag that the view is being dragged this.dragging = true; } }, { key: 'handleTouchStart', value: function handleTouchStart() { // Set a flag that the view is not being dragged this.dragging = false; } }, { key: 'renderRemoveIcon', value: function renderRemoveIcon() { if (this.props.disabled || !this.props.onRemove) return; return React__default.createElement( 'span', { className: 'Select-value-icon', 'aria-hidden': 'true', onMouseDown: this.onRemove, onTouchEnd: this.handleTouchEndRemove, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove }, '\xD7' ); } }, { key: 'renderLabel', value: function renderLabel() { var className = 'Select-value-label'; return this.props.onClick || this.props.value.href ? React__default.createElement( 'a', { className: className, href: this.props.value.href, target: this.props.value.target, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleMouseDown }, this.props.children ) : React__default.createElement( 'span', { className: className, role: 'option', 'aria-selected': 'true', id: this.props.id }, this.props.children ); } }, { key: 'render', value: function render() { return React__default.createElement( 'div', { className: classNames('Select-value', this.props.value.className), style: this.props.value.style, title: this.props.value.title }, this.renderRemoveIcon(), this.renderLabel() ); } }]); return Value; }(React__default.Component); Value.propTypes = { children: PropTypes.node, disabled: PropTypes.bool, // disabled prop passed to ReactSelect id: PropTypes.string, // Unique id for the value - used for aria onClick: PropTypes.func, // method to handle click on value label onRemove: PropTypes.func, // method to handle removal of the value value: PropTypes.object.isRequired // the option object for this value }; /*! Copyright (c) 2017 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/react-select */ var stringifyValue = function stringifyValue(value) { return typeof value === 'string' ? value : value !== null && JSON.stringify(value) || ''; }; var stringOrNode = PropTypes.oneOfType([PropTypes.string, PropTypes.node]); var stringOrNumber = PropTypes.oneOfType([PropTypes.string, PropTypes.number]); var instanceId = 1; var shouldShowValue = function shouldShowValue(state, props) { var inputValue = state.inputValue, isPseudoFocused = state.isPseudoFocused, isFocused = state.isFocused; var onSelectResetsInput = props.onSelectResetsInput; if (!inputValue) return true; if (!onSelectResetsInput) { return !(!isFocused && isPseudoFocused || isFocused && !isPseudoFocused); } return false; }; var shouldShowPlaceholder = function shouldShowPlaceholder(state, props, isOpen) { var inputValue = state.inputValue, isPseudoFocused = state.isPseudoFocused, isFocused = state.isFocused; var onSelectResetsInput = props.onSelectResetsInput; return !inputValue || !onSelectResetsInput && !isOpen && !isPseudoFocused && !isFocused; }; /** * Retrieve a value from the given options and valueKey * @param {String|Number|Array} value - the selected value(s) * @param {Object} props - the Select component's props (or nextProps) */ var expandValue = function expandValue(value, props) { var valueType = typeof value === 'undefined' ? 'undefined' : _typeof(value); if (valueType !== 'string' && valueType !== 'number' && valueType !== 'boolean') return value; var options = props.options, valueKey = props.valueKey; if (!options) return; for (var i = 0; i < options.length; i++) { if (String(options[i][valueKey]) === String(value)) return options[i]; } }; var handleRequired = function handleRequired(value, multi) { if (!value) return true; return multi ? value.length === 0 : Object.keys(value).length === 0; }; var Select$1 = function (_React$Component) { inherits(Select, _React$Component); function Select(props) { classCallCheck(this, Select); var _this = possibleConstructorReturn(this, (Select.__proto__ || Object.getPrototypeOf(Select)).call(this, props)); ['clearValue', 'focusOption', 'getOptionLabel', 'handleInputBlur', 'handleInputChange', 'handleInputFocus', 'handleInputValueChange', 'handleKeyDown', 'handleMenuScroll', 'handleMouseDown', 'handleMouseDownOnArrow', 'handleMouseDownOnMenu', 'handleTouchEnd', 'handleTouchEndClearValue', 'handleTouchMove', 'handleTouchOutside', 'handleTouchStart', 'handleValueClick', 'onOptionRef', 'removeValue', 'selectValue'].forEach(function (fn) { return _this[fn] = _this[fn].bind(_this); }); _this.state = { inputValue: '', isFocused: false, isOpen: false, isPseudoFocused: false, required: false }; return _this; } createClass(Select, [{ key: 'componentWillMount', value: function componentWillMount() { this._instancePrefix = 'react-select-' + (this.props.instanceId || ++instanceId) + '-'; var valueArray = this.getValueArray(this.props.value); if (this.props.required) { this.setState({ required: handleRequired(valueArray[0], this.props.multi) }); } } }, { key: 'componentDidMount', value: function componentDidMount() { if (typeof this.props.autofocus !== 'undefined' && typeof console !== 'undefined') { console.warn('Warning: The autofocus prop has changed to autoFocus, support will be removed after react-select@1.0'); } if (this.props.autoFocus || this.props.autofocus) { this.focus(); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var valueArray = this.getValueArray(nextProps.value, nextProps); if (nextProps.required) { this.setState({ required: handleRequired(valueArray[0], nextProps.multi) }); } else if (this.props.required) { // Used to be required but it's not any more this.setState({ required: false }); } if (this.state.inputValue && this.props.value !== nextProps.value && nextProps.onSelectResetsInput) { this.setState({ inputValue: this.handleInputValueChange('') }); } } }, { key: 'componentDidUpdate', value: function componentDidUpdate(prevProps, prevState) { // focus to the selected option if (this.menu && this.focused && this.state.isOpen && !this.hasScrolledToOption) { var focusedOptionNode = reactDom.findDOMNode(this.focused); var menuNode = reactDom.findDOMNode(this.menu); var scrollTop = menuNode.scrollTop; var scrollBottom = scrollTop + menuNode.offsetHeight; var optionTop = focusedOptionNode.offsetTop; var optionBottom = optionTop + focusedOptionNode.offsetHeight; if (scrollTop > optionTop || scrollBottom < optionBottom) { menuNode.scrollTop = focusedOptionNode.offsetTop; } // We still set hasScrolledToOption to true even if we didn't // actually need to scroll, as we've still confirmed that the // option is in view. this.hasScrolledToOption = true; } else if (!this.state.isOpen) { this.hasScrolledToOption = false; } if (this._scrollToFocusedOptionOnUpdate && this.focused && this.menu) { this._scrollToFocusedOptionOnUpdate = false; var focusedDOM = reactDom.findDOMNode(this.focused); var menuDOM = reactDom.findDOMNode(this.menu); var focusedRect = focusedDOM.getBoundingClientRect(); var menuRect = menuDOM.getBoundingClientRect(); if (focusedRect.bottom > menuRect.bottom) { menuDOM.scrollTop = focusedDOM.offsetTop + focusedDOM.clientHeight - menuDOM.offsetHeight; } else if (focusedRect.top < menuRect.top) { menuDOM.scrollTop = focusedDOM.offsetTop; } } if (this.props.scrollMenuIntoView && this.menuContainer) { var menuContainerRect = this.menuContainer.getBoundingClientRect(); if (window.innerHeight < menuContainerRect.bottom + this.props.menuBuffer) { window.scrollBy(0, menuContainerRect.bottom + this.props.menuBuffer - window.innerHeight); } } if (prevProps.disabled !== this.props.disabled) { this.setState({ isFocused: false }); // eslint-disable-line react/no-did-update-set-state this.closeMenu(); } if (prevState.isOpen !== this.state.isOpen) { this.toggleTouchOutsideEvent(this.state.isOpen); var handler = this.state.isOpen ? this.props.onOpen : this.props.onClose; handler && handler(); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.toggleTouchOutsideEvent(false); } }, { key: 'toggleTouchOutsideEvent', value: function toggleTouchOutsideEvent(enabled) { if (enabled) { if (!document.addEventListener && document.attachEvent) { document.attachEvent('ontouchstart', this.handleTouchOutside); } else { document.addEventListener('touchstart', this.handleTouchOutside); } } else { if (!document.removeEventListener && document.detachEvent) { document.detachEvent('ontouchstart', this.handleTouchOutside); } else { document.removeEventListener('touchstart', this.handleTouchOutside); } } } }, { key: 'handleTouchOutside', value: function handleTouchOutside(event) { // handle touch outside on ios to dismiss menu if (this.wrapper && !this.wrapper.contains(event.target)) { this.closeMenu(); } } }, { key: 'focus', value: function focus() { if (!this.input) return; this.input.focus(); } }, { key: 'blurInput', value: function blurInput() { if (!this.input) return; this.input.blur(); } }, { key: 'handleTouchMove', value: function handleTouchMove() { // Set a flag that the view is being dragged this.dragging = true; } }, { key: 'handleTouchStart', value: function handleTouchStart() { // Set a flag that the view is not being dragged this.dragging = false; } }, { key: 'handleTouchEnd', value: function handleTouchEnd(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Fire the mouse events this.handleMouseDown(event); } }, { key: 'handleTouchEndClearValue', value: function handleTouchEndClearValue(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Clear the value this.clearValue(event); } }, { key: 'handleMouseDown', value: function handleMouseDown(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } if (event.target.tagName === 'INPUT') { if (!this.state.isFocused) { this._openAfterFocus = this.props.openOnClick; this.focus(); } else if (!this.state.isOpen) { this.setState({ isOpen: true, isPseudoFocused: false }); } return; } // prevent default event handlers event.preventDefault(); // for the non-searchable select, toggle the menu if (!this.props.searchable) { // This code means that if a select is searchable, onClick the options menu will not appear, only on subsequent click will it open. this.focus(); return this.setState({ isOpen: !this.state.isOpen }); } if (this.state.isFocused) { // On iOS, we can get into a state where we think the input is focused but it isn't really, // since iOS ignores programmatic calls to input.focus() that weren't triggered by a click event. // Call focus() again here to be safe. this.focus(); var input = this.input; var toOpen = true; if (typeof input.getInput === 'function') { // Get the actual DOM input if the ref is an <AutosizeInput /> component input = input.getInput(); } // clears the value so that the cursor will be at the end of input when the component re-renders input.value = ''; if (this._focusAfterClear) { toOpen = false; this._focusAfterClear = false; } // if the input is focused, ensure the menu is open this.setState({ isOpen: toOpen, isPseudoFocused: false, focusedOption: null }); } else { // otherwise, focus the input and open the menu this._openAfterFocus = this.props.openOnClick; this.focus(); this.setState({ focusedOption: null }); } } }, { key: 'handleMouseDownOnArrow', value: function handleMouseDownOnArrow(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } if (this.state.isOpen) { // prevent default event handlers event.stopPropagation(); event.preventDefault(); // close the menu this.closeMenu(); } else { // If the menu isn't open, let the event bubble to the main handleMouseDown this.setState({ isOpen: true }); } } }, { key: 'handleMouseDownOnMenu', value: function handleMouseDownOnMenu(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); this._openAfterFocus = true; this.focus(); } }, { key: 'closeMenu', value: function closeMenu() { if (this.props.onCloseResetsInput) { this.setState({ inputValue: this.handleInputValueChange(''), isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi }); } else { this.setState({ isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi }); } this.hasScrolledToOption = false; } }, { key: 'handleInputFocus', value: function handleInputFocus(event) { if (this.props.disabled) return; var toOpen = this.state.isOpen || this._openAfterFocus || this.props.openOnFocus; toOpen = this._focusAfterClear ? false : toOpen; //if focus happens after clear values, don't open dropdown yet. if (this.props.onFocus) { this.props.onFocus(event); } this.setState({ isFocused: true, isOpen: !!toOpen }); this._focusAfterClear = false; this._openAfterFocus = false; } }, { key: 'handleInputBlur', value: function handleInputBlur(event) { // The check for menu.contains(activeElement) is necessary to prevent IE11's scrollbar from closing the menu in certain contexts. if (this.menu && (this.menu === document.activeElement || this.menu.contains(document.activeElement))) { this.focus(); return; } if (this.props.onBlur) { this.props.onBlur(event); } var onBlurredState = { isFocused: false, isOpen: false, isPseudoFocused: false }; if (this.props.onBlurResetsInput) { onBlurredState.inputValue = this.handleInputValueChange(''); } this.setState(onBlurredState); } }, { key: 'handleInputChange', value: function handleInputChange(event) { var newInputValue = event.target.value; if (this.state.inputValue !== event.target.value) { newInputValue = this.handleInputValueChange(newInputValue); } this.setState({ inputValue: newInputValue, isOpen: true, isPseudoFocused: false }); } }, { key: 'setInputValue', value: function setInputValue(newValue) { if (this.props.onInputChange) { var nextState = this.props.onInputChange(newValue); if (nextState != null && (typeof nextState === 'undefined' ? 'undefined' : _typeof(nextState)) !== 'object') { newValue = '' + nextState; } } this.setState({ inputValue: newValue }); } }, { key: 'handleInputValueChange', value: function handleInputValueChange(newValue) { if (this.props.onInputChange) { var nextState = this.props.onInputChange(newValue); // Note: != used deliberately here to catch undefined and null if (nextState != null && (typeof nextState === 'undefined' ? 'undefined' : _typeof(nextState)) !== 'object') { newValue = '' + nextState; } } return newValue; } }, { key: 'handleKeyDown', value: function handleKeyDown(event) { if (this.props.disabled) return; if (typeof this.props.onInputKeyDown === 'function') { this.props.onInputKeyDown(event); if (event.defaultPrevented) { return; } } switch (event.keyCode) { case 8: // backspace if (!this.state.inputValue && this.props.backspaceRemoves) { event.preventDefault(); this.popValue(); } break; case 9: // tab if (event.shiftKey || !this.state.isOpen || !this.props.tabSelectsValue) { break; } event.preventDefault(); this.selectFocusedOption(); break; case 13: // enter event.preventDefault(); event.stopPropagation(); if (this.state.isOpen) { this.selectFocusedOption(); } else { this.focusNextOption(); } break; case 27: // escape event.preventDefault(); if (this.state.isOpen) { this.closeMenu(); event.stopPropagation(); } else if (this.props.clearable && this.props.escapeClearsValue) { this.clearValue(event); event.stopPropagation(); } break; case 32: // space if (this.props.searchable) { break; } event.preventDefault(); if (!this.state.isOpen) { this.focusNextOption(); break; } event.stopPropagation(); this.selectFocusedOption(); break; case 38: // up event.preventDefault(); this.focusPreviousOption(); break; case 40: // down event.preventDefault(); this.focusNextOption(); break; case 33: // page up event.preventDefault(); this.focusPageUpOption(); break; case 34: // page down event.preventDefault(); this.focusPageDownOption(); break; case 35: // end key if (event.shiftKey) { break; } event.preventDefault(); this.focusEndOption(); break; case 36: // home key if (event.shiftKey) { break; } event.preventDefault(); this.focusStartOption(); break; case 46: // delete event.preventDefault(); if (!this.state.inputValue && this.props.deleteRemoves) { this.popValue(); } break; } } }, { key: 'handleValueClick', value: function handleValueClick(option, event) { if (!this.props.onValueClick) return; this.props.onValueClick(option, event); } }, { key: 'handleMenuScroll', value: function handleMenuScroll(event) { if (!this.props.onMenuScrollToBottom) return; var target = event.target; if (target.scrollHeight > target.offsetHeight && target.scrollHeight - target.offsetHeight - target.scrollTop <= 0) { this.props.onMenuScrollToBottom(); } } }, { key: 'getOptionLabel', value: function getOptionLabel(op) { return op[this.props.labelKey]; } /** * Turns a value into an array from the given options * @param {String|Number|Array} value - the value of the select input * @param {Object} nextProps - optionally specify the nextProps so the returned array uses the latest configuration * @returns {Array} the value of the select represented in an array */ }, { key: 'getValueArray', value: function getValueArray(value) { var nextProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; /** support optionally passing in the `nextProps` so `componentWillReceiveProps` updates will function as expected */ var props = (typeof nextProps === 'undefined' ? 'undefined' : _typeof(nextProps)) === 'object' ? nextProps : this.props; if (props.multi) { if (typeof value === 'string') { value = value.split(props.delimiter); } if (!Array.isArray(value)) { if (value === null || value === undefined) return []; value = [value]; } return value.map(function (value) { return expandValue(value, props); }).filter(function (i) { return i; }); } var expandedValue = expandValue(value, props); return expandedValue ? [expandedValue] : []; } }, { key: 'setValue', value: function setValue(value) { var _this2 = this; if (this.props.autoBlur) { this.blurInput(); } if (this.props.required) { var required = handleRequired(value, this.props.multi); this.setState({ required: required }); } if (this.props.simpleValue && value) { value = this.props.multi ? value.map(function (i) { return i[_this2.props.valueKey]; }).join(this.props.delimiter) : value[this.props.valueKey]; } if (this.props.onChange) { this.props.onChange(value); } } }, { key: 'selectValue', value: function selectValue(value) { var _this3 = this; // NOTE: we actually add/set the value in a callback to make sure the // input value is empty to avoid styling issues in Chrome if (this.props.closeOnSelect) { this.hasScrolledToOption = false; } var updatedValue = this.props.onSelectResetsInput ? '' : this.state.inputValue; if (this.props.multi) { this.setState({ focusedIndex: null, inputValue: this.handleInputValueChange(updatedValue), isOpen: !this.props.closeOnSelect }, function () { var valueArray = _this3.getValueArray(_this3.props.value); if (valueArray.some(function (i) { return i[_this3.props.valueKey] === value[_this3.props.valueKey]; })) { _this3.removeValue(value); } else { _this3.addValue(value); } }); } else { this.setState({ inputValue: this.handleInputValueChange(updatedValue), isOpen: !this.props.closeOnSelect, isPseudoFocused: this.state.isFocused }, function () { _this3.setValue(value); }); } } }, { key: 'addValue', value: function addValue(value) { var valueArray = this.getValueArray(this.props.value); var visibleOptions = this._visibleOptions.filter(function (val) { return !val.disabled; }); var lastValueIndex = visibleOptions.indexOf(value); this.setValue(valueArray.concat(value)); if (visibleOptions.length - 1 === lastValueIndex) { // the last option was selected; focus the second-last one this.focusOption(visibleOptions[lastValueIndex - 1]); } else if (visibleOptions.length > lastValueIndex) { // focus the option below the selected one this.focusOption(visibleOptions[lastValueIndex + 1]); } } }, { key: 'popValue', value: function popValue() { var valueArray = this.getValueArray(this.props.value); if (!valueArray.length) return; if (valueArray[valueArray.length - 1].clearableValue === false) return; this.setValue(this.props.multi ? valueArray.slice(0, valueArray.length - 1) : null); } }, { key: 'removeValue', value: function removeValue(value) { var _this4 = this; var valueArray = this.getValueArray(this.props.value); this.setValue(valueArray.filter(function (i) { return i[_this4.props.valueKey] !== value[_this4.props.valueKey]; })); this.focus(); } }, { key: 'clearValue', value: function clearValue(event) { // if the event was triggered by a mousedown and not the primary // button, ignore it. if (event && event.type === 'mousedown' && event.button !== 0) { return; } event.preventDefault(); this.setValue(this.getResetValue()); this.setState({ inputValue: this.handleInputValueChange(''), isOpen: false }, this.focus); this._focusAfterClear = true; } }, { key: 'getResetValue', value: function getResetValue() { if (this.props.resetValue !== undefined) { return this.props.resetValue; } else if (this.props.multi) { return []; } else { return null; } } }, { key: 'focusOption', value: function focusOption(option) { this.setState({ focusedOption: option }); } }, { key: 'focusNextOption', value: function focusNextOption() { this.focusAdjacentOption('next'); } }, { key: 'focusPreviousOption', value: function focusPreviousOption() { this.focusAdjacentOption('previous'); } }, { key: 'focusPageUpOption', value: function focusPageUpOption() { this.focusAdjacentOption('page_up'); } }, { key: 'focusPageDownOption', value: function focusPageDownOption() { this.focusAdjacentOption('page_down'); } }, { key: 'focusStartOption', value: function focusStartOption() { this.focusAdjacentOption('start'); } }, { key: 'focusEndOption', value: function focusEndOption() { this.focusAdjacentOption('end'); } }, { key: 'focusAdjacentOption', value: function focusAdjacentOption(dir) { var options = this._visibleOptions.map(function (option, index) { return { option: option, index: index }; }).filter(function (option) { return !option.option.disabled; }); this._scrollToFocusedOptionOnUpdate = true; if (!this.state.isOpen) { var newState = { focusedOption: this._focusedOption || (options.length ? options[dir === 'next' ? 0 : options.length - 1].option : null), isOpen: true }; if (this.props.onSelectResetsInput) { newState.inputValue = ''; } this.setState(newState); return; } if (!options.length) return; var focusedIndex = -1; for (var i = 0; i < options.length; i++) { if (this._focusedOption === options[i].option) { focusedIndex = i; break; } } if (dir === 'next' && focusedIndex !== -1) { focusedIndex = (focusedIndex + 1) % options.length; } else if (dir === 'previous') { if (focusedIndex > 0) { focusedIndex = focusedIndex - 1; } else { focusedIndex = options.length - 1; } } else if (dir === 'start') { focusedIndex = 0; } else if (dir === 'end') { focusedIndex = options.length - 1; } else if (dir === 'page_up') { var potentialIndex = focusedIndex - this.props.pageSize; if (potentialIndex < 0) { focusedIndex = 0; } else { focusedIndex = potentialIndex; } } else if (dir === 'page_down') { var _potentialIndex = focusedIndex + this.props.pageSize; if (_potentialIndex > options.length - 1) { focusedIndex = options.length - 1; } else { focusedIndex = _potentialIndex; } } if (focusedIndex === -1) { focusedIndex = 0; } this.setState({ focusedIndex: options[focusedIndex].index, focusedOption: options[focusedIndex].option }); } }, { key: 'getFocusedOption', value: function getFocusedOption() { return this._focusedOption; } }, { key: 'selectFocusedOption', value: function selectFocusedOption() { if (this._focusedOption) { return this.selectValue(this._focusedOption); } } }, { key: 'renderLoading', value: function renderLoading() { if (!this.props.isLoading) return; return React__default.createElement( 'span', { className: 'Select-loading-zone', 'aria-hidden': 'true' }, React__default.createElement('span', { className: 'Select-loading' }) ); } }, { key: 'renderValue', value: function renderValue(valueArray, isOpen) { var _this5 = this; var renderLabel = this.props.valueRenderer || this.getOptionLabel; var ValueComponent = this.props.valueComponent; if (!valueArray.length) { var showPlaceholder = shouldShowPlaceholder(this.state, this.props, isOpen); return showPlaceholder ? React__default.createElement( 'div', { className: 'Select-placeholder' }, this.props.placeholder ) : null; } var onClick = this.props.onValueClick ? this.handleValueClick : null; if (this.props.multi) { return valueArray.map(function (value, i) { return React__default.createElement( ValueComponent, { disabled: _this5.props.disabled || value.clearableValue === false, id: _this5._instancePrefix + '-value-' + i, instancePrefix: _this5._instancePrefix, key: 'value-' + i + '-' + value[_this5.props.valueKey], onClick: onClick, onRemove: _this5.removeValue, placeholder: _this5.props.placeholder, value: value }, renderLabel(value, i), React__default.createElement( 'span', { className: 'Select-aria-only' }, '\xA0' ) ); }); } else if (shouldShowValue(this.state, this.props)) { if (isOpen) onClick = null; return React__default.createElement( ValueComponent, { disabled: this.props.disabled, id: this._instancePrefix + '-value-item', instancePrefix: this._instancePrefix, onClick: onClick, placeholder: this.props.placeholder, value: valueArray[0] }, renderLabel(valueArray[0]) ); } } }, { key: 'renderInput', value: function renderInput(valueArray, focusedOptionIndex) { var _classNames, _this6 = this; var className = classNames('Select-input', this.props.inputProps.className); var isOpen = this.state.isOpen; var ariaOwns = classNames((_classNames = {}, defineProperty(_classNames, this._instancePrefix + '-list', isOpen), defineProperty(_classNames, this._instancePrefix + '-backspace-remove-message', this.props.multi && !this.props.disabled && this.state.isFocused && !this.state.inputValue), _classNames)); var value = this.state.inputValue; if (value && !this.props.onSelectResetsInput && !this.state.isFocused) { // it hides input value when it is not focused and was not reset on select value = ''; } var inputProps = _extends({}, this.props.inputProps, { 'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value', 'aria-describedby': this.props['aria-describedby'], 'aria-expanded': '' + isOpen, 'aria-haspopup': '' + isOpen, 'aria-label': this.props['aria-label'], 'aria-labelledby': this.props['aria-labelledby'], 'aria-owns': ariaOwns, className: className, onBlur: this.handleInputBlur, onChange: this.handleInputChange, onFocus: this.handleInputFocus, ref: function ref(_ref) { return _this6.input = _ref; }, role: 'combobox', required: this.state.required, tabIndex: this.props.tabIndex, value: value }); if (this.props.inputRenderer) { return this.props.inputRenderer(inputProps); } if (this.props.disabled || !this.props.searchable) { var divProps = objectWithoutProperties(this.props.inputProps, []); var _ariaOwns = classNames(defineProperty({}, this._instancePrefix + '-list', isOpen)); return React__default.createElement('div', _extends({}, divProps, { 'aria-expanded': isOpen, 'aria-owns': _ariaOwns, 'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value', 'aria-disabled': '' + this.props.disabled, 'aria-label': this.props['aria-label'], 'aria-labelledby': this.props['aria-labelledby'], className: className, onBlur: this.handleInputBlur, onFocus: this.handleInputFocus, ref: function ref(_ref2) { return _this6.input = _ref2; }, role: 'combobox', style: { border: 0, width: 1, display: 'inline-block' }, tabIndex: this.props.tabIndex || 0 })); } if (this.props.autosize) { return React__default.createElement(AutosizeInput, _extends({ id: this.props.id }, inputProps, { minWidth: '5' })); } return React__default.createElement( 'div', { className: className, key: 'input-wrap' }, React__default.createElement('input', _extends({ id: this.props.id }, inputProps)) ); } }, { key: 'renderClear', value: function renderClear() { var valueArray = this.getValueArray(this.props.value); if (!this.props.clearable || !valueArray.length || this.props.disabled || this.props.isLoading) return; var ariaLabel = this.props.multi ? this.props.clearAllText : this.props.clearValueText; var clear = this.props.clearRenderer(); return React__default.createElement( 'span', { 'aria-label': ariaLabel, className: 'Select-clear-zone', onMouseDown: this.clearValue, onTouchEnd: this.handleTouchEndClearValue, onTouchMove: this.handleTouchMove, onTouchStart: this.handleTouchStart, title: ariaLabel }, clear ); } }, { key: 'renderArrow', value: function renderArrow() { if (!this.props.arrowRenderer) return; var onMouseDown = this.handleMouseDownOnArrow; var isOpen = this.state.isOpen; var arrow = this.props.arrowRenderer({ onMouseDown: onMouseDown, isOpen: isOpen }); if (!arrow) { return null; } return React__default.createElement( 'span', { className: 'Select-arrow-zone', onMouseDown: onMouseDown }, arrow ); } }, { key: 'filterOptions', value: function filterOptions$$1(excludeOptions) { var filterValue = this.state.inputValue; var options = this.props.options || []; if (this.props.filterOptions) { // Maintain backwards compatibility with boolean attribute var filterOptions$$1 = typeof this.props.filterOptions === 'function' ? this.props.filterOptions : filterOptions; return filterOptions$$1(options, filterValue, excludeOptions, { filterOption: this.props.filterOption, ignoreAccents: this.props.ignoreAccents, ignoreCase: this.props.ignoreCase, labelKey: this.props.labelKey, matchPos: this.props.matchPos, matchProp: this.props.matchProp, trimFilter: this.props.trimFilter, valueKey: this.props.valueKey }); } else { return options; } } }, { key: 'onOptionRef', value: function onOptionRef(ref, isFocused) { if (isFocused) { this.focused = ref; } } }, { key: 'renderMenu', value: function renderMenu(options, valueArray, focusedOption) { if (options && options.length) { return this.props.menuRenderer({ focusedOption: focusedOption, focusOption: this.focusOption, inputValue: this.state.inputValue, instancePrefix: this._instancePrefix, labelKey: this.props.labelKey, onFocus: this.focusOption, onOptionRef: this.onOptionRef, onSelect: this.selectValue, optionClassName: this.props.optionClassName, optionComponent: this.props.optionComponent, optionRenderer: this.props.optionRenderer || this.getOptionLabel, options: options, removeValue: this.removeValue, selectValue: this.selectValue, valueArray: valueArray, valueKey: this.props.valueKey }); } else if (this.props.noResultsText) { return React__default.createElement( 'div', { className: 'Select-noresults' }, this.props.noResultsText ); } else { return null; } } }, { key: 'renderHiddenField', value: function renderHiddenField(valueArray) { var _this7 = this; if (!this.props.name) return; if (this.props.joinValues) { var value = valueArray.map(function (i) { return stringifyValue(i[_this7.props.valueKey]); }).join(this.props.delimiter); return React__default.createElement('input', { disabled: this.props.disabled, name: this.props.name, ref: function ref(_ref3) { return _this7.value = _ref3; }, type: 'hidden', value: value }); } return valueArray.map(function (item, index) { return React__default.createElement('input', { disabled: _this7.props.disabled, key: 'hidden.' + index, name: _this7.props.name, ref: 'value' + index, type: 'hidden', value: stringifyValue(item[_this7.props.valueKey]) }); }); } }, { key: 'getFocusableOptionIndex', value: function getFocusableOptionIndex(selectedOption) { var options = this._visibleOptions; if (!options.length) return null; var valueKey = this.props.valueKey; var focusedOption = this.state.focusedOption || selectedOption; if (focusedOption && !focusedOption.disabled) { var focusedOptionIndex = -1; options.some(function (option, index) { var isOptionEqual = option[valueKey] === focusedOption[valueKey]; if (isOptionEqual) { focusedOptionIndex = index; } return isOptionEqual; }); if (focusedOptionIndex !== -1) { return focusedOptionIndex; } } for (var i = 0; i < options.length; i++) { if (!options[i].disabled) return i; } return null; } }, { key: 'renderOuter', value: function renderOuter(options, valueArray, focusedOption) { var _this8 = this; var menu = this.renderMenu(options, valueArray, focusedOption); if (!menu) { return null; } return React__default.createElement( 'div', { ref: function ref(_ref5) { return _this8.menuContainer = _ref5; }, className: 'Select-menu-outer', style: this.props.menuContainerStyle }, React__default.createElement( 'div', { className: 'Select-menu', id: this._instancePrefix + '-list', onMouseDown: this.handleMouseDownOnMenu, onScroll: this.handleMenuScroll, ref: function ref(_ref4) { return _this8.menu = _ref4; }, role: 'listbox', style: this.props.menuStyle, tabIndex: -1 }, menu ) ); } }, { key: 'render', value: function render() { var _this9 = this; var valueArray = this.getValueArray(this.props.value); var options = this._visibleOptions = this.filterOptions(this.props.multi && this.props.removeSelected ? valueArray : null); var isOpen = this.state.isOpen; if (this.props.multi && !options.length && valueArray.length && !this.state.inputValue) isOpen = false; var focusedOptionIndex = this.getFocusableOptionIndex(valueArray[0]); var focusedOption = null; if (focusedOptionIndex !== null) { focusedOption = this._focusedOption = options[focusedOptionIndex]; } else { focusedOption = this._focusedOption = null; } var className = classNames('Select', this.props.className, { 'has-value': valueArray.length, 'is-clearable': this.props.clearable, 'is-disabled': this.props.disabled, 'is-focused': this.state.isFocused, 'is-loading': this.props.isLoading, 'is-open': isOpen, 'is-pseudo-focused': this.state.isPseudoFocused, 'is-searchable': this.props.searchable, 'Select--multi': this.props.multi, 'Select--rtl': this.props.rtl, 'Select--single': !this.props.multi }); var removeMessage = null; if (this.props.multi && !this.props.disabled && valueArray.length && !this.state.inputValue && this.state.isFocused && this.props.backspaceRemoves) { removeMessage = React__default.createElement( 'span', { id: this._instancePrefix + '-backspace-remove-message', className: 'Select-aria-only', 'aria-live': 'assertive' }, this.props.backspaceToRemoveMessage.replace('{label}', valueArray[valueArray.length - 1][this.props.labelKey]) ); } return React__default.createElement( 'div', { ref: function ref(_ref7) { return _this9.wrapper = _ref7; }, className: className, style: this.props.wrapperStyle }, this.renderHiddenField(valueArray), React__default.createElement( 'div', { ref: function ref(_ref6) { return _this9.control = _ref6; }, className: 'Select-control', onKeyDown: this.handleKeyDown, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleTouchEnd, onTouchMove: this.handleTouchMove, onTouchStart: this.handleTouchStart, style: this.props.style }, React__default.createElement( 'span', { className: 'Select-multi-value-wrapper', id: this._instancePrefix + '-value' }, this.renderValue(valueArray, isOpen), this.renderInput(valueArray, focusedOptionIndex) ), removeMessage, this.renderLoading(), this.renderClear(), this.renderArrow() ), isOpen ? this.renderOuter(options, valueArray, focusedOption) : null ); } }]); return Select; }(React__default.Component); Select$1.propTypes = { 'aria-describedby': PropTypes.string, // html id(s) of element(s) that should be used to describe this input (for assistive tech) 'aria-label': PropTypes.string, // aria label (for assistive tech) 'aria-labelledby': PropTypes.string, // html id of an element that should be used as the label (for assistive tech) arrowRenderer: PropTypes.func, // create the drop-down caret element autoBlur: PropTypes.bool, // automatically blur the component when an option is selected autoFocus: PropTypes.bool, // autofocus the component on mount autofocus: PropTypes.bool, // deprecated; use autoFocus instead autosize: PropTypes.bool, // whether to enable autosizing or not backspaceRemoves: PropTypes.bool, // whether backspace removes an item if there is no text input backspaceToRemoveMessage: PropTypes.string, // message to use for screenreaders to press backspace to remove the current item - {label} is replaced with the item label className: PropTypes.string, // className for the outer element clearAllText: stringOrNode, // title for the "clear" control when multi: true clearRenderer: PropTypes.func, // create clearable x element clearValueText: stringOrNode, // title for the "clear" control clearable: PropTypes.bool, // should it be possible to reset value closeOnSelect: PropTypes.bool, // whether to close the menu when a value is selected deleteRemoves: PropTypes.bool, // whether delete removes an item if there is no text input delimiter: PropTypes.string, // delimiter to use to join multiple values for the hidden field value disabled: PropTypes.bool, // whether the Select is disabled or not escapeClearsValue: PropTypes.bool, // whether escape clears the value when the menu is closed filterOption: PropTypes.func, // method to filter a single option (option, filterString) filterOptions: PropTypes.any, // boolean to enable default filtering or function to filter the options array ([options], filterString, [values]) id: PropTypes.string, // html id to set on the input element for accessibility or tests ignoreAccents: PropTypes.bool, // whether to strip diacritics when filtering ignoreCase: PropTypes.bool, // whether to perform case-insensitive filtering inputProps: PropTypes.object, // custom attributes for the Input inputRenderer: PropTypes.func, // returns a custom input component instanceId: PropTypes.string, // set the components instanceId isLoading: PropTypes.bool, // whether the Select is loading externally or not (such as options being loaded) joinValues: PropTypes.bool, // joins multiple values into a single form field with the delimiter (legacy mode) labelKey: PropTypes.string, // path of the label value in option objects matchPos: PropTypes.string, // (any|start) match the start or entire string when filtering matchProp: PropTypes.string, // (any|label|value) which option property to filter on menuBuffer: PropTypes.number, // optional buffer (in px) between the bottom of the viewport and the bottom of the menu menuContainerStyle: PropTypes.object, // optional style to apply to the menu container menuRenderer: PropTypes.func, // renders a custom menu with options menuStyle: PropTypes.object, // optional style to apply to the menu multi: PropTypes.bool, // multi-value input name: PropTypes.string, // generates a hidden <input /> tag with this field name for html forms noResultsText: stringOrNode, // placeholder displayed when there are no matching search results onBlur: PropTypes.func, // onBlur handler: function (event) {} onBlurResetsInput: PropTypes.bool, // whether input is cleared on blur onChange: PropTypes.func, // onChange handler: function (newValue) {} onClose: PropTypes.func, // fires when the menu is closed onCloseResetsInput: PropTypes.bool, // whether input is cleared when menu is closed through the arrow onFocus: PropTypes.func, // onFocus handler: function (event) {} onInputChange: PropTypes.func, // onInputChange handler: function (inputValue) {} onInputKeyDown: PropTypes.func, // input keyDown handler: function (event) {} onMenuScrollToBottom: PropTypes.func, // fires when the menu is scrolled to the bottom; can be used to paginate options onOpen: PropTypes.func, // fires when the menu is opened onSelectResetsInput: PropTypes.bool, // whether input is cleared on select (works only for multiselect) onValueClick: PropTypes.func, // onClick handler for value labels: function (value, event) {} openOnClick: PropTypes.bool, // boolean to control opening the menu when the control is clicked openOnFocus: PropTypes.bool, // always open options menu on focus optionClassName: PropTypes.string, // additional class(es) to apply to the <Option /> elements optionComponent: PropTypes.func, // option component to render in dropdown optionRenderer: PropTypes.func, // optionRenderer: function (option) {} options: PropTypes.array, // array of options pageSize: PropTypes.number, // number of entries to page when using page up/down keys placeholder: stringOrNode, // field placeholder, displayed when there's no value removeSelected: PropTypes.bool, // whether the selected option is removed from the dropdown on multi selects required: PropTypes.bool, // applies HTML5 required attribute when needed resetValue: PropTypes.any, // value to use when you clear the control rtl: PropTypes.bool, // set to true in order to use react-select in right-to-left direction scrollMenuIntoView: PropTypes.bool, // boolean to enable the viewport to shift so that the full menu fully visible when engaged searchable: PropTypes.bool, // whether to enable searching feature or not simpleValue: PropTypes.bool, // pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false style: PropTypes.object, // optional style to apply to the control tabIndex: stringOrNumber, // optional tab index of the control tabSelectsValue: PropTypes.bool, // whether to treat tabbing out while focused to be value selection trimFilter: PropTypes.bool, // whether to trim whitespace around filter value value: PropTypes.any, // initial field value valueComponent: PropTypes.func, // value component to render valueKey: PropTypes.string, // path of the label value in option objects valueRenderer: PropTypes.func, // valueRenderer: function (option) {} wrapperStyle: PropTypes.object // optional style to apply to the component wrapper }; Select$1.defaultProps = { arrowRenderer: arrowRenderer, autosize: true, backspaceRemoves: true, backspaceToRemoveMessage: 'Press backspace to remove {label}', clearable: true, clearAllText: 'Clear all', clearRenderer: clearRenderer, clearValueText: 'Clear value', closeOnSelect: true, deleteRemoves: true, delimiter: ',', disabled: false, escapeClearsValue: true, filterOptions: filterOptions, ignoreAccents: true, ignoreCase: true, inputProps: {}, isLoading: false, joinValues: false, labelKey: 'label', matchPos: 'any', matchProp: 'any', menuBuffer: 0, menuRenderer: menuRenderer, multi: false, noResultsText: 'No results found', onBlurResetsInput: true, onCloseResetsInput: true, onSelectResetsInput: true, openOnClick: true, optionComponent: Option, pageSize: 5, placeholder: 'Select...', removeSelected: true, required: false, rtl: false, scrollMenuIntoView: true, searchable: true, simpleValue: false, tabSelectsValue: true, trimFilter: true, valueComponent: Value, valueKey: 'value' }; var propTypes = { autoload: PropTypes.bool.isRequired, // automatically call the `loadOptions` prop on-mount; defaults to true cache: PropTypes.any, // object to use to cache results; set to null/false to disable caching children: PropTypes.func.isRequired, // Child function responsible for creating the inner Select component; (props: Object): PropTypes.element ignoreAccents: PropTypes.bool, // strip diacritics when filtering; defaults to true ignoreCase: PropTypes.bool, // perform case-insensitive filtering; defaults to true loadOptions: PropTypes.func.isRequired, // callback to load options asynchronously; (inputValue: string, callback: Function): ?Promise loadingPlaceholder: PropTypes.oneOfType([// replaces the placeholder while options are loading PropTypes.string, PropTypes.node]), multi: PropTypes.bool, // multi-value input noResultsText: PropTypes.oneOfType([// field noResultsText, displayed when no options come back from the server PropTypes.string, PropTypes.node]), onChange: PropTypes.func, // onChange handler: function (newValue) {} onInputChange: PropTypes.func, // optional for keeping track of what is being typed options: PropTypes.array.isRequired, // array of options placeholder: PropTypes.oneOfType([// field placeholder, displayed when there's no value (shared with Select) PropTypes.string, PropTypes.node]), searchPromptText: PropTypes.oneOfType([// label to prompt for search input PropTypes.string, PropTypes.node]), value: PropTypes.any // initial field value }; var defaultCache = {}; var defaultChildren = function defaultChildren(props) { return React__default.createElement(Select$1, props); }; var defaultProps = { autoload: true, cache: defaultCache, children: defaultChildren, ignoreAccents: true, ignoreCase: true, loadingPlaceholder: 'Loading...', options: [], searchPromptText: 'Type to search' }; var Async = function (_Component) { inherits(Async, _Component); function Async(props, context) { classCallCheck(this, Async); var _this = possibleConstructorReturn(this, (Async.__proto__ || Object.getPrototypeOf(Async)).call(this, props, context)); _this._cache = props.cache === defaultCache ? {} : props.cache; _this.state = { inputValue: '', isLoading: false, options: props.options }; _this.onInputChange = _this.onInputChange.bind(_this); return _this; } createClass(Async, [{ key: 'componentDidMount', value: function componentDidMount() { var autoload = this.props.autoload; if (autoload) { this.loadOptions(''); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (nextProps.options !== this.props.options) { this.setState({ options: nextProps.options }); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this._callback = null; } }, { key: 'loadOptions', value: function loadOptions(inputValue) { var _this2 = this; var loadOptions = this.props.loadOptions; var cache = this._cache; if (cache && Object.prototype.hasOwnProperty.call(cache, inputValue)) { this._callback = null; this.setState({ isLoading: false, options: cache[inputValue] }); return; } var callback = function callback(error, data) { var options = data && data.options || []; if (cache) { cache[inputValue] = options; } if (callback === _this2._callback) { _this2._callback = null; _this2.setState({ isLoading: false, options: options }); } }; // Ignore all but the most recent request this._callback = callback; var promise = loadOptions(inputValue, callback); if (promise) { promise.then(function (data) { return callback(null, data); }, function (error) { return callback(error); }); } if (this._callback && !this.state.isLoading) { this.setState({ isLoading: true }); } } }, { key: 'onInputChange', value: function onInputChange(inputValue) { var _props = this.props, ignoreAccents = _props.ignoreAccents, ignoreCase = _props.ignoreCase, onInputChange = _props.onInputChange; var newInputValue = inputValue; if (onInputChange) { var value = onInputChange(newInputValue); // Note: != used deliberately here to catch undefined and null if (value != null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object') { newInputValue = '' + value; } } var transformedInputValue = newInputValue; if (ignoreAccents) { transformedInputValue = stripDiacritics(transformedInputValue); } if (ignoreCase) { transformedInputValue = transformedInputValue.toLowerCase(); } this.setState({ inputValue: newInputValue }); this.loadOptions(transformedInputValue); // Return new input value, but without applying toLowerCase() to avoid modifying the user's view case of the input while typing. return newInputValue; } }, { key: 'noResultsText', value: function noResultsText() { var _props2 = this.props, loadingPlaceholder = _props2.loadingPlaceholder, noResultsText = _props2.noResultsText, searchPromptText = _props2.searchPromptText; var _state = this.state, inputValue = _state.inputValue, isLoading = _state.isLoading; if (isLoading) { return loadingPlaceholder; } if (inputValue && noResultsText) { return noResultsText; } return searchPromptText; } }, { key: 'focus', value: function focus() { this.select.focus(); } }, { key: 'render', value: function render() { var _this3 = this; var _props3 = this.props, children = _props3.children, loadingPlaceholder = _props3.loadingPlaceholder, placeholder = _props3.placeholder; var _state2 = this.state, isLoading = _state2.isLoading, options = _state2.options; var props = { noResultsText: this.noResultsText(), placeholder: isLoading ? loadingPlaceholder : placeholder, options: isLoading && loadingPlaceholder ? [] : options, ref: function ref(_ref) { return _this3.select = _ref; } }; return children(_extends({}, this.props, props, { isLoading: isLoading, onInputChange: this.onInputChange })); } }]); return Async; }(React.Component); Async.propTypes = propTypes; Async.defaultProps = defaultProps; var CreatableSelect = function (_React$Component) { inherits(CreatableSelect, _React$Component); function CreatableSelect(props, context) { classCallCheck(this, CreatableSelect); var _this = possibleConstructorReturn(this, (CreatableSelect.__proto__ || Object.getPrototypeOf(CreatableSelect)).call(this, props, context)); _this.filterOptions = _this.filterOptions.bind(_this); _this.menuRenderer = _this.menuRenderer.bind(_this); _this.onInputKeyDown = _this.onInputKeyDown.bind(_this); _this.onInputChange = _this.onInputChange.bind(_this); _this.onOptionSelect = _this.onOptionSelect.bind(_this); return _this; } createClass(CreatableSelect, [{ key: 'createNewOption', value: function createNewOption() { var _props = this.props, isValidNewOption = _props.isValidNewOption, newOptionCreator = _props.newOptionCreator, onNewOptionClick = _props.onNewOptionClick, _props$options = _props.options, options = _props$options === undefined ? [] : _props$options; if (isValidNewOption({ label: this.inputValue })) { var option = newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey }); var _isOptionUnique = this.isOptionUnique({ option: option, options: options }); // Don't add the same option twice. if (_isOptionUnique) { if (onNewOptionClick) { onNewOptionClick(option); } else { options.unshift(option); this.select.selectValue(option); } } } } }, { key: 'filterOptions', value: function filterOptions$$1() { var _props2 = this.props, filterOptions$$1 = _props2.filterOptions, isValidNewOption = _props2.isValidNewOption, promptTextCreator = _props2.promptTextCreator; // TRICKY Check currently selected options as well. // Don't display a create-prompt for a value that's selected. // This covers async edge-cases where a newly-created Option isn't yet in the async-loaded array. var excludeOptions = (arguments.length <= 2 ? undefined : arguments[2]) || []; var filteredOptions = filterOptions$$1.apply(undefined, arguments) || []; if (isValidNewOption({ label: this.inputValue })) { var _newOptionCreator = this.props.newOptionCreator; var option = _newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey }); // TRICKY Compare to all options (not just filtered options) in case option has already been selected). // For multi-selects, this would remove it from the filtered list. var _isOptionUnique2 = this.isOptionUnique({ option: option, options: excludeOptions.concat(filteredOptions) }); if (_isOptionUnique2) { var prompt = promptTextCreator(this.inputValue); this._createPlaceholderOption = _newOptionCreator({ label: prompt, labelKey: this.labelKey, valueKey: this.valueKey }); filteredOptions.unshift(this._createPlaceholderOption); } } return filteredOptions; } }, { key: 'isOptionUnique', value: function isOptionUnique(_ref) { var option = _ref.option, options = _ref.options; var isOptionUnique = this.props.isOptionUnique; options = options || this.props.options; return isOptionUnique({ labelKey: this.labelKey, option: option, options: options, valueKey: this.valueKey }); } }, { key: 'menuRenderer', value: function menuRenderer$$1(params) { var menuRenderer$$1 = this.props.menuRenderer; return menuRenderer$$1(_extends({}, params, { onSelect: this.onOptionSelect, selectValue: this.onOptionSelect })); } }, { key: 'onInputChange', value: function onInputChange(input) { var onInputChange = this.props.onInputChange; // This value may be needed in between Select mounts (when this.select is null) this.inputValue = input; if (onInputChange) { this.inputValue = onInputChange(input); } return this.inputValue; } }, { key: 'onInputKeyDown', value: function onInputKeyDown(event) { var _props3 = this.props, shouldKeyDownEventCreateNewOption = _props3.shouldKeyDownEventCreateNewOption, onInputKeyDown = _props3.onInputKeyDown; var focusedOption = this.select.getFocusedOption(); if (focusedOption && focusedOption === this._createPlaceholderOption && shouldKeyDownEventCreateNewOption({ keyCode: event.keyCode })) { this.createNewOption(); // Prevent decorated Select from doing anything additional with this keyDown event event.preventDefault(); } else if (onInputKeyDown) { onInputKeyDown(event); } } }, { key: 'onOptionSelect', value: function onOptionSelect(option) { if (option === this._createPlaceholderOption) { this.createNewOption(); } else { this.select.selectValue(option); } } }, { key: 'focus', value: function focus() { this.select.focus(); } }, { key: 'render', value: function render() { var _this2 = this; var _props4 = this.props, refProp = _props4.ref, restProps = objectWithoutProperties(_props4, ['ref']); var children = this.props.children; // We can't use destructuring default values to set the children, // because it won't apply work if `children` is null. A falsy check is // more reliable in real world use-cases. if (!children) { children = defaultChildren$2; } var props = _extends({}, restProps, { allowCreate: true, filterOptions: this.filterOptions, menuRenderer: this.menuRenderer, onInputChange: this.onInputChange, onInputKeyDown: this.onInputKeyDown, ref: function ref(_ref2) { _this2.select = _ref2; // These values may be needed in between Select mounts (when this.select is null) if (_ref2) { _this2.labelKey = _ref2.props.labelKey; _this2.valueKey = _ref2.props.valueKey; } if (refProp) { refProp(_ref2); } } }); return children(props); } }]); return CreatableSelect; }(React__default.Component); var defaultChildren$2 = function defaultChildren(props) { return React__default.createElement(Select$1, props); }; var isOptionUnique = function isOptionUnique(_ref3) { var option = _ref3.option, options = _ref3.options, labelKey = _ref3.labelKey, valueKey = _ref3.valueKey; if (!options || !options.length) { return true; } return options.filter(function (existingOption) { return existingOption[labelKey] === option[labelKey] || existingOption[valueKey] === option[valueKey]; }).length === 0; }; var isValidNewOption = function isValidNewOption(_ref4) { var label = _ref4.label; return !!label; }; var newOptionCreator = function newOptionCreator(_ref5) { var label = _ref5.label, labelKey = _ref5.labelKey, valueKey = _ref5.valueKey; var option = {}; option[valueKey] = label; option[labelKey] = label; option.className = 'Select-create-option-placeholder'; return option; }; var promptTextCreator = function promptTextCreator(label) { return 'Create option "' + label + '"'; }; var shouldKeyDownEventCreateNewOption = function shouldKeyDownEventCreateNewOption(_ref6) { var keyCode = _ref6.keyCode; switch (keyCode) { case 9: // TAB case 13: // ENTER case 188: // COMMA return true; default: return false; } }; // Default prop methods CreatableSelect.isOptionUnique = isOptionUnique; CreatableSelect.isValidNewOption = isValidNewOption; CreatableSelect.newOptionCreator = newOptionCreator; CreatableSelect.promptTextCreator = promptTextCreator; CreatableSelect.shouldKeyDownEventCreateNewOption = shouldKeyDownEventCreateNewOption; CreatableSelect.defaultProps = { filterOptions: filterOptions, isOptionUnique: isOptionUnique, isValidNewOption: isValidNewOption, menuRenderer: menuRenderer, newOptionCreator: newOptionCreator, promptTextCreator: promptTextCreator, shouldKeyDownEventCreateNewOption: shouldKeyDownEventCreateNewOption }; CreatableSelect.propTypes = { // Child function responsible for creating the inner Select component // This component can be used to compose HOCs (eg Creatable and Async) // (props: Object): PropTypes.element children: PropTypes.func, // See Select.propTypes.filterOptions filterOptions: PropTypes.any, // Searches for any matching option within the set of options. // This function prevents duplicate options from being created. // ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean isOptionUnique: PropTypes.func, // Determines if the current input text represents a valid option. // ({ label: string }): boolean isValidNewOption: PropTypes.func, // See Select.propTypes.menuRenderer menuRenderer: PropTypes.any, // Factory to create new option. // ({ label: string, labelKey: string, valueKey: string }): Object newOptionCreator: PropTypes.func, // input change handler: function (inputValue) {} onInputChange: PropTypes.func, // input keyDown handler: function (event) {} onInputKeyDown: PropTypes.func, // new option click handler: function (option) {} onNewOptionClick: PropTypes.func, // See Select.propTypes.options options: PropTypes.array, // Creates prompt/placeholder option text. // (filterText: string): string promptTextCreator: PropTypes.func, ref: PropTypes.func, // Decides if a keyDown event (eg its `keyCode`) should result in the creation of a new option. shouldKeyDownEventCreateNewOption: PropTypes.func }; var AsyncCreatableSelect = function (_React$Component) { inherits(AsyncCreatableSelect, _React$Component); function AsyncCreatableSelect() { classCallCheck(this, AsyncCreatableSelect); return possibleConstructorReturn(this, (AsyncCreatableSelect.__proto__ || Object.getPrototypeOf(AsyncCreatableSelect)).apply(this, arguments)); } createClass(AsyncCreatableSelect, [{ key: 'focus', value: function focus() { this.select.focus(); } }, { key: 'render', value: function render() { var _this2 = this; return React__default.createElement( Async, this.props, function (_ref) { var ref = _ref.ref, asyncProps = objectWithoutProperties(_ref, ['ref']); var asyncRef = ref; return React__default.createElement( CreatableSelect, asyncProps, function (_ref2) { var ref = _ref2.ref, creatableProps = objectWithoutProperties(_ref2, ['ref']); var creatableRef = ref; return _this2.props.children(_extends({}, creatableProps, { ref: function ref(select) { creatableRef(select); asyncRef(select); _this2.select = select; } })); } ); } ); } }]); return AsyncCreatableSelect; }(React__default.Component); var defaultChildren$1 = function defaultChildren(props) { return React__default.createElement(Select$1, props); }; AsyncCreatableSelect.propTypes = { children: PropTypes.func.isRequired // Child function responsible for creating the inner Select component; (props: Object): PropTypes.element }; AsyncCreatableSelect.defaultProps = { children: defaultChildren$1 }; // This file exists as an entry point for bundling our umd builds. // Both in rollup and in webpack, umd builds built from es6 modules are not // compatible with mixed imports (which exist in index.js) // This file does away with named imports in favor of a single export default. Select$1.Async = Async; Select$1.AsyncCreatable = AsyncCreatableSelect; Select$1.Creatable = CreatableSelect; Select$1.Value = Value; Select$1.Option = Option; return Select$1; })));
reflux-app/components/Management.js
Orientsoft/conalog-front
import React from 'react' import _ from 'lodash' import AppActions from '../actions/AppActions' import AppStore from '../stores/AppStore' import { FormattedMessage } from 'react-intl'; class Login extends React.Component { constructor(props) { super(props) this.state = { managementErr: {} } } componentDidMount() { this.unsubscribe = AppStore.listen(function(state) { this.setState(state) }.bind(this)) } componentWillUnmount() { if (_.isFunction(this.unsubscribe)) this.unsubscribe() } changeManagementPassword(e) { // prevent default submit e.preventDefault() // get value from controls, with refs let oldPass = this.refs.old.value.trim() let newPass = this.refs.new.value.trim() let repeatedNewPass = this.refs.repeat.value.trim() // submit AppActions.changeManagementPassword({oldPass: oldPass, newPass: newPass, repeatedNewPass: repeatedNewPass}) } render() { let a = <FormattedMessage id = 'home'/> let oldPass = a._owner._context.intl.messages.oldPass let newPass = a._owner._context.intl.messages.newPass let repeatNewPass = a._owner._context.intl.messages.repeatNewPassword return ( <div> <div className="account-pages"></div> <div className="clearfix"></div> <div className="wrapper-page"> <div className=" card-box"> <div className="panel-heading"> <h3 className="text-center"> <FormattedMessage id="manage"/> <strong className="text-custom">Conalog</strong> </h3> </div> <div className="panel-body"> <div className=""></div> <form className="form-horizontal m-t-20" action="#"> <div className="form-group "> <div className="ant-col-xs-24"> <input className="form-control" type="password" required="" placeholder={oldPass} ref="old" /> </div> </div> <div className="form-group"> <div className="ant-col-xs-24"> <input className="form-control" type="password" required="" placeholder={newPass} ref="new" /> </div> </div> <div className="form-group "> <div className="ant-col-xs-24"> <input className="form-control" type="password" required="" placeholder={repeatNewPass} ref="repeat"/> </div> </div> <div className="form-group text-center m-t-40"> <div className="ant-col-xs-24"> <button className="btn btn-pink btn-block text-uppercase waves-effect waves-light" type="submit" onClick={this.changeManagementPassword.bind(this)}> <FormattedMessage id="changePass"/></button> </div> </div> </form> </div> </div> </div> </div> ) } } Login.propTypes = { } Login.defaultProps = { } export default Login
ajax/libs/onsen/2.0.0-alpha.3/js/ons-core.min.js
dc-js/cdnjs
/*! ons-core.js for Onsen UI v2.0.0-alpha - 2015-10-22 */ function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}!function(){function getAttributes(element){return Node_get_attributes.call(element)}function setAttribute(element,attribute,value){try{Element_setAttribute.call(element,attribute,value)}catch(e){}}function removeAttribute(element,attribute){Element_removeAttribute.call(element,attribute)}function childNodes(element){return Node_get_childNodes.call(element)}function empty(element){for(;element.childNodes.length;)element.removeChild(element.lastChild)}function insertAdjacentHTML(element,position,html){HTMLElement_insertAdjacentHTMLPropertyDescriptor.value.call(element,position,html)}function inUnsafeMode(){var isUnsafe=!0;try{detectionDiv.innerHTML="<test/>"}catch(ex){isUnsafe=!1}return isUnsafe}function cleanse(html,targetElement){function cleanseAttributes(element){var attributes=getAttributes(element);if(attributes&&attributes.length){for(var events,i=0,len=attributes.length;len>i;i++){var attribute=attributes[i],name=attribute.name;"o"!==name[0]&&"O"!==name[0]||"n"!==name[1]&&"N"!==name[1]||(events=events||[],events.push({name:attribute.name,value:attribute.value}))}if(events)for(var i=0,len=events.length;len>i;i++){var attribute=events[i];removeAttribute(element,attribute.name),setAttribute(element,"x-"+attribute.name,attribute.value)}}for(var children=childNodes(element),i=0,len=children.length;len>i;i++)cleanseAttributes(children[i])}var cleaner=document.implementation.createHTMLDocument("cleaner");empty(cleaner.documentElement),MSApp.execUnsafeLocalFunction(function(){insertAdjacentHTML(cleaner.documentElement,"afterbegin",html)});var scripts=cleaner.documentElement.querySelectorAll("script");Array.prototype.forEach.call(scripts,function(script){switch(script.type.toLowerCase()){case"":script.type="text/inert";break;case"text/javascript":case"text/ecmascript":case"text/x-javascript":case"text/jscript":case"text/livescript":case"text/javascript1.1":case"text/javascript1.2":case"text/javascript1.3":script.type="text/inert-"+script.type.slice("text/".length);break;case"application/javascript":case"application/ecmascript":case"application/x-javascript":script.type="application/inert-"+script.type.slice("application/".length)}}),cleanseAttributes(cleaner.documentElement);var cleanedNodes=[];return"HTML"===targetElement.tagName?cleanedNodes=Array.prototype.slice.call(document.adoptNode(cleaner.documentElement).childNodes):(cleaner.head&&(cleanedNodes=cleanedNodes.concat(Array.prototype.slice.call(document.adoptNode(cleaner.head).childNodes))),cleaner.body&&(cleanedNodes=cleanedNodes.concat(Array.prototype.slice.call(document.adoptNode(cleaner.body).childNodes)))),cleanedNodes}function cleansePropertySetter(property,setter){var propertyDescriptor=Object.getOwnPropertyDescriptor(HTMLElement.prototype,property),originalSetter=propertyDescriptor.set;Object.defineProperty(HTMLElement.prototype,property,{get:propertyDescriptor.get,set:function(value){if(window.WinJS&&window.WinJS._execUnsafe&&inUnsafeMode())originalSetter.call(this,value);else{var that=this,nodes=cleanse(value,that);MSApp.execUnsafeLocalFunction(function(){setter(propertyDescriptor,that,nodes)})}},enumerable:propertyDescriptor.enumerable,configurable:propertyDescriptor.configurable})}if(window.MSApp&&MSApp.execUnsafeLocalFunction){var Element_setAttribute=Object.getOwnPropertyDescriptor(Element.prototype,"setAttribute").value,Element_removeAttribute=Object.getOwnPropertyDescriptor(Element.prototype,"removeAttribute").value,HTMLElement_insertAdjacentHTMLPropertyDescriptor=Object.getOwnPropertyDescriptor(HTMLElement.prototype,"insertAdjacentHTML"),Node_get_attributes=Object.getOwnPropertyDescriptor(Node.prototype,"attributes").get,Node_get_childNodes=Object.getOwnPropertyDescriptor(Node.prototype,"childNodes").get,detectionDiv=document.createElement("div");cleansePropertySetter("innerHTML",function(propertyDescriptor,target,elements){empty(target);for(var i=0,len=elements.length;len>i;i++)target.appendChild(elements[i])}),cleansePropertySetter("outerHTML",function(propertyDescriptor,target,elements){for(var i=0,len=elements.length;len>i;i++)target.insertAdjacentElement("afterend",elements[i]);target.parentNode.removeChild(target)})}}(),"undefined"==typeof WeakMap&&!function(){var defineProperty=Object.defineProperty,counter=Date.now()%1e9,WeakMap=function(){this.name="__st"+(1e9*Math.random()>>>0)+(counter++ +"__")};WeakMap.prototype={set:function(key,value){var entry=key[this.name];return entry&&entry[0]===key?entry[1]=value:defineProperty(key,this.name,{value:[key,value],writable:!0}),this},get:function(key){var entry;return(entry=key[this.name])&&entry[0]===key?entry[1]:void 0},"delete":function(key){var entry=key[this.name];return entry&&entry[0]===key?(entry[0]=entry[1]=void 0, !0):!1},has:function(key){var entry=key[this.name];return entry?entry[0]===key:!1}},window.WeakMap=WeakMap}(),function(global){function scheduleCallback(observer){scheduledObservers.push(observer),isScheduled||(isScheduled=!0,setImmediate(dispatchCallbacks))}function wrapIfNeeded(node){return window.ShadowDOMPolyfill&&window.ShadowDOMPolyfill.wrapIfNeeded(node)||node}function dispatchCallbacks(){isScheduled=!1;var observers=scheduledObservers;scheduledObservers=[],observers.sort(function(o1,o2){return o1.uid_-o2.uid_});var anyNonEmpty=!1;observers.forEach(function(observer){var queue=observer.takeRecords();removeTransientObserversFor(observer),queue.length&&(observer.callback_(queue,observer),anyNonEmpty=!0)}),anyNonEmpty&&dispatchCallbacks()}function removeTransientObserversFor(observer){observer.nodes_.forEach(function(node){var registrations=registrationsTable.get(node);registrations&&registrations.forEach(function(registration){registration.observer===observer&&registration.removeTransientObservers()})})}function forEachAncestorAndObserverEnqueueRecord(target,callback){for(var node=target;node;node=node.parentNode){var registrations=registrationsTable.get(node);if(registrations)for(var j=0;j<registrations.length;j++){var registration=registrations[j],options=registration.options;if(node===target||options.subtree){var record=callback(options);record&&registration.enqueue(record)}}}}function JsMutationObserver(callback){this.callback_=callback,this.nodes_=[],this.records_=[],this.uid_=++uidCounter}function MutationRecord(type,target){this.type=type,this.target=target,this.addedNodes=[],this.removedNodes=[],this.previousSibling=null,this.nextSibling=null,this.attributeName=null,this.attributeNamespace=null,this.oldValue=null}function copyMutationRecord(original){var record=new MutationRecord(original.type,original.target);return record.addedNodes=original.addedNodes.slice(),record.removedNodes=original.removedNodes.slice(),record.previousSibling=original.previousSibling,record.nextSibling=original.nextSibling,record.attributeName=original.attributeName,record.attributeNamespace=original.attributeNamespace,record.oldValue=original.oldValue,record}function getRecord(type,target){return currentRecord=new MutationRecord(type,target)}function getRecordWithOldValue(oldValue){return recordWithOldValue?recordWithOldValue:(recordWithOldValue=copyMutationRecord(currentRecord),recordWithOldValue.oldValue=oldValue,recordWithOldValue)}function clearRecords(){currentRecord=recordWithOldValue=void 0}function recordRepresentsCurrentMutation(record){return record===recordWithOldValue||record===currentRecord}function selectRecord(lastRecord,newRecord){return lastRecord===newRecord?lastRecord:recordWithOldValue&&recordRepresentsCurrentMutation(lastRecord)?recordWithOldValue:null}function Registration(observer,target,options){this.observer=observer,this.target=target,this.options=options,this.transientObservedNodes=[]}var setImmediate,registrationsTable=new WeakMap;if(/Trident|Edge/.test(navigator.userAgent))setImmediate=setTimeout;else if(window.setImmediate)setImmediate=window.setImmediate;else{var setImmediateQueue=[],sentinel=String(Math.random());window.addEventListener("message",function(e){if(e.data===sentinel){var queue=setImmediateQueue;setImmediateQueue=[],queue.forEach(function(func){func()})}}),setImmediate=function(func){setImmediateQueue.push(func),window.postMessage(sentinel,"*")}}var isScheduled=!1,scheduledObservers=[],uidCounter=0;JsMutationObserver.prototype={observe:function(target,options){if(target=wrapIfNeeded(target),!options.childList&&!options.attributes&&!options.characterData||options.attributeOldValue&&!options.attributes||options.attributeFilter&&options.attributeFilter.length&&!options.attributes||options.characterDataOldValue&&!options.characterData)throw new SyntaxError;var registrations=registrationsTable.get(target);registrations||registrationsTable.set(target,registrations=[]);for(var registration,i=0;i<registrations.length;i++)if(registrations[i].observer===this){registration=registrations[i],registration.removeListeners(),registration.options=options;break}registration||(registration=new Registration(this,target,options),registrations.push(registration),this.nodes_.push(target)),registration.addListeners()},disconnect:function(){this.nodes_.forEach(function(node){for(var registrations=registrationsTable.get(node),i=0;i<registrations.length;i++){var registration=registrations[i];if(registration.observer===this){registration.removeListeners(),registrations.splice(i,1);break}}},this),this.records_=[]},takeRecords:function(){var copyOfRecords=this.records_;return this.records_=[],copyOfRecords}};var currentRecord,recordWithOldValue;Registration.prototype={enqueue:function(record){var records=this.observer.records_,length=records.length;if(records.length>0){var lastRecord=records[length-1],recordToReplaceLast=selectRecord(lastRecord,record);if(recordToReplaceLast)return void(records[length-1]=recordToReplaceLast)}else scheduleCallback(this.observer);records[length]=record},addListeners:function(){this.addListeners_(this.target)},addListeners_:function(node){var options=this.options;options.attributes&&node.addEventListener("DOMAttrModified",this,!0),options.characterData&&node.addEventListener("DOMCharacterDataModified",this,!0),options.childList&&node.addEventListener("DOMNodeInserted",this,!0),(options.childList||options.subtree)&&node.addEventListener("DOMNodeRemoved",this,!0)},removeListeners:function(){this.removeListeners_(this.target)},removeListeners_:function(node){var options=this.options;options.attributes&&node.removeEventListener("DOMAttrModified",this,!0),options.characterData&&node.removeEventListener("DOMCharacterDataModified",this,!0),options.childList&&node.removeEventListener("DOMNodeInserted",this,!0),(options.childList||options.subtree)&&node.removeEventListener("DOMNodeRemoved",this,!0)},addTransientObserver:function(node){if(node!==this.target){this.addListeners_(node),this.transientObservedNodes.push(node);var registrations=registrationsTable.get(node);registrations||registrationsTable.set(node,registrations=[]),registrations.push(this)}},removeTransientObservers:function(){var transientObservedNodes=this.transientObservedNodes;this.transientObservedNodes=[],transientObservedNodes.forEach(function(node){this.removeListeners_(node);for(var registrations=registrationsTable.get(node),i=0;i<registrations.length;i++)if(registrations[i]===this){registrations.splice(i,1);break}},this)},handleEvent:function(e){switch(e.stopImmediatePropagation(),e.type){case"DOMAttrModified":var name=e.attrName,namespace=e.relatedNode.namespaceURI,target=e.target,record=new getRecord("attributes",target);record.attributeName=name,record.attributeNamespace=namespace;var oldValue=e.attrChange===MutationEvent.ADDITION?null:e.prevValue;forEachAncestorAndObserverEnqueueRecord(target,function(options){return!options.attributes||options.attributeFilter&&options.attributeFilter.length&&-1===options.attributeFilter.indexOf(name)&&-1===options.attributeFilter.indexOf(namespace)?void 0:options.attributeOldValue?getRecordWithOldValue(oldValue):record});break;case"DOMCharacterDataModified":var target=e.target,record=getRecord("characterData",target),oldValue=e.prevValue;forEachAncestorAndObserverEnqueueRecord(target,function(options){return options.characterData?options.characterDataOldValue?getRecordWithOldValue(oldValue):record:void 0});break;case"DOMNodeRemoved":this.addTransientObserver(e.target);case"DOMNodeInserted":var addedNodes,removedNodes,changedNode=e.target;"DOMNodeInserted"===e.type?(addedNodes=[changedNode],removedNodes=[]):(addedNodes=[],removedNodes=[changedNode]);var previousSibling=changedNode.previousSibling,nextSibling=changedNode.nextSibling,record=getRecord("childList",e.target.parentNode);record.addedNodes=addedNodes,record.removedNodes=removedNodes,record.previousSibling=previousSibling,record.nextSibling=nextSibling,forEachAncestorAndObserverEnqueueRecord(e.relatedNode,function(options){return options.childList?record:void 0})}clearRecords()}},global.JsMutationObserver=JsMutationObserver,global.MutationObserver||(global.MutationObserver=JsMutationObserver)}(this),window.CustomElements=window.CustomElements||{flags:{}},function(scope){var flags=scope.flags,modules=[],addModule=function(module){modules.push(module)},initializeModules=function(){modules.forEach(function(module){module(scope)})};scope.addModule=addModule,scope.initializeModules=initializeModules,scope.hasNative=Boolean(document.registerElement),scope.useNative=!flags.register&&scope.hasNative&&!window.ShadowDOMPolyfill&&(!window.HTMLImports||HTMLImports.useNative)}(window.CustomElements),window.CustomElements.addModule(function(scope){function forSubtree(node,cb){findAllElements(node,function(e){return cb(e)?!0:void forRoots(e,cb)}),forRoots(node,cb)}function findAllElements(node,find,data){var e=node.firstElementChild;if(!e)for(e=node.firstChild;e&&e.nodeType!==Node.ELEMENT_NODE;)e=e.nextSibling;for(;e;)find(e,data)!==!0&&findAllElements(e,find,data),e=e.nextElementSibling;return null}function forRoots(node,cb){for(var root=node.shadowRoot;root;)forSubtree(root,cb),root=root.olderShadowRoot}function forDocumentTree(doc,cb){_forDocumentTree(doc,cb,[])}function _forDocumentTree(doc,cb,processingDocuments){if(doc=wrap(doc),!(processingDocuments.indexOf(doc)>=0)){processingDocuments.push(doc);for(var n,imports=doc.querySelectorAll("link[rel="+IMPORT_LINK_TYPE+"]"),i=0,l=imports.length;l>i&&(n=imports[i]);i++)n["import"]&&_forDocumentTree(n["import"],cb,processingDocuments);cb(doc)}}var IMPORT_LINK_TYPE=window.HTMLImports?HTMLImports.IMPORT_LINK_TYPE:"none";scope.forDocumentTree=forDocumentTree,scope.forSubtree=forSubtree}),window.CustomElements.addModule(function(scope){function addedNode(node){return added(node)||addedSubtree(node)}function added(node){return scope.upgrade(node)?!0:void attached(node)}function addedSubtree(node){forSubtree(node,function(e){return added(e)?!0:void 0})}function attachedNode(node){attached(node),inDocument(node)&&forSubtree(node,function(e){attached(e)})}function deferMutation(fn){pendingMutations.push(fn),isPendingMutations||(isPendingMutations=!0,setTimeout(takeMutations))}function takeMutations(){isPendingMutations=!1;for(var p,$p=pendingMutations,i=0,l=$p.length;l>i&&(p=$p[i]);i++)p();pendingMutations=[]}function attached(element){hasPolyfillMutations?deferMutation(function(){_attached(element)}):_attached(element)}function _attached(element){element.__upgraded__&&(element.attachedCallback||element.detachedCallback)&&!element.__attached&&inDocument(element)&&(element.__attached=!0,element.attachedCallback&&element.attachedCallback())}function detachedNode(node){detached(node),forSubtree(node,function(e){detached(e)})}function detached(element){hasPolyfillMutations?deferMutation(function(){_detached(element)}):_detached(element)}function _detached(element){element.__upgraded__&&(element.attachedCallback||element.detachedCallback)&&element.__attached&&!inDocument(element)&&(element.__attached=!1,element.detachedCallback&&element.detachedCallback())}function inDocument(element){for(var p=element,doc=wrap(document);p;){if(p==doc)return!0;p=p.parentNode||p.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&p.host}}function watchShadow(node){if(node.shadowRoot&&!node.shadowRoot.__watched){flags.dom&&console.log("watching shadow-root for: ",node.localName);for(var root=node.shadowRoot;root;)observe(root),root=root.olderShadowRoot}}function handler(mutations){if(flags.dom){var mx=mutations[0];if(mx&&"childList"===mx.type&&mx.addedNodes&&mx.addedNodes){for(var d=mx.addedNodes[0];d&&d!==document&&!d.host;)d=d.parentNode;var u=d&&(d.URL||d._URL||d.host&&d.host.localName)||"";u=u.split("/?").shift().split("/").pop()}console.group("mutations (%d) [%s]",mutations.length,u||"")}mutations.forEach(function(mx){"childList"===mx.type&&(forEach(mx.addedNodes,function(n){n.localName&&addedNode(n)}),forEach(mx.removedNodes,function(n){n.localName&&detachedNode(n)}))}),flags.dom&&console.groupEnd()}function takeRecords(node){for(node=wrap(node),node||(node=wrap(document));node.parentNode;)node=node.parentNode;var observer=node.__observer;observer&&(handler(observer.takeRecords()),takeMutations())}function observe(inRoot){if(!inRoot.__observer){var observer=new MutationObserver(handler);observer.observe(inRoot,{childList:!0,subtree:!0}),inRoot.__observer=observer}}function upgradeDocument(doc){doc=wrap(doc),flags.dom&&console.group("upgradeDocument: ",doc.baseURI.split("/").pop()),addedNode(doc),observe(doc),flags.dom&&console.groupEnd()}function upgradeDocumentTree(doc){forDocumentTree(doc,upgradeDocument)}var flags=scope.flags,forSubtree=scope.forSubtree,forDocumentTree=scope.forDocumentTree,hasPolyfillMutations=!window.MutationObserver||window.MutationObserver===window.JsMutationObserver;scope.hasPolyfillMutations=hasPolyfillMutations;var isPendingMutations=!1,pendingMutations=[],forEach=Array.prototype.forEach.call.bind(Array.prototype.forEach),originalCreateShadowRoot=Element.prototype.createShadowRoot;originalCreateShadowRoot&&(Element.prototype.createShadowRoot=function(){var root=originalCreateShadowRoot.call(this);return CustomElements.watchShadow(this),root}),scope.watchShadow=watchShadow,scope.upgradeDocumentTree=upgradeDocumentTree,scope.upgradeSubtree=addedSubtree,scope.upgradeAll=addedNode,scope.attachedNode=attachedNode,scope.takeRecords=takeRecords}),window.CustomElements.addModule(function(scope){function upgrade(node){if(!node.__upgraded__&&node.nodeType===Node.ELEMENT_NODE){var is=node.getAttribute("is"),definition=scope.getRegisteredDefinition(is||node.localName);if(definition){if(is&&definition.tag==node.localName)return upgradeWithDefinition(node,definition);if(!is&&!definition["extends"])return upgradeWithDefinition(node,definition)}}}function upgradeWithDefinition(element,definition){return flags.upgrade&&console.group("upgrade:",element.localName),definition.is&&element.setAttribute("is",definition.is),implementPrototype(element,definition),element.__upgraded__=!0,created(element),scope.attachedNode(element),scope.upgradeSubtree(element),flags.upgrade&&console.groupEnd(),element}function implementPrototype(element,definition){Object.__proto__?element.__proto__=definition.prototype:(customMixin(element,definition.prototype,definition["native"]),element.__proto__=definition.prototype)}function customMixin(inTarget,inSrc,inNative){for(var used={},p=inSrc;p!==inNative&&p!==HTMLElement.prototype;){for(var k,keys=Object.getOwnPropertyNames(p),i=0;k=keys[i];i++)used[k]||(Object.defineProperty(inTarget,k,Object.getOwnPropertyDescriptor(p,k)),used[k]=1);p=Object.getPrototypeOf(p)}}function created(element){element.createdCallback&&element.createdCallback()}var flags=scope.flags;scope.upgrade=upgrade,scope.upgradeWithDefinition=upgradeWithDefinition,scope.implementPrototype=implementPrototype}),window.CustomElements.addModule(function(scope){function register(name,options){var definition=options||{};if(!name)throw new Error("document.registerElement: first argument `name` must not be empty");if(name.indexOf("-")<0)throw new Error("document.registerElement: first argument ('name') must contain a dash ('-'). Argument provided was '"+String(name)+"'.");if(isReservedTag(name))throw new Error("Failed to execute 'registerElement' on 'Document': Registration failed for type '"+String(name)+"'. The type name is invalid.");if(getRegisteredDefinition(name))throw new Error("DuplicateDefinitionError: a type with name '"+String(name)+"' is already registered");return definition.prototype||(definition.prototype=Object.create(HTMLElement.prototype)),definition.__name=name.toLowerCase(),definition.lifecycle=definition.lifecycle||{},definition.ancestry=ancestry(definition["extends"]),resolveTagName(definition),resolvePrototypeChain(definition),overrideAttributeApi(definition.prototype),registerDefinition(definition.__name,definition),definition.ctor=generateConstructor(definition),definition.ctor.prototype=definition.prototype,definition.prototype.constructor=definition.ctor,scope.ready&&upgradeDocumentTree(document),definition.ctor}function overrideAttributeApi(prototype){if(!prototype.setAttribute._polyfilled){var setAttribute=prototype.setAttribute;prototype.setAttribute=function(name,value){changeAttribute.call(this,name,value,setAttribute)};var removeAttribute=prototype.removeAttribute;prototype.removeAttribute=function(name){changeAttribute.call(this,name,null,removeAttribute)},prototype.setAttribute._polyfilled=!0}}function changeAttribute(name,value,operation){name=name.toLowerCase();var oldValue=this.getAttribute(name);operation.apply(this,arguments);var newValue=this.getAttribute(name);this.attributeChangedCallback&&newValue!==oldValue&&this.attributeChangedCallback(name,oldValue,newValue)}function isReservedTag(name){for(var i=0;i<reservedTagList.length;i++)if(name===reservedTagList[i])return!0}function ancestry(extnds){var extendee=getRegisteredDefinition(extnds);return extendee?ancestry(extendee["extends"]).concat([extendee]):[]}function resolveTagName(definition){for(var a,baseTag=definition["extends"],i=0;a=definition.ancestry[i];i++)baseTag=a.is&&a.tag;definition.tag=baseTag||definition.__name,baseTag&&(definition.is=definition.__name)}function resolvePrototypeChain(definition){if(!Object.__proto__){var nativePrototype=HTMLElement.prototype;if(definition.is){var inst=document.createElement(definition.tag),expectedPrototype=Object.getPrototypeOf(inst);expectedPrototype===definition.prototype&&(nativePrototype=expectedPrototype)}for(var ancestor,proto=definition.prototype;proto&&proto!==nativePrototype;)ancestor=Object.getPrototypeOf(proto),proto.__proto__=ancestor,proto=ancestor;definition["native"]=nativePrototype}}function instantiate(definition){return upgradeWithDefinition(domCreateElement(definition.tag),definition)}function getRegisteredDefinition(name){return name?registry[name.toLowerCase()]:void 0}function registerDefinition(name,definition){registry[name]=definition}function generateConstructor(definition){return function(){return instantiate(definition)}}function createElementNS(namespace,tag,typeExtension){return namespace===HTML_NAMESPACE?createElement(tag,typeExtension):domCreateElementNS(namespace,tag)}function createElement(tag,typeExtension){tag&&(tag=tag.toLowerCase()),typeExtension&&(typeExtension=typeExtension.toLowerCase());var definition=getRegisteredDefinition(typeExtension||tag);if(definition){if(tag==definition.tag&&typeExtension==definition.is)return new definition.ctor;if(!typeExtension&&!definition.is)return new definition.ctor}var element;return typeExtension?(element=createElement(tag),element.setAttribute("is",typeExtension),element):(element=domCreateElement(tag),tag.indexOf("-")>=0&&implementPrototype(element,HTMLElement),element)}function wrapDomMethodToForceUpgrade(obj,methodName){var orig=obj[methodName];obj[methodName]=function(){var n=orig.apply(this,arguments);return upgradeAll(n),n}}var isInstance,isIE11OrOlder=scope.isIE11OrOlder,upgradeDocumentTree=scope.upgradeDocumentTree,upgradeAll=scope.upgradeAll,upgradeWithDefinition=scope.upgradeWithDefinition,implementPrototype=scope.implementPrototype,useNative=scope.useNative,reservedTagList=["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"],registry={},HTML_NAMESPACE="http://www.w3.org/1999/xhtml",domCreateElement=document.createElement.bind(document),domCreateElementNS=document.createElementNS.bind(document);isInstance=Object.__proto__||useNative?function(obj,base){return obj instanceof base}:function(obj,ctor){for(var p=obj;p;){if(p===ctor.prototype)return!0;p=p.__proto__}return!1},wrapDomMethodToForceUpgrade(Node.prototype,"cloneNode"),wrapDomMethodToForceUpgrade(document,"importNode"),isIE11OrOlder&&!function(){var importNode=document.importNode;document.importNode=function(){var n=importNode.apply(document,arguments);if(n.nodeType==n.DOCUMENT_FRAGMENT_NODE){var f=document.createDocumentFragment();return f.appendChild(n),f}return n}}(),document.registerElement=register,document.createElement=createElement,document.createElementNS=createElementNS,scope.registry=registry,scope["instanceof"]=isInstance,scope.reservedTagList=reservedTagList,scope.getRegisteredDefinition=getRegisteredDefinition,document.register=document.registerElement}),function(scope){function bootstrap(){upgradeDocumentTree(wrap(document)),window.HTMLImports&&(HTMLImports.__importsParsingHook=function(elt){upgradeDocumentTree(wrap(elt["import"]))}),CustomElements.ready=!0,setTimeout(function(){CustomElements.readyTime=Date.now(),window.HTMLImports&&(CustomElements.elapsed=CustomElements.readyTime-HTMLImports.readyTime),document.dispatchEvent(new CustomEvent("WebComponentsReady",{bubbles:!0}))})}var useNative=scope.useNative,initializeModules=scope.initializeModules,isIE11OrOlder=/Trident/.test(navigator.userAgent);if(useNative){var nop=function(){};scope.watchShadow=nop,scope.upgrade=nop,scope.upgradeAll=nop,scope.upgradeDocumentTree=nop,scope.upgradeSubtree=nop,scope.takeRecords=nop,scope["instanceof"]=function(obj,base){return obj instanceof base}}else initializeModules();var upgradeDocumentTree=scope.upgradeDocumentTree;if(window.wrap||(window.ShadowDOMPolyfill?(window.wrap=ShadowDOMPolyfill.wrapIfNeeded,window.unwrap=ShadowDOMPolyfill.unwrapIfNeeded):window.wrap=window.unwrap=function(node){return node}),isIE11OrOlder&&"function"!=typeof window.CustomEvent&&(window.CustomEvent=function(inType,params){params=params||{};var e=document.createEvent("CustomEvent");return e.initCustomEvent(inType,Boolean(params.bubbles),Boolean(params.cancelable),params.detail),e},window.CustomEvent.prototype=window.Event.prototype),"complete"===document.readyState||scope.flags.eager)bootstrap();else if("interactive"!==document.readyState||window.attachEvent||window.HTMLImports&&!window.HTMLImports.ready){var loadEvent=window.HTMLImports&&!HTMLImports.ready?"HTMLImportsLoaded":"DOMContentLoaded";window.addEventListener(loadEvent,bootstrap)}else bootstrap();scope.isIE11OrOlder=isIE11OrOlder}(window.CustomElements),window.CustomEvent||!function(){var CustomEvent;CustomEvent=function(event,params){var evt;return params=params||{bubbles:!1,cancelable:!1,detail:void 0},evt=document.createEvent("CustomEvent"),evt.initCustomEvent(event,params.bubbles,params.cancelable,params.detail),evt},CustomEvent.prototype=window.Event.prototype,window.CustomEvent=CustomEvent}(),function(){var initializing=!1,fnTest=/xyz/.test(function(){xyz})?/\b_super\b/:/.*/;this.Class=function(){},Class.extend=function(prop){function Class(){!initializing&&this.init&&this.init.apply(this,arguments)}var _super=this.prototype;initializing=!0;var prototype=new this;initializing=!1;for(var name in prop)prototype[name]="function"==typeof prop[name]&&"function"==typeof _super[name]&&fnTest.test(prop[name])?function(name,fn){return function(){var tmp=this._super;this._super=_super[name];var ret=fn.apply(this,arguments);return this._super=tmp,ret}}(name,prop[name]):prop[name];return Class.prototype=prototype,Class.prototype.constructor=Class,Class.extend=arguments.callee,Class}}(),function(){"use strict";function FastClick(layer,options){function bind(method,context){return function(){return method.apply(context,arguments)}}var oldOnClick;if(options=options||{},this.trackingClick=!1,this.trackingClickStart=0,this.targetElement=null,this.touchStartX=0,this.touchStartY=0,this.lastTouchIdentifier=0,this.touchBoundary=options.touchBoundary||10,this.layer=layer,this.tapDelay=options.tapDelay||200,this.tapTimeout=options.tapTimeout||700,!FastClick.notNeeded(layer)){for(var methods=["onMouse","onClick","onTouchStart","onTouchMove","onTouchEnd","onTouchCancel"],context=this,i=0,l=methods.length;l>i;i++)context[methods[i]]=bind(context[methods[i]],context);deviceIsAndroid&&(layer.addEventListener("mouseover",this.onMouse,!0),layer.addEventListener("mousedown",this.onMouse,!0),layer.addEventListener("mouseup",this.onMouse,!0)),layer.addEventListener("click",this.onClick,!0),layer.addEventListener("touchstart",this.onTouchStart,!1),layer.addEventListener("touchmove",this.onTouchMove,!1),layer.addEventListener("touchend",this.onTouchEnd,!1),layer.addEventListener("touchcancel",this.onTouchCancel,!1),Event.prototype.stopImmediatePropagation||(layer.removeEventListener=function(type,callback,capture){var rmv=Node.prototype.removeEventListener;"click"===type?rmv.call(layer,type,callback.hijacked||callback,capture):rmv.call(layer,type,callback,capture)},layer.addEventListener=function(type,callback,capture){var adv=Node.prototype.addEventListener;"click"===type?adv.call(layer,type,callback.hijacked||(callback.hijacked=function(event){event.propagationStopped||callback(event)}),capture):adv.call(layer,type,callback,capture)}),"function"==typeof layer.onclick&&(oldOnClick=layer.onclick,layer.addEventListener("click",function(event){oldOnClick(event)},!1),layer.onclick=null)}}var deviceIsWindowsPhone=navigator.userAgent.indexOf("Windows Phone")>=0,deviceIsAndroid=navigator.userAgent.indexOf("Android")>0&&!deviceIsWindowsPhone,deviceIsIOS=/iP(ad|hone|od)/.test(navigator.userAgent)&&!deviceIsWindowsPhone,deviceIsIOS4=deviceIsIOS&&/OS 4_\d(_\d)?/.test(navigator.userAgent),deviceIsIOSWithBadTarget=deviceIsIOS&&/OS [6-7]_\d/.test(navigator.userAgent),deviceIsBlackBerry10=navigator.userAgent.indexOf("BB10")>0;FastClick.prototype.needsClick=function(target){switch(target.nodeName.toLowerCase()){case"button":case"select":case"textarea":if(target.disabled)return!0;break;case"input":if(deviceIsIOS&&"file"===target.type||target.disabled)return!0;break;case"label":case"iframe":case"video":return!0}return/\bneedsclick\b/.test(target.className)},FastClick.prototype.needsFocus=function(target){switch(target.nodeName.toLowerCase()){case"textarea":return!0;case"select":return!deviceIsAndroid;case"input":switch(target.type){case"button":case"checkbox":case"file":case"image":case"radio":case"submit":return!1}return!target.disabled&&!target.readOnly;default:return/\bneedsfocus\b/.test(target.className)}},FastClick.prototype.sendClick=function(targetElement,event){var clickEvent,touch;document.activeElement&&document.activeElement!==targetElement&&document.activeElement.blur(),touch=event.changedTouches[0],clickEvent=document.createEvent("MouseEvents"),clickEvent.initMouseEvent(this.determineEventType(targetElement),!0,!0,window,1,touch.screenX,touch.screenY,touch.clientX,touch.clientY,!1,!1,!1,!1,0,null),clickEvent.forwardedTouchEvent=!0,targetElement.dispatchEvent(clickEvent)},FastClick.prototype.determineEventType=function(targetElement){return deviceIsAndroid&&"select"===targetElement.tagName.toLowerCase()?"mousedown":"click"},FastClick.prototype.focus=function(targetElement){var length;deviceIsIOS&&targetElement.setSelectionRange&&0!==targetElement.type.indexOf("date")&&"time"!==targetElement.type&&"month"!==targetElement.type?(length=targetElement.value.length,targetElement.setSelectionRange(length,length)):targetElement.focus()},FastClick.prototype.updateScrollParent=function(targetElement){var scrollParent,parentElement;if(scrollParent=targetElement.fastClickScrollParent,!scrollParent||!scrollParent.contains(targetElement)){parentElement=targetElement;do{if(parentElement.scrollHeight>parentElement.offsetHeight){scrollParent=parentElement,targetElement.fastClickScrollParent=parentElement;break}parentElement=parentElement.parentElement}while(parentElement)}scrollParent&&(scrollParent.fastClickLastScrollTop=scrollParent.scrollTop)},FastClick.prototype.getTargetElementFromEventTarget=function(eventTarget){return eventTarget.nodeType===Node.TEXT_NODE?eventTarget.parentNode:eventTarget},FastClick.prototype.onTouchStart=function(event){var targetElement,touch,selection;if(event.targetTouches.length>1)return!0;if(targetElement=this.getTargetElementFromEventTarget(event.target),touch=event.targetTouches[0],deviceIsIOS){if(selection=window.getSelection(),selection.rangeCount&&!selection.isCollapsed)return!0;if(!deviceIsIOS4){if(touch.identifier&&touch.identifier===this.lastTouchIdentifier)return event.preventDefault(),!1;this.lastTouchIdentifier=touch.identifier,this.updateScrollParent(targetElement)}}return this.trackingClick=!0,this.trackingClickStart=event.timeStamp,this.targetElement=targetElement,this.touchStartX=touch.pageX,this.touchStartY=touch.pageY,event.timeStamp-this.lastClickTime<this.tapDelay&&event.timeStamp-this.lastClickTime>-1&&event.preventDefault(),!0},FastClick.prototype.touchHasMoved=function(event){var touch=event.changedTouches[0],boundary=this.touchBoundary;return Math.abs(touch.pageX-this.touchStartX)>boundary||Math.abs(touch.pageY-this.touchStartY)>boundary?!0:!1},FastClick.prototype.onTouchMove=function(event){return this.trackingClick?((this.targetElement!==this.getTargetElementFromEventTarget(event.target)||this.touchHasMoved(event))&&(this.trackingClick=!1,this.targetElement=null),!0):!0},FastClick.prototype.findControl=function(labelElement){return void 0!==labelElement.control?labelElement.control:labelElement.htmlFor?document.getElementById(labelElement.htmlFor):labelElement.querySelector("button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea")},FastClick.prototype.onTouchEnd=function(event){var forElement,trackingClickStart,targetTagName,scrollParent,touch,targetElement=this.targetElement;if(!this.trackingClick)return!0;if(event.timeStamp-this.lastClickTime<this.tapDelay&&event.timeStamp-this.lastClickTime>-1)return this.cancelNextClick=!0,!0;if(event.timeStamp-this.trackingClickStart>this.tapTimeout)return!0;if(this.cancelNextClick=!1,this.lastClickTime=event.timeStamp,trackingClickStart=this.trackingClickStart,this.trackingClick=!1,this.trackingClickStart=0,deviceIsIOSWithBadTarget&&(touch=event.changedTouches[0],targetElement=document.elementFromPoint(touch.pageX-window.pageXOffset,touch.pageY-window.pageYOffset)||targetElement,targetElement.fastClickScrollParent=this.targetElement.fastClickScrollParent),targetTagName=targetElement.tagName.toLowerCase(),"label"===targetTagName){if(forElement=this.findControl(targetElement)){if(this.focus(targetElement),deviceIsAndroid)return!1;targetElement=forElement}}else if(this.needsFocus(targetElement))return event.timeStamp-trackingClickStart>100||deviceIsIOS&&window.top!==window&&"input"===targetTagName?(this.targetElement=null,!1):(this.focus(targetElement),this.sendClick(targetElement,event),deviceIsIOS&&"select"===targetTagName||(this.targetElement=null,event.preventDefault()),!1);return deviceIsIOS&&!deviceIsIOS4&&(scrollParent=targetElement.fastClickScrollParent,scrollParent&&scrollParent.fastClickLastScrollTop!==scrollParent.scrollTop)?!0:(this.needsClick(targetElement)||(event.preventDefault(),this.sendClick(targetElement,event)),!1)},FastClick.prototype.onTouchCancel=function(){this.trackingClick=!1,this.targetElement=null},FastClick.prototype.onMouse=function(event){return this.targetElement?event.forwardedTouchEvent?!0:event.cancelable&&(!this.needsClick(this.targetElement)||this.cancelNextClick)?(event.stopImmediatePropagation?event.stopImmediatePropagation():event.propagationStopped=!0,event.stopPropagation(),event.preventDefault(),!1):!0:!0},FastClick.prototype.onClick=function(event){var permitted;return this.trackingClick?(this.targetElement=null,this.trackingClick=!1,!0):"submit"===event.target.type&&0===event.detail?!0:(permitted=this.onMouse(event),permitted||(this.targetElement=null),permitted)},FastClick.prototype.destroy=function(){var layer=this.layer;deviceIsAndroid&&(layer.removeEventListener("mouseover",this.onMouse,!0),layer.removeEventListener("mousedown",this.onMouse,!0),layer.removeEventListener("mouseup",this.onMouse,!0)),layer.removeEventListener("click",this.onClick,!0),layer.removeEventListener("touchstart",this.onTouchStart,!1), layer.removeEventListener("touchmove",this.onTouchMove,!1),layer.removeEventListener("touchend",this.onTouchEnd,!1),layer.removeEventListener("touchcancel",this.onTouchCancel,!1)},FastClick.notNeeded=function(layer){var metaViewport,chromeVersion,blackberryVersion,firefoxVersion;if("undefined"==typeof window.ontouchstart)return!0;if(chromeVersion=+(/Chrome\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1]){if(!deviceIsAndroid)return!0;if(metaViewport=document.querySelector("meta[name=viewport]")){if(-1!==metaViewport.content.indexOf("user-scalable=no"))return!0;if(chromeVersion>31&&document.documentElement.scrollWidth<=window.outerWidth)return!0}}if(deviceIsBlackBerry10&&(blackberryVersion=navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/),blackberryVersion[1]>=10&&blackberryVersion[2]>=3&&(metaViewport=document.querySelector("meta[name=viewport]")))){if(-1!==metaViewport.content.indexOf("user-scalable=no"))return!0;if(document.documentElement.scrollWidth<=window.outerWidth)return!0}return"none"===layer.style.msTouchAction||"manipulation"===layer.style.touchAction?!0:(firefoxVersion=+(/Firefox\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1],firefoxVersion>=27&&(metaViewport=document.querySelector("meta[name=viewport]"),metaViewport&&(-1!==metaViewport.content.indexOf("user-scalable=no")||document.documentElement.scrollWidth<=window.outerWidth))?!0:"none"===layer.style.touchAction||"manipulation"===layer.style.touchAction?!0:!1)},FastClick.attach=function(layer,options){return new FastClick(layer,options)},"function"==typeof define&&"object"==typeof define.amd&&define.amd?define(function(){return FastClick}):"undefined"!=typeof module&&module.exports?(module.exports=FastClick.attach,module.exports.FastClick=FastClick):window.FastClick=FastClick}();var MicroEvent=function(){};MicroEvent.prototype={on:function(event,fct){this._events=this._events||{},this._events[event]=this._events[event]||[],this._events[event].push(fct)},once:function(event,fct){var self=this,wrapper=function(){return self.off(event,wrapper),fct.apply(null,arguments)};this.on(event,wrapper)},off:function(event,fct){this._events=this._events||{},event in this._events!=!1&&this._events[event].splice(this._events[event].indexOf(fct),1)},emit:function(event){if(this._events=this._events||{},event in this._events!=!1)for(var i=0;i<this._events[event].length;i++)this._events[event][i].apply(this,Array.prototype.slice.call(arguments,1))}},MicroEvent.mixin=function(destObject){for(var props=["on","once","off","emit"],i=0;i<props.length;i++)"function"==typeof destObject?destObject.prototype[props[i]]=MicroEvent.prototype[props[i]]:destObject[props[i]]=MicroEvent.prototype[props[i]]},"undefined"!=typeof module&&"exports"in module&&(module.exports=MicroEvent),window.Modernizr=function(window,document,undefined){function setCss(str){mStyle.cssText=str}function is(obj,type){return typeof obj===type}function contains(str,substr){return!!~(""+str).indexOf(substr)}function testProps(props,prefixed){for(var i in props){var prop=props[i];if(!contains(prop,"-")&&mStyle[prop]!==undefined)return"pfx"==prefixed?prop:!0}return!1}function testDOMProps(props,obj,elem){for(var i in props){var item=obj[props[i]];if(item!==undefined)return elem===!1?props[i]:is(item,"function")?item.bind(elem||obj):item}return!1}function testPropsAll(prop,prefixed,elem){var ucProp=prop.charAt(0).toUpperCase()+prop.slice(1),props=(prop+" "+cssomPrefixes.join(ucProp+" ")+ucProp).split(" ");return is(prefixed,"string")||is(prefixed,"undefined")?testProps(props,prefixed):(props=(prop+" "+domPrefixes.join(ucProp+" ")+ucProp).split(" "),testDOMProps(props,prefixed,elem))}var inputElem,featureName,hasOwnProp,version="2.6.2",Modernizr={},enableClasses=!0,docElement=document.documentElement,mod="modernizr",modElem=document.createElement(mod),mStyle=modElem.style,prefixes=({}.toString," -webkit- -moz- -o- -ms- ".split(" ")),omPrefixes="Webkit Moz O ms",cssomPrefixes=omPrefixes.split(" "),domPrefixes=omPrefixes.toLowerCase().split(" "),ns={svg:"http://www.w3.org/2000/svg"},tests={},classes=[],slice=classes.slice,injectElementWithStyles=function(rule,callback,nodes,testnames){var style,ret,node,docOverflow,div=document.createElement("div"),body=document.body,fakeBody=body||document.createElement("body");if(parseInt(nodes,10))for(;nodes--;)node=document.createElement("div"),node.id=testnames?testnames[nodes]:mod+(nodes+1),div.appendChild(node);return style=["&#173;",'<style id="s',mod,'">',rule,"</style>"].join(""),div.id=mod,(body?div:fakeBody).innerHTML+=style,fakeBody.appendChild(div),body||(fakeBody.style.background="",fakeBody.style.overflow="hidden",docOverflow=docElement.style.overflow,docElement.style.overflow="hidden",docElement.appendChild(fakeBody)),ret=callback(div,rule),body?div.parentNode.removeChild(div):(fakeBody.parentNode.removeChild(fakeBody),docElement.style.overflow=docOverflow),!!ret},_hasOwnProperty={}.hasOwnProperty;hasOwnProp=is(_hasOwnProperty,"undefined")||is(_hasOwnProperty.call,"undefined")?function(object,property){return property in object&&is(object.constructor.prototype[property],"undefined")}:function(object,property){return _hasOwnProperty.call(object,property)},Function.prototype.bind||(Function.prototype.bind=function(that){var target=this;if("function"!=typeof target)throw new TypeError;var args=slice.call(arguments,1),bound=function(){if(this instanceof bound){var F=function(){};F.prototype=target.prototype;var self=new F,result=target.apply(self,args.concat(slice.call(arguments)));return Object(result)===result?result:self}return target.apply(that,args.concat(slice.call(arguments)))};return bound}),tests.canvas=function(){var elem=document.createElement("canvas");return!(!elem.getContext||!elem.getContext("2d"))},tests.borderradius=function(){return testPropsAll("borderRadius")},tests.boxshadow=function(){return testPropsAll("boxShadow")},tests.cssanimations=function(){return testPropsAll("animationName")},tests.csstransforms=function(){return!!testPropsAll("transform")},tests.csstransforms3d=function(){var ret=!!testPropsAll("perspective");return ret&&"webkitPerspective"in docElement.style&&injectElementWithStyles("@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}",function(node,rule){ret=9===node.offsetLeft&&3===node.offsetHeight}),ret},tests.csstransitions=function(){return testPropsAll("transition")},tests.svg=function(){return!!document.createElementNS&&!!document.createElementNS(ns.svg,"svg").createSVGRect};for(var feature in tests)hasOwnProp(tests,feature)&&(featureName=feature.toLowerCase(),Modernizr[featureName]=tests[feature](),classes.push((Modernizr[featureName]?"":"no-")+featureName));return Modernizr.addTest=function(feature,test){if("object"==typeof feature)for(var key in feature)hasOwnProp(feature,key)&&Modernizr.addTest(key,feature[key]);else{if(feature=feature.toLowerCase(),Modernizr[feature]!==undefined)return Modernizr;test="function"==typeof test?test():test,"undefined"!=typeof enableClasses&&enableClasses&&(docElement.className+=" "+(test?"":"no-")+feature),Modernizr[feature]=test}return Modernizr},setCss(""),modElem=inputElem=null,function(window,document){function addStyleSheet(ownerDocument,cssText){var p=ownerDocument.createElement("p"),parent=ownerDocument.getElementsByTagName("head")[0]||ownerDocument.documentElement;return p.innerHTML="x<style>"+cssText+"</style>",parent.insertBefore(p.lastChild,parent.firstChild)}function getElements(){var elements=html5.elements;return"string"==typeof elements?elements.split(" "):elements}function getExpandoData(ownerDocument){var data=expandoData[ownerDocument[expando]];return data||(data={},expanID++,ownerDocument[expando]=expanID,expandoData[expanID]=data),data}function createElement(nodeName,ownerDocument,data){if(ownerDocument||(ownerDocument=document),supportsUnknownElements)return ownerDocument.createElement(nodeName);data||(data=getExpandoData(ownerDocument));var node;return node=data.cache[nodeName]?data.cache[nodeName].cloneNode():saveClones.test(nodeName)?(data.cache[nodeName]=data.createElem(nodeName)).cloneNode():data.createElem(nodeName),node.canHaveChildren&&!reSkip.test(nodeName)?data.frag.appendChild(node):node}function createDocumentFragment(ownerDocument,data){if(ownerDocument||(ownerDocument=document),supportsUnknownElements)return ownerDocument.createDocumentFragment();data=data||getExpandoData(ownerDocument);for(var clone=data.frag.cloneNode(),i=0,elems=getElements(),l=elems.length;l>i;i++)clone.createElement(elems[i]);return clone}function shivMethods(ownerDocument,data){data.cache||(data.cache={},data.createElem=ownerDocument.createElement,data.createFrag=ownerDocument.createDocumentFragment,data.frag=data.createFrag()),ownerDocument.createElement=function(nodeName){return html5.shivMethods?createElement(nodeName,ownerDocument,data):data.createElem(nodeName)},ownerDocument.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+getElements().join().replace(/\w+/g,function(nodeName){return data.createElem(nodeName),data.frag.createElement(nodeName),'c("'+nodeName+'")'})+");return n}")(html5,data.frag)}function shivDocument(ownerDocument){ownerDocument||(ownerDocument=document);var data=getExpandoData(ownerDocument);return!html5.shivCSS||supportsHtml5Styles||data.hasCSS||(data.hasCSS=!!addStyleSheet(ownerDocument,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),supportsUnknownElements||shivMethods(ownerDocument,data),ownerDocument}var supportsHtml5Styles,supportsUnknownElements,options=window.html5||{},reSkip=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,saveClones=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,expando="_html5shiv",expanID=0,expandoData={};!function(){try{var a=document.createElement("a");a.innerHTML="<xyz></xyz>",supportsHtml5Styles="hidden"in a,supportsUnknownElements=1==a.childNodes.length||function(){document.createElement("a");var frag=document.createDocumentFragment();return"undefined"==typeof frag.cloneNode||"undefined"==typeof frag.createDocumentFragment||"undefined"==typeof frag.createElement}()}catch(e){supportsHtml5Styles=!0,supportsUnknownElements=!0}}();var html5={elements:options.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:options.shivCSS!==!1,supportsUnknownElements:supportsUnknownElements,shivMethods:options.shivMethods!==!1,type:"default",shivDocument:shivDocument,createElement:createElement,createDocumentFragment:createDocumentFragment};window.html5=html5,shivDocument(document)}(this,document),Modernizr._version=version,Modernizr._prefixes=prefixes,Modernizr._domPrefixes=domPrefixes,Modernizr._cssomPrefixes=cssomPrefixes,Modernizr.testProp=function(prop){return testProps([prop])},Modernizr.testAllProps=testPropsAll,Modernizr.testStyles=injectElementWithStyles,docElement.className=docElement.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(enableClasses?" js "+classes.join(" "):""),Modernizr}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var A,B,l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}};B=function(a){function b(a){var e,f,g,a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a};for(f=0;d>f;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;b>f;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var c,b=0;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var m,n,h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var l,o,k=b.createElement("script"),e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var j,e=b.createElement("link"),c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))},function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&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}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){function noop(){}var process=module.exports={};process.nextTick=function(){var canSetImmediate="undefined"!=typeof window&&window.setImmediate,canPost="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(canSetImmediate)return function(f){return window.setImmediate(f)};if(canPost){var queue=[];return window.addEventListener("message",function(ev){var source=ev.source;if((source===window||null===source)&&"process-tick"===ev.data&&(ev.stopPropagation(),queue.length>0)){var fn=queue.shift();fn()}},!0),function(fn){queue.push(fn),window.postMessage("process-tick","*")}}return function(fn){setTimeout(fn,0)}}(),process.title="browser",process.browser=!0,process.env={},process.argv=[],process.on=noop,process.addListener=noop,process.once=noop,process.off=noop,process.removeListener=noop,process.removeAllListeners=noop,process.emit=noop,process.binding=function(name){throw new Error("process.binding is not supported")},process.cwd=function(){return"/"},process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],2:[function(require,module,exports){"use strict";function Promise(fn){function handle(deferred){return null===state?void deferreds.push(deferred):void asap(function(){var cb=state?deferred.onFulfilled:deferred.onRejected;if(null===cb)return void(state?deferred.resolve:deferred.reject)(value);var ret;try{ret=cb(value)}catch(e){return void deferred.reject(e)}deferred.resolve(ret)})}function resolve(newValue){try{if(newValue===self)throw new TypeError("A promise cannot be resolved with itself.");if(newValue&&("object"==typeof newValue||"function"==typeof newValue)){var then=newValue.then;if("function"==typeof then)return void doResolve(then.bind(newValue),resolve,reject)}state=!0,value=newValue,finale()}catch(e){reject(e)}}function reject(newValue){state=!1,value=newValue,finale()}function finale(){for(var i=0,len=deferreds.length;len>i;i++)handle(deferreds[i]);deferreds=null}if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof fn)throw new TypeError("not a function");var state=null,value=null,deferreds=[],self=this;this.then=function(onFulfilled,onRejected){return new self.constructor(function(resolve,reject){handle(new Handler(onFulfilled,onRejected,resolve,reject))})},doResolve(fn,resolve,reject)}function Handler(onFulfilled,onRejected,resolve,reject){this.onFulfilled="function"==typeof onFulfilled?onFulfilled:null,this.onRejected="function"==typeof onRejected?onRejected:null,this.resolve=resolve,this.reject=reject}function doResolve(fn,onFulfilled,onRejected){var done=!1;try{fn(function(value){done||(done=!0,onFulfilled(value))},function(reason){done||(done=!0,onRejected(reason))})}catch(ex){if(done)return;done=!0,onRejected(ex)}}var asap=require("asap");module.exports=Promise},{asap:4}],3:[function(require,module,exports){"use strict";function ValuePromise(value){this.then=function(onFulfilled){return"function"!=typeof onFulfilled?this:new Promise(function(resolve,reject){asap(function(){try{resolve(onFulfilled(value))}catch(ex){reject(ex)}})})}}var Promise=require("./core.js"),asap=require("asap");module.exports=Promise,ValuePromise.prototype=Promise.prototype;var TRUE=new ValuePromise(!0),FALSE=new ValuePromise(!1),NULL=new ValuePromise(null),UNDEFINED=new ValuePromise(void 0),ZERO=new ValuePromise(0),EMPTYSTRING=new ValuePromise("");Promise.resolve=function(value){if(value instanceof Promise)return value;if(null===value)return NULL;if(void 0===value)return UNDEFINED;if(value===!0)return TRUE;if(value===!1)return FALSE;if(0===value)return ZERO;if(""===value)return EMPTYSTRING;if("object"==typeof value||"function"==typeof value)try{var then=value.then;if("function"==typeof then)return new Promise(then.bind(value))}catch(ex){return new Promise(function(resolve,reject){reject(ex)})}return new ValuePromise(value)},Promise.all=function(arr){var args=Array.prototype.slice.call(arr);return new Promise(function(resolve,reject){function res(i,val){try{if(val&&("object"==typeof val||"function"==typeof val)){var then=val.then;if("function"==typeof then)return void then.call(val,function(val){res(i,val)},reject)}args[i]=val,0===--remaining&&resolve(args)}catch(ex){reject(ex)}}if(0===args.length)return resolve([]);for(var remaining=args.length,i=0;i<args.length;i++)res(i,args[i])})},Promise.reject=function(value){return new Promise(function(resolve,reject){reject(value)})},Promise.race=function(values){return new Promise(function(resolve,reject){values.forEach(function(value){Promise.resolve(value).then(resolve,reject)})})},Promise.prototype["catch"]=function(onRejected){return this.then(null,onRejected)}},{"./core.js":2,asap:4}],4:[function(require,module,exports){(function(process){function flush(){for(;head.next;){head=head.next;var task=head.task;head.task=void 0;var domain=head.domain;domain&&(head.domain=void 0,domain.enter());try{task()}catch(e){if(isNodeJS)throw domain&&domain.exit(),setTimeout(flush,0),domain&&domain.enter(),e;setTimeout(function(){throw e},0)}domain&&domain.exit()}flushing=!1}function asap(task){tail=tail.next={task:task,domain:isNodeJS&&process.domain,next:null},flushing||(flushing=!0,requestFlush())}var head={task:void 0,next:null},tail=head,flushing=!1,requestFlush=void 0,isNodeJS=!1;if("undefined"!=typeof process&&process.nextTick)isNodeJS=!0,requestFlush=function(){process.nextTick(flush)};else if("function"==typeof setImmediate)requestFlush="undefined"!=typeof window?setImmediate.bind(window,flush):function(){setImmediate(flush)};else if("undefined"!=typeof MessageChannel){var channel=new MessageChannel;channel.port1.onmessage=flush,requestFlush=function(){channel.port2.postMessage(0)}}else requestFlush=function(){setTimeout(flush,0)};module.exports=asap}).call(this,require("_process"))},{_process:1}],5:[function(require,module,exports){"function"!=typeof Promise.prototype.done&&(Promise.prototype.done=function(onFulfilled,onRejected){var self=arguments.length?this.then.apply(this,arguments):this;self.then(null,function(err){setTimeout(function(){throw err},0)})})},{}],6:[function(require,module,exports){require("asap");"undefined"==typeof Promise&&(Promise=require("./lib/core.js"),require("./lib/es6-extensions.js")),require("./polyfill-done.js")},{"./lib/core.js":2,"./lib/es6-extensions.js":3,"./polyfill-done.js":5,asap:4}]},{},[6]),function(global,undefined){"use strict";function addFromSetImmediateArguments(args){return tasksByHandle[nextHandle]=partiallyApplied.apply(undefined,args),nextHandle++}function partiallyApplied(handler){var args=[].slice.call(arguments,1);return function(){"function"==typeof handler?handler.apply(undefined,args):new Function(""+handler)()}}function runIfPresent(handle){if(currentlyRunningATask)setTimeout(partiallyApplied(runIfPresent,handle),0);else{var task=tasksByHandle[handle];if(task){currentlyRunningATask=!0;try{task()}finally{clearImmediate(handle),currentlyRunningATask=!1}}}}function clearImmediate(handle){delete tasksByHandle[handle]}function installNextTickImplementation(){setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return process.nextTick(partiallyApplied(runIfPresent,handle)),handle}}function canUsePostMessage(){if(global.postMessage&&!global.importScripts){var postMessageIsAsynchronous=!0,oldOnMessage=global.onmessage;return global.onmessage=function(){postMessageIsAsynchronous=!1},global.postMessage("","*"),global.onmessage=oldOnMessage,postMessageIsAsynchronous}}function installPostMessageImplementation(){var messagePrefix="setImmediate$"+Math.random()+"$",onGlobalMessage=function(event){event.source===global&&"string"==typeof event.data&&0===event.data.indexOf(messagePrefix)&&runIfPresent(+event.data.slice(messagePrefix.length))};global.addEventListener?global.addEventListener("message",onGlobalMessage,!1):global.attachEvent("onmessage",onGlobalMessage),setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return global.postMessage(messagePrefix+handle,"*"),handle}}function installMessageChannelImplementation(){var channel=new MessageChannel;channel.port1.onmessage=function(event){var handle=event.data;runIfPresent(handle)},setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return channel.port2.postMessage(handle),handle}}function installReadyStateChangeImplementation(){var html=doc.documentElement;setImmediate=function(){var handle=addFromSetImmediateArguments(arguments),script=doc.createElement("script");return script.onreadystatechange=function(){runIfPresent(handle),script.onreadystatechange=null,html.removeChild(script),script=null},html.appendChild(script),handle}}function installSetTimeoutImplementation(){setImmediate=function(){var handle=addFromSetImmediateArguments(arguments);return setTimeout(partiallyApplied(runIfPresent,handle),0),handle}}if(!global.setImmediate){var setImmediate,nextHandle=1,tasksByHandle={},currentlyRunningATask=!1,doc=global.document,attachTo=Object.getPrototypeOf&&Object.getPrototypeOf(global);attachTo=attachTo&&attachTo.setTimeout?attachTo:global,"[object process]"==={}.toString.call(global.process)?installNextTickImplementation():canUsePostMessage()?installPostMessageImplementation():global.MessageChannel?installMessageChannelImplementation():doc&&"onreadystatechange"in doc.createElement("script")?installReadyStateChangeImplementation():installSetTimeoutImplementation(),attachTo.setImmediate=setImmediate,attachTo.clearImmediate=clearImmediate}}(new Function("return this")()),function(){function Viewport(){return this.PRE_IOS7_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.IOS7_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.DEFAULT_VIEWPORT="initial-scale=1, maximum-scale=1, user-scalable=no",this.ensureViewportElement(),this.platform={},this.platform.name=this.getPlatformName(),this.platform.version=this.getPlatformVersion(),this}Viewport.prototype.ensureViewportElement=function(){this.viewportElement=document.querySelector("meta[name=viewport]"),this.viewportElement||(this.viewportElement=document.createElement("meta"),this.viewportElement.name="viewport",document.head.appendChild(this.viewportElement))},Viewport.prototype.setup=function(){function isWebView(){return!!(window.cordova||window.phonegap||window.PhoneGap)}this.viewportElement&&"true"!=this.viewportElement.getAttribute("data-no-adjust")&&("ios"==this.platform.name?this.platform.version>=7&&isWebView()?this.viewportElement.setAttribute("content",this.IOS7_VIEWPORT):this.viewportElement.setAttribute("content",this.PRE_IOS7_VIEWPORT):this.viewportElement.setAttribute("content",this.DEFAULT_VIEWPORT))},Viewport.prototype.getPlatformName=function(){return navigator.userAgent.match(/Android/i)?"android":navigator.userAgent.match(/iPhone|iPad|iPod/i)?"ios":void 0},Viewport.prototype.getPlatformVersion=function(){var start=window.navigator.userAgent.indexOf("OS ");return window.Number(window.navigator.userAgent.substr(start+3,3).replace("_","."))},window.Viewport=Viewport}(),window.animit=function(){"use strict";var TIMEOUT_RATIO=1.4,Animit=function(element){if(!(this instanceof Animit))return new Animit(element);if(element instanceof HTMLElement)this.elements=[element];else{if("[object Array]"!==Object.prototype.toString.call(element))throw new Error("First argument must be an array or an instance of HTMLElement.");this.elements=element}this.transitionQueue=[],this.lastStyleAttributeDict=[]};Animit.prototype={transitionQueue:void 0,elements:void 0,play:function(callback){return"function"==typeof callback&&this.transitionQueue.push(function(done){callback(),done()}),this.startAnimation(),this},queue:function(transition,options){var queue=this.transitionQueue;if(transition&&options&&(options.css=transition,transition=new Animit.Transition(options)),transition instanceof Function||transition instanceof Animit.Transition||(transition=transition.css?new Animit.Transition(transition):new Animit.Transition({css:transition})),transition instanceof Function)queue.push(transition);else{if(!(transition instanceof Animit.Transition))throw new Error("Invalid arguments");queue.push(transition.build())}return this},wait:function(seconds){return seconds>0&&this.transitionQueue.push(function(done){setTimeout(done,1e3*seconds)}),this},saveStyle:function(){return this.transitionQueue.push(function(done){this.elements.forEach(function(element,index){for(var css=this.lastStyleAttributeDict[index]={},i=0;i<element.style.length;i++)css[element.style[i]]=element.style[element.style[i]]}.bind(this)),done()}.bind(this)),this},restoreStyle:function(options){function reset(){self.elements.forEach(function(element,index){element.style[transitionName]="none";var css=self.lastStyleAttributeDict[index];if(!css)throw new Error("restoreStyle(): The style is not saved. Invoke saveStyle() before.");self.lastStyleAttributeDict[index]=void 0;for(var i=0,name="";i<element.style.length;i++)name=element.style[i],"string"!=typeof css[element.style[i]]&&(css[element.style[i]]="");Object.keys(css).forEach(function(key){element.style[key]=css[key]})})}options=options||{};var self=this;if(options.transition&&!options.duration)throw new Error('"options.duration" is required when "options.transition" is enabled.');var transitionName=util.transitionPropertyName;if(options.transition||options.duration&&options.duration>0){var transitionValue=options.transition||"all "+options.duration+"s "+(options.timing||"linear");this.transitionQueue.push(function(done){var elements=this.elements,removeListeners=util.onceOnTransitionEnd(elements[0],function(){clearTimeout(timeoutId),clearTransition(),done()}),timeoutId=setTimeout(function(){removeListeners(),clearTransition(),done()},1e3*options.duration*TIMEOUT_RATIO);elements.forEach(function(element,index){var css=self.lastStyleAttributeDict[index];if(!css)throw new Error("restoreStyle(): The style is not saved. Invoke saveStyle() before.");self.lastStyleAttributeDict[index]=void 0;for(var name,i=0,len=element.style.length;len>i;i++)name=element.style[i],void 0===css[name]&&(css[name]="");element.style[transitionName]=transitionValue,Object.keys(css).forEach(function(key){key!==transitionName&&(element.style[key]=css[key])}),element.style[transitionName]=transitionValue});var clearTransition=function(){elements.forEach(function(element){element.style[transitionName]=""})}})}else this.transitionQueue.push(function(done){reset(),done()});return this},startAnimation:function(){return this._dequeueTransition(),this},_dequeueTransition:function(){var transition=this.transitionQueue.shift();if(this._currentTransition)throw new Error("Current transition exists.");this._currentTransition=transition;var self=this,called=!1,done=function(){if(called)throw new Error("Invalid state: This callback is called twice.");called=!0,self._currentTransition=void 0,self._dequeueTransition()};transition&&transition.call(this,done)}},Animit.runAll=function(){for(var i=0;i<arguments.length;i++)arguments[i].play()},Animit.Transition=function(options){this.options=options||{},this.options.duration=this.options.duration||0,this.options.timing=this.options.timing||"linear",this.options.css=this.options.css||{},this.options.property=this.options.property||"all"},Animit.Transition.prototype={build:function(){function createActualCssProps(css){var result={};return Object.keys(css).forEach(function(name){var value=css[name];if(util.hasCssProperty(name))return void(result[name]=value);var prefixed=util.vendorPrefix+util.capitalize(name);util.hasCssProperty(prefixed)?result[prefixed]=value:(result[prefixed]=value,result[name]=value)}),result}if(0===Object.keys(this.options.css).length)throw new Error("options.css is required.");var css=createActualCssProps(this.options.css);if(this.options.duration>0){var transitionValue=util.buildTransitionValue(this.options),self=this;return function(callback){var elements=this.elements,timeout=1e3*self.options.duration*TIMEOUT_RATIO,removeListeners=util.onceOnTransitionEnd(elements[0],function(){clearTimeout(timeoutId),callback()}),timeoutId=setTimeout(function(){removeListeners(),callback()},timeout);elements.forEach(function(element){element.style[util.transitionPropertyName]=transitionValue,Object.keys(css).forEach(function(name){element.style[name]=css[name]})})}}return this.options.duration<=0?function(callback){var elements=this.elements;elements.forEach(function(element){ element.style[util.transitionPropertyName]="",Object.keys(css).forEach(function(name){element.style[name]=css[name]})}),elements.length>0?util.forceLayoutAtOnce(elements,function(){util.batchAnimationFrame(callback)}):util.batchAnimationFrame(callback)}:void 0}};var util={capitalize:function(str){return str.charAt(0).toUpperCase()+str.slice(1)},buildTransitionValue:function(params){params.property=params.property||"all",params.duration=params.duration||.4,params.timing=params.timing||"linear";var props=params.property.split(/ +/);return props.map(function(prop){return prop+" "+params.duration+"s "+params.timing}).join(", ")},onceOnTransitionEnd:function(element,callback){if(!element)return function(){};var fn=function(event){element==event.target&&(event.stopPropagation(),removeListeners(),callback())},removeListeners=function(){util._transitionEndEvents.forEach(function(eventName){element.removeEventListener(eventName,fn,!1)})};return util._transitionEndEvents.forEach(function(eventName){element.addEventListener(eventName,fn,!1)}),removeListeners},_transitionEndEvents:function(){return"ontransitionend"in window?["transitionend"]:"onwebkittransitionend"in window?["webkitTransitionEnd"]:"webkit"===util.vendorPrefix||"o"===util.vendorPrefix||"moz"===util.vendorPrefix||"ms"===util.vendorPrefix?[util.vendorPrefix+"TransitionEnd","transitionend"]:[]}(),_cssPropertyDict:function(){var styles=window.getComputedStyle(document.documentElement,""),dict={},a="A".charCodeAt(0),z="z".charCodeAt(0);for(var key in styles)styles.hasOwnProperty(key)&&a<=key.charCodeAt(0)&&z>=key.charCodeAt(0)&&"cssText"!==key&&"parentText"!==key&&"length"!==key&&(dict[key]=!0);return dict}(),hasCssProperty:function(name){return name in util._cssPropertyDict},vendorPrefix:function(){var styles=window.getComputedStyle(document.documentElement,""),pre=(Array.prototype.slice.call(styles).join("").match(/-(moz|webkit|ms)-/)||""===styles.OLink&&["","o"])[1];return pre}(),forceLayoutAtOnce:function(elements,callback){this.batchImmediate(function(){elements.forEach(function(element){element.offsetHeight}),callback()})},batchImmediate:function(){var callbacks=[];return function(callback){0===callbacks.length&&setImmediate(function(){var concreateCallbacks=callbacks.slice(0);callbacks=[],concreateCallbacks.forEach(function(callback){callback()})}),callbacks.push(callback)}}(),batchAnimationFrame:function(){var callbacks=[],raf=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(callback){setTimeout(callback,1e3/60)};return function(callback){0===callbacks.length&&raf(function(){var concreateCallbacks=callbacks.slice(0);callbacks=[],concreateCallbacks.forEach(function(callback){callback()})}),callbacks.push(callback)}}()};return util.transitionPropertyName=function(){if(util.hasCssProperty("transition"))return"transition";if(util.hasCssProperty(util.vendorPrefix+"Transition"))return util.vendorPrefix+"Transition";throw new Exception("Invalid state")}(),Animit}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();window.DoorLock=function(){"use strict";var generateId=function(){var i=0;return function(){return i++}}(),DoorLock=function(){function DoorLock(options){_classCallCheck(this,DoorLock),options=options||{},this._lockList=[],this._waitList=[],this._log=options.log||function(){}}return _createClass(DoorLock,[{key:"lock",value:function(){var _this=this,unlock=function unlock(){_this._unlock(unlock)};return unlock.id=generateId(),this._lockList.push(unlock),this._log("lock: "+unlock.id),unlock}},{key:"_unlock",value:function(fn){var index=this._lockList.indexOf(fn);if(-1===index)throw new Error("This function is not registered in the lock list.");this._lockList.splice(index,1),this._log("unlock: "+fn.id),this._tryToFreeWaitList()}},{key:"_tryToFreeWaitList",value:function(){for(;!this.isLocked()&&this._waitList.length>0;)this._waitList.shift()()}},{key:"waitUnlock",value:function(callback){if(!(callback instanceof Function))throw new Error("The callback param must be a function.");this.isLocked()?this._waitList.push(callback):callback()}},{key:"isLocked",value:function(){return this._lockList.length>0}}]),DoorLock}();return DoorLock}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var util={_ready:!1,_domContentLoaded:!1,_onDOMContentLoaded:function(){util._domContentLoaded=!0,ons.isWebView()?window.document.addEventListener("deviceready",function(){util._ready=!0},!1):util._ready=!0},addBackButtonListener:function(fn){if(!this._domContentLoaded)throw new Error("This method is available after DOMContentLoaded");this._ready?window.document.addEventListener("backbutton",fn,!1):window.document.addEventListener("deviceready",function(){window.document.addEventListener("backbutton",fn,!1)})},removeBackButtonListener:function(fn){if(!this._domContentLoaded)throw new Error("This method is available after DOMContentLoaded");this._ready?window.document.removeEventListener("backbutton",fn,!1):window.document.addEventListener("deviceready",function(){window.document.removeEventListener("backbutton",fn,!1)})}};window.addEventListener("DOMContentLoaded",function(){return util._onDOMContentLoaded()},!1);var HandlerRepository={_store:{},_genId:function(){var i=0;return function(){return i++}}(),set:function(element,handler){element.dataset.deviceBackButtonHandlerId&&this.remove(element);var id=element.dataset.deviceBackButtonHandlerId=HandlerRepository._genId();this._store[id]=handler},remove:function(element){element.dataset.deviceBackButtonHandlerId&&(delete this._store[element.dataset.deviceBackButtonHandlerId],delete element.dataset.deviceBackButtonHandlerId)},get:function(element){if(!element.dataset.deviceBackButtonHandlerId)return void 0;var id=element.dataset.deviceBackButtonHandlerId;if(!this._store[id])throw new Error;return this._store[id]},has:function(element){var id=element.dataset.deviceBackButtonHandlerId;return!!this._store[id]}},DeviceBackButtonDispatcher=function(){function DeviceBackButtonDispatcher(){_classCallCheck(this,DeviceBackButtonDispatcher),this._isEnabled=!1,this._boundCallback=this._callback.bind(this)}return _createClass(DeviceBackButtonDispatcher,[{key:"enable",value:function(){this._isEnabled||(util.addBackButtonListener(this._boundCallback),this._isEnabled=!0)}},{key:"disable",value:function(){this._isEnabled&&(util.removeBackButtonListener(this._boundCallback),this._isEnabled=!1)}},{key:"fireDeviceBackButtonEvent",value:function(){var event=document.createEvent("Event");event.initEvent("backbutton",!0,!0),document.dispatchEvent(event)}},{key:"_callback",value:function(){this._dispatchDeviceBackButtonEvent()}},{key:"createHandler",value:function(element,callback){if(!(element instanceof HTMLElement))throw new Error("element must be an instance of HTMLElement");if(!(callback instanceof Function))throw new Error("callback must be an instance of Function");var handler={_callback:callback,_element:element,disable:function(){HandlerRepository.remove(element)},setListener:function(callback){this._callback=callback},enable:function(){HandlerRepository.set(element,this)},isEnabled:function(){return HandlerRepository.get(element)===this},destroy:function(){HandlerRepository.remove(element),this._callback=this._element=null}};return handler.enable(),handler}},{key:"_dispatchDeviceBackButtonEvent",value:function(){function createEvent(element){return{_element:element,callParentHandler:function(){for(var parent=this._element.parentNode;parent;){if(handler=HandlerRepository.get(parent))return handler._callback(createEvent(parent));parent=parent.parentNode}}}}var tree=this._captureTree(),element=this._findHandlerLeafElement(tree),handler=HandlerRepository.get(element);handler._callback(createEvent(element))}},{key:"_captureTree",value:function(){function createTree(element){return{element:element,children:Array.prototype.concat.apply([],arrayOf(element.children).map(function(childElement){if("none"===childElement.style.display)return[];if(0===childElement.children.length&&!HandlerRepository.has(childElement))return[];var result=createTree(childElement);return 0!==result.children.length||HandlerRepository.has(result.element)?[result]:[]}))}}function arrayOf(target){for(var result=[],i=0;i<target.length;i++)result.push(target[i]);return result}return createTree(document.body)}},{key:"_findHandlerLeafElement",value:function(tree){function find(_x){for(var _again=!0;_again;){var node=_x;if(_again=!1,0===node.children.length)return node.element;if(1!==node.children.length)return node.children.map(function(childNode){return childNode.element}).reduce(function(left,right){if(!left)return right;var leftZ=parseInt(window.getComputedStyle(left,"").zIndex,10),rightZ=parseInt(window.getComputedStyle(right,"").zIndex,10);if(!isNaN(leftZ)&&!isNaN(rightZ))return leftZ>rightZ?left:right;throw new Error("Capturing backbutton-handler is failure.")},null);_x=node.children[0],_again=!0}}return find(tree)}}]),DeviceBackButtonDispatcher}();ons._deviceBackButtonDispatcher=new DeviceBackButtonDispatcher,window.addEventListener("DOMContentLoaded",function(){ons._deviceBackButtonDispatcher.enable()})}(window.ons=window.ons||{}),function(ons){"use strict";function waitDeviceReady(){var unlockDeviceReady=ons._readyLock.lock();window.addEventListener("DOMContentLoaded",function(){ons.isWebView()?window.document.addEventListener("deviceready",unlockDeviceReady,!1):unlockDeviceReady()},!1)}ons._readyLock=new DoorLock,ons._config={autoStatusBarFill:!0,animationsDisabled:!1},waitDeviceReady(),ons.isReady=function(){return!ons._readyLock.isLocked()},ons.isWebView=function(){if("loading"===document.readyState||"uninitialized"==document.readyState)throw new Error("isWebView() method is available after dom contents loaded.");return!!(window.cordova||window.phonegap||window.PhoneGap)},ons.ready=function(callback){ons.isReady()?callback():ons._readyLock.waitUnlock(callback)},ons.setDefaultDeviceBackButtonListener=function(listener){ons._defaultDeviceBackButtonHandler.setListener(listener)},ons.disableDeviceBackButtonHandler=function(){ons._deviceBackButtonDispatcher.disable()},ons.enableDeviceBackButtonHandler=function(){ons._deviceBackButtonDispatcher.enable()},ons.enableAutoStatusBarFill=function(){if(ons.isReady())throw new Error("This method must be called before ons.isReady() is true.");ons._config.autoStatusBarFill=!0},ons.disableAutoStatusBarFill=function(){if(ons.isReady())throw new Error("This method must be called before ons.isReady() is true.");ons._config.autoStatusBarFill=!1},ons.disableAnimations=function(){ons._config.animationsDisabled=!0},ons.enableAnimations=function(){ons._config.animationsDisabled=!1},ons._createPopoverOriginal=function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");return ons._internal.getPageHTMLAsync(page).then(function(html){html=html.match(/<ons-popover/gi)?"<div>"+html+"</div>":"<ons-popover>"+html+"</ons-popover>";var div=ons._util.createElement("<div>"+html+"</div>"),popover=div.querySelector("ons-popover");return CustomElements.upgrade(popover),document.body.appendChild(popover),options.link instanceof Function&&options.link(popover),popover})},ons.createPopover=ons._createPopoverOriginal,ons._createDialogOriginal=function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");return ons._internal.getPageHTMLAsync(page).then(function(html){html=html.match(/<ons-dialog/gi)?"<div>"+html+"</div>":"<ons-dialog>"+html+"</ons-dialog>";var div=ons._util.createElement("<div>"+html+"</div>"),dialog=div.querySelector("ons-dialog");return CustomElements.upgrade(dialog),document.body.appendChild(dialog),options.link instanceof Function&&options.link(dialog),dialog})},ons.createDialog=ons._createDialogOriginal,ons._createAlertDialogOriginal=function(page,options){if(options=options||{},!page)throw new Error("Page url must be defined.");return ons._internal.getPageHTMLAsync(page).then(function(html){html=html.match(/<ons-alert-dialog/gi)?"<div>"+html+"</div>":"<ons-alert-dialog>"+html+"</ons-alert-dialog>";var div=ons._util.createElement("<div>"+html+"</div>"),alertDialog=div.querySelector("ons-alert-dialog");return CustomElements.upgrade(alertDialog),document.body.appendChild(alertDialog),options.link instanceof Function&&options.link(alertDialog),alertDialog})},ons.createAlertDialog=ons._createAlertDialogOriginal,ons._resolveLoadingPlaceholderOriginal=function(page,link){var elements=ons._util.arrayFrom(window.document.querySelectorAll("[ons-loading-placeholder]"));if(!(elements.length>0))throw new Error("No ons-loading-placeholder exists.");elements.filter(function(element){return!element.getAttribute("page")}).forEach(function(element){element.setAttribute("ons-loading-placeholder",page),ons._resolveLoadingPlaceholder(element,page,link)})},ons.resolveLoadingPlaceholder=ons._resolveLoadingPlaceholderOriginal,ons._setupLoadingPlaceHolders=function(){ons.ready(function(){var elements=ons._util.arrayFrom(window.document.querySelectorAll("[ons-loading-placeholder]"));elements.forEach(function(element){var page=element.getAttribute("ons-loading-placeholder");"string"==typeof page&&ons._resolveLoadingPlaceholder(element,page)})})},ons._resolveLoadingPlaceholder=function(element,page,link){link=link||function(element,done){done()},ons._internal.getPageHTMLAsync(page).then(function(html){for(;element.firstChild;)element.removeChild(element.firstChild);var contentElement=ons._util.createElement("<div>"+html+"</div>");contentElement.style.display="none",element.appendChild(contentElement),link(contentElement,function(){contentElement.style.display=""})})["catch"](function(error){throw new Error("Unabled to resolve placeholder: "+error)})}}(window.ons=window.ons||{}),function(ons){"use strict";var util=ons._util=ons._util||{};util.findChild=function(element,query){for(var match=query instanceof Function?query:"."===query.substr(0,1)?function(node){return node.classList.contains(query.substr(1))}:function(node){return node.nodeName.toLowerCase()===query},i=0;i<element.children.length;i++){var node=element.children[i];if(match(node))return node}return null},util.findParent=function(element,query){for(var match="."===query.substr(0,1)?function(node){return node.classList.contains(query.substr(1))}:function(node){return node.nodeName.toLowerCase()===query},parent=element.parentNode;;){if(!parent)return null;if(match(parent))return parent;parent=parent.parentNode}},util.isAttached=function(element){for(;document.documentElement!==element;){if(!element)return!1;element=element.parentNode}return!0},util.hasAnyComponentAsParent=function(element){for(;element&&document.documentElement!==element;)if(element=element.parentNode,element&&element.nodeName.toLowerCase().match(/(ons-navigator|ons-tabbar|ons-sliding-menu|ons-split-view)/))return!0;return!1},util.propagateAction=function(element,action){for(var i=0;i<element.childNodes.length;i++){var child=element.childNodes[i];child[action]?child[action]():ons._util.propagateAction(child,action)}},util.createElement=function(html){var wrapper=document.createElement("div");if(wrapper.innerHTML=html,wrapper.children.length>1)throw new Error('"html" must be one wrapper element.');return wrapper.children[0]},util.createFragment=function(html){var wrapper=document.createElement("div");wrapper.innerHTML=html;var fragment=document.createDocumentFragment();return wrapper.firstChild&&fragment.appendChild(wrapper.firstChild),fragment},util.extend=function(dst){for(var _len=arguments.length,args=Array(_len>1?_len-1:0),_key=1;_len>_key;_key++)args[_key-1]=arguments[_key];for(var i=0;i<args.length;i++)if(args[i])for(var keys=Object.keys(args[i]),j=0;j<keys.length;j++){var key=keys[j];dst[key]=args[i][key]}return dst},util.arrayFrom=function(arrayLike){for(var result=[],i=0;i<arrayLike.length;i++)result.push(arrayLike[i]);return result},util.parseJSONObjectSafely=function(jsonString){var failSafe=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];try{var result=JSON.parse(""+jsonString);if("object"==typeof result&&null!==result)return result}catch(e){return failSafe}return failSafe},util.triggerElementEvent=function(target,eventName){var detail=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],event=new CustomEvent(eventName,{bubbles:!0,cancelable:!0,detail:detail});return Object.keys(detail).forEach(function(key){event[key]=detail[key]}),target.dispatchEvent(event),event}}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var ModalAnimator=function(){function ModalAnimator(options){_classCallCheck(this,ModalAnimator),this.delay=0,this.duration=.2,options=options||{},this.timing=options.timing||this.timing,this.duration=void 0!==options.duration?options.duration:this.duration,this.delay=void 0!==options.delay?options.delay:this.delay}return _createClass(ModalAnimator,[{key:"show",value:function(modal,callback){callback()}},{key:"hide",value:function(modal,callback){callback()}}]),ModalAnimator}();ons._internal=ons._internal||{},ons._internal.ModalAnimator=ModalAnimator}(window.ons=window.ons||{});var _get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var SplitterAnimator=(ons._util,function(){function SplitterAnimator(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];_classCallCheck(this,SplitterAnimator),options=ons._util.extend({timing:"linear",duration:"0.3",delay:"0"},options||{}),this._timing=options.timing,this._duration=options.duration,this._delay=options.delay}return _createClass(SplitterAnimator,[{key:"layoutOnOpen",value:function(){}},{key:"layoutOnClose",value:function(){}},{key:"translate",value:function(distance){}},{key:"open",value:function(done){done()}},{key:"close",value:function(done){done()}},{key:"activate",value:function(contentElement,sideElement,maskElement){}},{key:"inactivate",value:function(){}},{key:"isActivated",value:function(){throw new Error}}]),SplitterAnimator}()),OverlaySplitterAnimator=function(_SplitterAnimator){function OverlaySplitterAnimator(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];_classCallCheck(this,OverlaySplitterAnimator),options=ons._util.extend({timing:"cubic-bezier(.1, .7, .1, 1)",duration:"0.3",delay:"0"},options||{}),_get(Object.getPrototypeOf(OverlaySplitterAnimator.prototype),"constructor",this).call(this,options)}return _inherits(OverlaySplitterAnimator,_SplitterAnimator),_createClass(OverlaySplitterAnimator,[{key:"isActivated",value:function(){return this._isActivated}},{key:"layoutOnClose",value:function(){animit(this._side).queue({transform:"translateX(0%)",width:this._side._getWidth()}).play(),this._mask.style.display="none"}},{key:"layoutOnOpen",value:function(){animit(this._side).queue({transform:"translate3d("+(this._side._isLeftSide()?"":"-")+"100%, 0px, 0px)",width:this._side._getWidth()}).play(),this._mask.style.display="block"}},{key:"activate",value:function(contentElement,sideElement,maskElement){this._isActivated=!0,this._content=contentElement,this._side=sideElement,this._mask=maskElement,this._setupLayout()}},{key:"inactivate",value:function(){this._isActivated=!1,this._clearLayout(),this._content=this._side=this._mask=null}},{key:"translate",value:function(distance){animit(this._side).queue({transform:"translate3d("+(this._side._isLeftSide()?"":"-")+distance+"px, 0px, 0px)"}).play()}},{key:"_clearLayout",value:function(){var side=this._side,mask=this._mask;side.style.zIndex="",side.style.right="",side.style.left="",side.style.transform=side.style.webkitTransform="",side.style.transition=side.style.webkitTransition="",side.style.width="",side.style.display="",mask.style.display="none"}},{key:"_setupLayout",value:function(){var side=this._side;side.style.zIndex=3,side.style.display="block",side._isLeftSide()?(side.style.left="auto",side.style.right="100%"):(side.style.left="100%",side.style.right="auto")}},{key:"open",value:function(done){var transform=this._side._isLeftSide()?"translate3d(100%, 0px, 0px)":"translate3d(-100%, 0px, 0px)";animit.runAll(animit(this._side).wait(this._delay).queue({transform:transform},{duration:this._duration,timing:this._timing}).queue(function(callback){callback(),done()}),animit(this._mask).wait(this._delay).queue({display:"block"}).queue({opacity:"1"},{duration:this._duration,timing:"linear"}))}},{key:"close",value:function(done){var _this=this;animit.runAll(animit(this._side).wait(this._delay).queue({transform:"translate3d(0px, 0px, 0px)"},{duration:this._duration,timing:this._timing}).queue(function(callback){_this._side.style.webkitTransition="",done(),callback()}),animit(this._mask).wait(this._delay).queue({opacity:"0"},{duration:this._duration,timing:"linear"}).queue({display:"none"}))}}]),OverlaySplitterAnimator}(SplitterAnimator);ons._internal=ons._internal||{},ons._internal.SplitterAnimator=SplitterAnimator,ons._internal.OverlaySplitterAnimator=OverlaySplitterAnimator}(window.ons=window.ons||{});var _get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var NavigatorTransitionAnimator=function(){function NavigatorTransitionAnimator(options){_classCallCheck(this,NavigatorTransitionAnimator),options=ons._util.extend({timing:"linear",duration:"0.4",delay:"0"},options||{}),this.timing=options.timing,this.duration=options.duration,this.delay=options.delay}return _createClass(NavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){callback()}},{key:"pop",value:function(enterPage,leavePage,callback){callback()}}]),NavigatorTransitionAnimator}(),NoneNavigatorTransitionAnimator=function(_NavigatorTransitionAnimator){function NoneNavigatorTransitionAnimator(options){_classCallCheck(this,NoneNavigatorTransitionAnimator),_get(Object.getPrototypeOf(NoneNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options)}return _inherits(NoneNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(NoneNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){callback()}},{key:"pop",value:function(enterPage,leavePage,callback){callback()}}]),NoneNavigatorTransitionAnimator}(NavigatorTransitionAnimator);ons._internal=ons._internal||{},ons._internal.NavigatorTransitionAnimator=NavigatorTransitionAnimator,ons._internal.NoneNavigatorTransitionAnimator=NoneNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var PopoverAnimator=function(){function PopoverAnimator(options){_classCallCheck(this,PopoverAnimator),options=ons._util.extend({timing:"cubic-bezier(.1, .7, .4, 1)",duration:.2,delay:0},options||{}),this.timing=options.timing,this.duration=options.duration,this.delay=options.delay}return _createClass(PopoverAnimator,[{key:"show",value:function(popover,callback){callback()}},{key:"hide",value:function(popover,callback){callback()}}]),PopoverAnimator}();ons._internal=ons._internal||{},ons._internal.PopoverAnimator=PopoverAnimator}(window.ons=window.ons||{}),function(ons){"use strict";ons.platform={_renderPlatform:null,select:function(platform){ons.platform._renderPlatform=platform.trim().toLowerCase()},isWebView:function(){return ons.isWebView()},isIOS:function(){return ons.platform._renderPlatform?"ios"===ons.platform._renderPlatform:/iPhone|iPad|iPod/i.test(navigator.userAgent)},isAndroid:function(){return ons.platform._renderPlatform?"android"===ons.platform._renderPlatform:/Android/i.test(navigator.userAgent)},isAndroidPhone:function(){return/Android/i.test(navigator.userAgent)&&/Mobile/i.test(navigator.userAgent)},isAndroidTablet:function(){return/Android/i.test(navigator.userAgent)&&!/Mobile/i.test(navigator.userAgent)},isWP:function(){return ons.platform._renderPlatform?"wp"===ons.platform._renderPlatform:/Windows Phone|IEMobile|WPDesktop/i.test(navigator.userAgent)},isIPhone:function(){return/iPhone/i.test(navigator.userAgent)},isIPad:function(){return/iPad/i.test(navigator.userAgent)},isIPod:function(){return/iPod/i.test(navigator.userAgent)},isBlackBerry:function(){return ons.platform._renderPlatform?"blackberry"===ons.platform._renderPlatform:/BlackBerry|RIM Tablet OS|BB10/i.test(navigator.userAgent)},isOpera:function(){return ons.platform._renderPlatform?"opera"===ons.platform._renderPlatform:!!window.opera||navigator.userAgent.indexOf(" OPR/")>=0},isFirefox:function(){return ons.platform._renderPlatform?"firefox"===ons.platform._renderPlatform:"undefined"!=typeof InstallTrigger},isSafari:function(){return ons.platform._renderPlatform?"safari"===ons.platform._renderPlatform:Object.prototype.toString.call(window.HTMLElement).indexOf("Constructor")>0},isChrome:function(){return ons.platform._renderPlatform?"chrome"===ons.platform._renderPlatform:!!window.chrome&&!(window.opera||navigator.userAgent.indexOf(" OPR/")>=0)},isIE:function(){return ons.platform._renderPlatform?"ie"===ons.platform._renderPlatform:!!document.documentMode},isIOS7above:function(){if(/iPhone|iPad|iPod/i.test(navigator.userAgent)){var ver=(navigator.userAgent.match(/\b[0-9]+_[0-9]+(?:_[0-9]+)?\b/)||[""])[0].replace(/_/g,".");return parseInt(ver.split(".")[0])>=7}return!1},getMobileOS:function(){return this.isAndroid()?"android":this.isIOS()?"ios":this.isWP()?"wp":"other"},getIOSDevice:function(){return this.isIPhone()?"iphone":this.isIPad()?"ipad":this.isIPod()?"ipod":"na"}}}(window.ons=window.ons||{});var _get=function(_x4,_x5,_x6){for(var _again=!0;_again;){var object=_x4,property=_x5,receiver=_x6;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x4=parent,_x5=property,_x6=receiver,_again=!0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var AlertDialogAnimator=function(){function AlertDialogAnimator(){var _ref=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref$timing=_ref.timing,timing=void 0===_ref$timing?"linear":_ref$timing,_ref$delay=_ref.delay,delay=void 0===_ref$delay?0:_ref$delay,_ref$duration=_ref.duration,duration=void 0===_ref$duration?.2:_ref$duration;_classCallCheck(this,AlertDialogAnimator),this.timing=timing,this.delay=delay,this.duration=duration}return _createClass(AlertDialogAnimator,[{key:"show",value:function(dialog,done){done()}},{key:"hide",value:function(dialog,done){done()}}]),AlertDialogAnimator}(),AndroidAlertDialogAnimator=function(_AlertDialogAnimator){function AndroidAlertDialogAnimator(){var _ref2=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref2$timing=_ref2.timing,timing=void 0===_ref2$timing?"cubic-bezier(.1, .7, .4, 1)":_ref2$timing,_ref2$duration=_ref2.duration,duration=void 0===_ref2$duration?.2:_ref2$duration,_ref2$delay=_ref2.delay,delay=void 0===_ref2$delay?0:_ref2$delay;_classCallCheck(this,AndroidAlertDialogAnimator),_get(Object.getPrototypeOf(AndroidAlertDialogAnimator.prototype),"constructor",this).call(this,{duration:duration,timing:timing,delay:delay})}return _inherits(AndroidAlertDialogAnimator,_AlertDialogAnimator),_createClass(AndroidAlertDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:this.duration, timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(0.9, 0.9, 1.0)",opacity:0},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),AndroidAlertDialogAnimator}(AlertDialogAnimator),IOSAlertDialogAnimator=function(_AlertDialogAnimator2){function IOSAlertDialogAnimator(){var _ref3=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref3$timing=_ref3.timing,timing=void 0===_ref3$timing?"cubic-bezier(.1, .7, .4, 1)":_ref3$timing,_ref3$duration=_ref3.duration,duration=void 0===_ref3$duration?.2:_ref3$duration,_ref3$delay=_ref3.delay,delay=void 0===_ref3$delay?0:_ref3$delay;_classCallCheck(this,IOSAlertDialogAnimator),_get(Object.getPrototypeOf(IOSAlertDialogAnimator.prototype),"constructor",this).call(this,{duration:duration,timing:timing,delay:delay})}return _inherits(IOSAlertDialogAnimator,_AlertDialogAnimator2),_createClass(IOSAlertDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.3, 1.3, 1.0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0) scale3d(1.0, 1.0, 1.0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{opacity:1},duration:0}).wait(this.delay).queue({css:{opacity:0},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),IOSAlertDialogAnimator}(AlertDialogAnimator);ons._internal=ons._internal||{},ons._internal.AlertDialogAnimator=AlertDialogAnimator,ons._internal.AndroidAlertDialogAnimator=AndroidAlertDialogAnimator,ons._internal.IOSAlertDialogAnimator=IOSAlertDialogAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var AnimatorFactory=function(){function AnimatorFactory(opts){if(_classCallCheck(this,AnimatorFactory),this._animators=opts.animators,this._baseClass=opts.baseClass,this._baseClassName=opts.baseClassName||opts.baseClass.name,this._animation=opts.defaultAnimation||"default",this._animationOptions=opts.defaultAnimationOptions||{},!this._animators[this._animation])throw new Error("No such animation: "+this._animation)}return _createClass(AnimatorFactory,[{key:"setAnimationOptions",value:function(options){this._animationOptions=options}},{key:"newAnimator",value:function(options,defaultAnimator){options=options||{};var animator=null;if(options.animation instanceof this._baseClass)return options.animation;var Animator=null;if("string"==typeof options.animation&&(Animator=this._animators[options.animation]),!Animator&&defaultAnimator)animator=defaultAnimator;else{Animator=Animator||this._animators[this._animation];var animationOpts=ons._util.extend({},this._animationOptions,options.animationOptions||{},ons._config.animationsDisabled?{duration:0,delay:0}:{});animator=new Animator(animationOpts)}if(!(animator instanceof this._baseClass))throw new Error('"animator" is not an instance of '+this._baseClassName+".");return animator}}],[{key:"parseAnimationOptionsString",value:function(jsonString){try{if("string"==typeof jsonString){var result=JSON.parse(jsonString);if("object"==typeof result&&null!==result)return result;console.error('"animation-options" attribute must be a JSON object string: '+jsonString)}return{}}catch(e){return console.error('"animation-options" attribute must be a JSON object string: '+jsonString),{}}}}]),AnimatorFactory}();ons._internal=ons._internal||{},ons._internal.AnimatorFactory=AnimatorFactory}(window.ons=window.ons||{});var _get=function(_x5,_x6,_x7){for(var _again=!0;_again;){var object=_x5,property=_x6,receiver=_x7;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x5=parent,_x6=property,_x7=receiver,_again=!0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var DialogAnimator=function(){function DialogAnimator(){var _ref=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref$timing=_ref.timing,timing=void 0===_ref$timing?"linear":_ref$timing,_ref$delay=_ref.delay,delay=void 0===_ref$delay?0:_ref$delay,_ref$duration=_ref.duration,duration=void 0===_ref$duration?.2:_ref$duration;_classCallCheck(this,DialogAnimator),this.timing=timing,this.delay=delay,this.duration=duration}return _createClass(DialogAnimator,[{key:"show",value:function(dialog,done){done()}},{key:"hide",value:function(dialog,done){done()}}]),DialogAnimator}(),AndroidDialogAnimator=function(_DialogAnimator){function AndroidDialogAnimator(){var _ref2=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref2$timing=_ref2.timing,timing=void 0===_ref2$timing?"ease-in-out":_ref2$timing,_ref2$delay=_ref2.delay,delay=void 0===_ref2$delay?0:_ref2$delay,_ref2$duration=_ref2.duration,duration=void 0===_ref2$duration?.3:_ref2$duration;_classCallCheck(this,AndroidDialogAnimator),_get(Object.getPrototypeOf(AndroidDialogAnimator.prototype),"constructor",this).call(this,{timing:timing,delay:delay,duration:duration})}return _inherits(AndroidDialogAnimator,_DialogAnimator),_createClass(AndroidDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -60%, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -60%, 0)",opacity:0},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),AndroidDialogAnimator}(DialogAnimator),IOSDialogAnimator=function(_DialogAnimator2){function IOSDialogAnimator(){var _ref3=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref3$timing=_ref3.timing,timing=void 0===_ref3$timing?"ease-in-out":_ref3$timing,_ref3$delay=_ref3.delay,delay=void 0===_ref3$delay?0:_ref3$delay,_ref3$duration=_ref3.duration,duration=void 0===_ref3$duration?.3:_ref3$duration;_classCallCheck(this,IOSDialogAnimator),_get(Object.getPrototypeOf(IOSDialogAnimator.prototype),"constructor",this).call(this,{timing:timing,delay:delay,duration:duration})}return _inherits(IOSDialogAnimator,_DialogAnimator2),_createClass(IOSDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, 300%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, -50%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3d(-50%, -50%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-50%, 300%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),IOSDialogAnimator}(DialogAnimator),SlideDialogAnimator=function(_DialogAnimator3){function SlideDialogAnimator(){var _ref4=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_ref4$timing=_ref4.timing,timing=void 0===_ref4$timing?"cubic-bezier(.1, .7, .4, 1)":_ref4$timing,_ref4$delay=_ref4.delay,delay=void 0===_ref4$delay?0:_ref4$delay,_ref4$duration=_ref4.duration,duration=void 0===_ref4$duration?.2:_ref4$duration;_classCallCheck(this,SlideDialogAnimator),_get(Object.getPrototypeOf(SlideDialogAnimator.prototype),"constructor",this).call(this,{timing:timing,delay:delay,duration:duration})}return _inherits(SlideDialogAnimator,_DialogAnimator3),_createClass(SlideDialogAnimator,[{key:"show",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3D(-50%, -350%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-50%, -50%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(dialog,callback){callback=callback?callback:function(){},animit.runAll(animit(dialog._mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(dialog._dialog).saveStyle().queue({css:{transform:"translate3D(-50%, -50%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-50%, -350%, 0)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),SlideDialogAnimator}(DialogAnimator);ons._internal=ons._internal||{},ons._internal.DialogAnimator=DialogAnimator,ons._internal.AndroidDialogAnimator=AndroidDialogAnimator,ons._internal.IOSDialogAnimator=IOSDialogAnimator,ons._internal.SlideDialogAnimator=SlideDialogAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(ons){"use strict";var ModalAnimator=ons._internal.ModalAnimator,FadeModalAnimator=function(_ModalAnimator){function FadeModalAnimator(options){_classCallCheck(this,FadeModalAnimator),options.timing=options.timing||"linear",options.duration=options.duration||"0.3",options.delay=options.delay||0,_get(Object.getPrototypeOf(FadeModalAnimator.prototype),"constructor",this).call(this,options)}return _inherits(FadeModalAnimator,_ModalAnimator),_createClass(FadeModalAnimator,[{key:"show",value:function(modal,callback){callback=callback?callback:function(){},animit(modal).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}).queue(function(done){callback(),done()}).play()}},{key:"hide",value:function(modal,callback){callback=callback?callback:function(){},animit(modal).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).queue(function(done){callback(),done()}).play()}}]),FadeModalAnimator}(ModalAnimator);ons._internal=ons._internal||{},ons._internal.FadeModalAnimator=FadeModalAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,FadeNavigatorTransitionAnimator=function(_NavigatorTransitionAnimator){function FadeNavigatorTransitionAnimator(options){_classCallCheck(this,FadeNavigatorTransitionAnimator),options=ons._util.extend({timing:"linear",duration:"0.4",delay:"0"},options||{}),_get(Object.getPrototypeOf(FadeNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options)}return _inherits(FadeNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(FadeNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){animit.runAll(animit([enterPage.element._getContentElement(),enterPage.element._getBackgroundElement()]).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}),animit(enterPage.element._getToolbarElement()).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle())}},{key:"pop",value:function(enterPage,leavePage,callback){animit.runAll(animit([leavePage.element._getContentElement(),leavePage.element._getBackgroundElement()]).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}).queue(function(done){callback(),done()}),animit(leavePage.element._getToolbarElement()).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}))}}]),FadeNavigatorTransitionAnimator}(NavigatorTransitionAnimator);ons._internal=ons._internal||{},ons._internal.FadeNavigatorTransitionAnimator=FadeNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(ons){"use strict";var PopoverAnimator=ons._internal.PopoverAnimator,FadePopoverAnimator=function(_PopoverAnimator){function FadePopoverAnimator(options){_classCallCheck(this,FadePopoverAnimator),_get(Object.getPrototypeOf(FadePopoverAnimator.prototype),"constructor",this).call(this,options)}return _inherits(FadePopoverAnimator,_PopoverAnimator),_createClass(FadePopoverAnimator,[{key:"show",value:function(popover,callback){var pop=popover.querySelector(".popover"),mask=popover.querySelector(".popover-mask");animit.runAll(animit(mask).queue({opacity:0}).wait(this.delay).queue({opacity:1},{duration:this.duration,timing:this.timing}),animit(pop).saveStyle().queue({transform:"scale3d(1.3, 1.3, 1.0)",opacity:0}).wait(this.delay).queue({transform:"scale3d(1.0, 1.0, 1.0)",opacity:1},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}},{key:"hide",value:function(popover,callback){var pop=popover.querySelector(".popover"),mask=popover.querySelector(".popover-mask");animit.runAll(animit(mask).queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}),animit(pop).saveStyle().queue({opacity:1}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){callback(),done()}))}}]),FadePopoverAnimator}(PopoverAnimator);ons._internal=ons._internal||{},ons._internal.FadePopoverAnimator=FadePopoverAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,IOSSlideNavigatorTransitionAnimator=(ons._util,function(_NavigatorTransitionAnimator){function IOSSlideNavigatorTransitionAnimator(options){_classCallCheck(this,IOSSlideNavigatorTransitionAnimator),options=ons._util.extend({duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)",delay:0},options||{}),_get(Object.getPrototypeOf(IOSSlideNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options),this.backgroundMask=ons._util.createElement('\n <div style="position: absolute; width: 100%; height: 100%;\n background-color: black; opacity: 0;"></div>\n ')}return _inherits(IOSSlideNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(IOSSlideNavigatorTransitionAnimator,[{key:"_decompose",value:function(page){CustomElements.upgrade(page.element);var toolbar=page.element._getToolbarElement();CustomElements.upgrade(toolbar);var left=toolbar._getToolbarLeftItemsElement(),right=toolbar._getToolbarRightItemsElement(),excludeBackButtonLabel=function(elements){for(var result=[],i=0;i<elements.length;i++)if("ons-back-button"===elements[i].nodeName.toLowerCase()){var iconElement=elements[i].querySelector(".ons-back-button__icon");iconElement&&result.push(iconElement)}else result.push(elements[i]);return result},other=[].concat(0===left.children.length?left:excludeBackButtonLabel(left.children)).concat(0===right.children.length?right:excludeBackButtonLabel(right.children)),pageLabels=[toolbar._getToolbarCenterItemsElement(),toolbar._getToolbarBackButtonLabelElement()];return{pageLabels:pageLabels,other:other,content:page.element._getContentElement(),background:page.element._getBackgroundElement(),toolbar:toolbar,bottomToolbar:page.element._getBottomToolbarElement()}}},{key:"_shouldAnimateToolbar",value:function(enterPage,leavePage){var bothPageHasToolbar=enterPage.element._canAnimateToolbar()&&leavePage.element._canAnimateToolbar(),noAndroidLikeToolbar=!enterPage.element._getToolbarElement().classList.contains("navigation-bar--android")&&!leavePage.element._getToolbarElement().classList.contains("navigation-bar--android");return bothPageHasToolbar&&noAndroidLikeToolbar}},{key:"push",value:function(enterPage,leavePage,callback){var _this=this;this.backgroundMask.remove(),leavePage.element.parentNode.insertBefore(this.backgroundMask,leavePage.element.nextSibling);var enterPageDecomposition=this._decompose(enterPage),leavePageDecomposition=this._decompose(leavePage),delta=function(){var rect=leavePage.element.getBoundingClientRect();return Math.round((rect.right-rect.left)/2*.6)}(),maskClear=animit(this.backgroundMask).saveStyle().queue({opacity:0,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:.1},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this.backgroundMask.remove(),done()}),shouldAnimateToolbar=this._shouldAnimateToolbar(enterPage,leavePage);shouldAnimateToolbar?(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit([enterPageDecomposition.content,enterPageDecomposition.bottomToolbar,enterPageDecomposition.background]).saveStyle().queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.toolbar).saveStyle().queue({css:{background:"none",backgroundColor:"rgba(0, 0, 0, 0)",borderColor:"rgba(0, 0, 0, 0)"},duration:0}).wait(this.delay+.3).restoreStyle({duration:.1,transition:"background-color 0.1s linear, border-color 0.1s linear"}),animit(enterPageDecomposition.pageLabels).saveStyle().queue({css:{transform:"translate3d("+delta+"px, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.other).saveStyle().queue({css:{opacity:0},duration:0}).wait(this.delay).queue({css:{opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit([leavePageDecomposition.content,leavePageDecomposition.bottomToolbar,leavePageDecomposition.background]).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-25%, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",callback(),done()}),animit(leavePageDecomposition.pageLabels).saveStyle().queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(-"+delta+"px, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePageDecomposition.other).saveStyle().queue({css:{opacity:1},duration:0}).wait(this.delay).queue({css:{opacity:0},duration:this.duration,timing:this.timing}).restoreStyle())):(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-25%, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",callback(),done()})))}},{key:"pop",value:function(enterPage,leavePage,done){var _this2=this;this.backgroundMask.remove(),enterPage.element.parentNode.insertBefore(this.backgroundMask,enterPage.element.nextSibling);var enterPageDecomposition=this._decompose(enterPage),leavePageDecomposition=this._decompose(leavePage),delta=function(){var rect=leavePage.element.getBoundingClientRect();return Math.round((rect.right-rect.left)/2*.6)}(),maskClear=animit(this.backgroundMask).saveStyle().queue({opacity:.1,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this2.backgroundMask.remove(),done()}),shouldAnimateToolbar=this._shouldAnimateToolbar(enterPage,leavePage);shouldAnimateToolbar?(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit([enterPageDecomposition.content,enterPageDecomposition.bottomToolbar,enterPageDecomposition.background]).saveStyle().queue({css:{transform:"translate3D(-25%, 0px, 0px)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.pageLabels).saveStyle().queue({css:{transform:"translate3d(-"+delta+"px, 0, 0)",opacity:0},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.toolbar).saveStyle().queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(enterPageDecomposition.other).saveStyle().queue({css:{opacity:0},duration:0}).wait(this.delay).queue({css:{opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit([leavePageDecomposition.content,leavePageDecomposition.bottomToolbar,leavePageDecomposition.background]).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:this.duration,timing:this.timing}).wait(0).queue(function(finish){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",done(),finish()}),animit(leavePageDecomposition.other).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d(0, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}),animit(leavePageDecomposition.toolbar).queue({css:{background:"none",backgroundColor:"rgba(0, 0, 0, 0)",borderColor:"rgba(0, 0, 0, 0)"},duration:0}),animit(leavePageDecomposition.pageLabels).queue({css:{transform:"translate3d(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3d("+delta+"px, 0, 0)",opacity:0},duration:this.duration,timing:this.timing}))):(enterPage.element.style.zIndex="auto",leavePage.element.style.zIndex="auto",animit.runAll(maskClear,animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(-25%, 0px, 0px)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:this.duration,timing:this.timing}).queue(function(finish){enterPage.element.style.zIndex="",leavePage.element.style.zIndex="",done(),finish()})))}}]),IOSSlideNavigatorTransitionAnimator}(NavigatorTransitionAnimator));ons._internal=ons._internal||{},ons._internal.IOSSlideNavigatorTransitionAnimator=IOSSlideNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var util=ons._util,LazyRepeatDelegate=function(){function LazyRepeatDelegate(){_classCallCheck(this,LazyRepeatDelegate)}return _createClass(LazyRepeatDelegate,[{key:"prepareItem",value:function(index,done){throw new Error("This is an abstract method.")}},{key:"countItems",value:function(){throw new Error("This is an abstract method.")}},{key:"updateItem",value:function(index,item){throw new Error("This is an abstract method.")}},{key:"calculateItemHeight",value:function(index){throw new Error("This is an abstract method.")}},{key:"destroyItem",value:function(index,item){throw new Error("This is an abstract method.")}},{key:"destroy",value:function(){throw new Error("This is an abstract method.")}}]),LazyRepeatDelegate}(),LazyRepeatProvider=function(){function LazyRepeatProvider(wrapperElement,templateElement,delegate){if(_classCallCheck(this,LazyRepeatProvider),!(delegate instanceof LazyRepeatDelegate))throw new Error('"delegate" parameter must be an instance of ons._internal.LazyRepeatDelegate.');if(!(templateElement instanceof Element))throw new Error('"templateElement" parameter must be an instance of Element.');if(!(wrapperElement instanceof Element))throw new Error('"wrapperElement" parameter must be an instance of Element.');if(this._templateElement=templateElement,this._wrapperElement=wrapperElement,this._delegate=delegate,this._pageContent=util.findParent(wrapperElement,".page__content"),!this._pageContent)throw new Error("ons-lazy-repeat must be a descendant of an <ons-page> element.");this._itemHeightSum=[], this._maxIndex=0,this._renderedItems={},this._addEventListeners(),this._onChange()}return _createClass(LazyRepeatProvider,[{key:"_countItems",value:function(){return this._delegate.countItems()}},{key:"_getItemHeight",value:function(i){return this._delegate.calculateItemHeight(i)}},{key:"_getTopOffset",value:function(){return"undefined"!=typeof this._wrapperElement&&null!==this._wrapperElement?this._wrapperElement.getBoundingClientRect().top:0}},{key:"_onChange",value:function(){this._render()}},{key:"_render",value:function(){for(var items=this._getItemsInView(),keep={},i=0,l=items.length;l>i;i++){var _item=items[i];this._renderElement(_item),keep[_item.index]=!0}for(var key in this._renderedItems)this._renderedItems.hasOwnProperty(key)&&!keep.hasOwnProperty(key)&&this._removeElement(key);this._wrapperElement.style.height=this._calculateListHeight()+"px"}},{key:"_calculateListHeight",value:function(){var indices=Object.keys(this._renderedItems).map(function(n){return parseInt(n)});return this._itemHeightSum[indices.pop()]||0}},{key:"_isRendered",value:function(index){return this._renderedItems.hasOwnProperty(index)}},{key:"_renderElement",value:function(_ref){var _this=this,index=_ref.index,top=_ref.top;if(this._isRendered(index)){var currentItem=this._renderedItems[index];this._delegate.updateItem(index,currentItem);var element=this._renderedItems[index].element;return void(element.style.top=this._wrapperElement.offsetTop+top+"px")}this._delegate.prepareItem(index,function(item){var element=item.element;element.style.position="absolute",element.style.top=top+"px",element.style.left="0px",element.style.right="0px",_this._wrapperElement.appendChild(element),_this._renderedItems[index]=item})}},{key:"_removeElement",value:function(index){if(this._isRendered(index)){var item=this._renderedItems[index];this._delegate.destroyItem(index,item),item.element.parentElement&&item.element.parentElement.removeChild(item.element),item=null,delete this._renderedItems[index]}}},{key:"_removeAllElements",value:function(){for(var key in this._renderedItems)this._renderedItems.hasOwnProperty(key)&&this._removeElement(key)}},{key:"_calculateStartIndex",value:function(current){for(var start=0,end=this._maxIndex;;){var middle=Math.floor((start+end)/2),value=current+this._itemHeightSum[middle];if(start>end)return 0;if(value>=0&&value-this._getItemHeight(middle)<0)return middle;isNaN(value)||value>=0?end=middle-1:start=middle+1}}},{key:"_recalculateItemHeightSum",value:function(){for(var sums=this._itemHeightSum,i=0,sum=0;i<Math.min(sums.length,this._countItems());i++)sum+=this._getItemHeight(i),sums[i]=sum}},{key:"_getItemsInView",value:function(){var topOffset=this._getTopOffset(),topPosition=topOffset,cnt=this._countItems();cnt!==this._itemCount&&(this._recalculateItemHeightSum(),this._maxIndex=cnt-1),this._itemCount=cnt;var startIndex=this._calculateStartIndex(topPosition);startIndex=Math.max(startIndex-30,0),startIndex>0&&(topPosition+=this._itemHeightSum[startIndex-1]);for(var items=[],i=startIndex;cnt>i&&topPosition<4*window.innerHeight;i++){var h=this._getItemHeight(i);i>=this._itemHeightSum.length&&(this._itemHeightSum=this._itemHeightSum.concat(new Array(100))),i>0?this._itemHeightSum[i]=this._itemHeightSum[i-1]+h:this._itemHeightSum[i]=h,this._maxIndex=Math.max(i,this._maxIndex),items.push({index:i,top:topPosition-topOffset}),topPosition+=h}return items}},{key:"_debounce",value:function(func,wait,immediate){var timeout;return function(){var context=this,args=arguments,later=function(){timeout=null,immediate||func.apply(context,args)},callNow=immediate&&!timeout;clearTimeout(timeout),timeout=setTimeout(later,wait),callNow&&func.apply(context,args)}}},{key:"_doubleFireOnTouchend",value:function(){this._render(),this._debounce(this._render.bind(this),100)}},{key:"_addEventListeners",value:function(){ons.platform.isIOS()?this._boundOnChange=this._debounce(this._onChange.bind(this),30):this._boundOnChange=this._onChange.bind(this),this._pageContent.addEventListener("scroll",this._boundOnChange,!0),ons.platform.isIOS()&&(this._pageContent.addEventListener("touchmove",this._boundOnChange,!0),this._pageContent.addEventListener("touchend",this._doubleFireOnTouchend,!0)),window.document.addEventListener("resize",this._boundOnChange,!0)}},{key:"_removeEventListeners",value:function(){this._pageContent.removeEventListener("scroll",this._boundOnChange,!0),ons.platform.isIOS()&&(this._pageContent.removeEventListener("touchmove",this._boundOnChange,!0),this._pageContent.removeEventListener("touchend",this._doubleFireOnTouchend,!0)),window.document.removeEventListener("resize",this._boundOnChange,!0)}},{key:"destroy",value:function(){this._delegate.destroy(),this._parentElement=this._templateElement=this._delegate=this._renderedItems=null,this._removeEventListeners()}}]),LazyRepeatProvider}();ons._internal=ons._internal||{},ons._internal.LazyRepeatProvider=LazyRepeatProvider,ons._internal.LazyRepeatDelegate=LazyRepeatDelegate}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,LiftNavigatorTransitionAnimator=(ons._util,function(_NavigatorTransitionAnimator){function LiftNavigatorTransitionAnimator(options){_classCallCheck(this,LiftNavigatorTransitionAnimator),options=ons._util.extend({duration:.4,timing:"cubic-bezier(.1, .7, .1, 1)",delay:0},options||{}),_get(Object.getPrototypeOf(LiftNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options),this.backgroundMask=ons._util.createElement('\n <div style="position: absolute; width: 100%; height: 100%;\n background-color: black;"></div>\n ')}return _inherits(LiftNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(LiftNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){var _this=this;this.backgroundMask.remove(),leavePage.element.parentNode.insertBefore(this.backgroundMask,leavePage.element);var maskClear=animit(this.backgroundMask).wait(.6).queue(function(done){_this.backgroundMask.remove(),done()});animit.runAll(maskClear,animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(0, 100%, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)"},duration:this.duration,timing:this.timing}).wait(.2).restoreStyle().queue(function(done){callback(),done()}),animit(leavePage.element).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, -10%, 0)",opacity:.9},duration:this.duration,timing:this.timing}))}},{key:"pop",value:function(enterPage,leavePage,callback){var _this2=this;this.backgroundMask.remove(),enterPage.element.parentNode.insertBefore(this.backgroundMask,enterPage.element),animit.runAll(animit(this.backgroundMask).wait(.4).queue(function(done){_this2.backgroundMask.remove(),done()}),animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(0, -10%, 0)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle().wait(.4).queue(function(done){callback(),done()}),animit(leavePage.element).queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 100%, 0)"},duration:this.duration,timing:this.timing}))}}]),LiftNavigatorTransitionAnimator}(NavigatorTransitionAnimator));ons._internal=ons._internal||{},ons._internal.LiftNavigatorTransitionAnimator=LiftNavigatorTransitionAnimator}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var ModifierUtil=function(){function ModifierUtil(){_classCallCheck(this,ModifierUtil)}return _createClass(ModifierUtil,null,[{key:"diff",value:function(last,current){function makeDict(modifier){var dict={};return ModifierUtil.split(modifier).forEach(function(token){return dict[token]=token}),dict}last=makeDict((""+last).trim()),current=makeDict((""+current).trim());var removed=Object.keys(last).reduce(function(result,token){return current[token]||result.push(token),result},[]),added=Object.keys(current).reduce(function(result,token){return last[token]||result.push(token),result},[]);return{added:added,removed:removed}}},{key:"applyDiffToClassList",value:function(diff,classList,template){diff.added.map(function(modifier){return template.replace(/\*/g,modifier)}).forEach(function(klass){return classList.add(klass)}),diff.removed.map(function(modifier){return template.replace(/\*/g,modifier)}).forEach(function(klass){return classList.remove(klass)})}},{key:"applyDiffToElement",value:function(diff,element,scheme){for(var selector in scheme)if(scheme.hasOwnProperty(selector))for(var targetElements=""===selector?[element]:element.querySelectorAll(selector),i=0;i<targetElements.length;i++)ModifierUtil.applyDiffToClassList(diff,targetElements[i].classList,scheme[selector])}},{key:"onModifierChanged",value:function(last,current,element,scheme){return ModifierUtil.applyDiffToElement(ModifierUtil.diff(last,current),element,scheme)}},{key:"initModifier",value:function(element,scheme){var modifier=element.getAttribute("modifier");"string"==typeof modifier&&ModifierUtil.applyDiffToElement({removed:[],added:ModifierUtil.split(modifier)},element,scheme)}},{key:"split",value:function(modifier){return"string"!=typeof modifier?[]:modifier.trim().split(/ +/).filter(function(token){return""!==token})}}]),ModifierUtil}();ons._internal=ons._internal||{},ons._internal.ModifierUtil=ModifierUtil}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var util=ons._util,NavigatorPage=function(){function NavigatorPage(params){var _this=this;_classCallCheck(this,NavigatorPage),this.page=params.page,this.name=params.page,this.element=params.element,this.options=params.options,this.navigator=params.navigator,this.initialContent=params.initialContent,this._blockEvents=function(event){(_this.navigator._isPopping||_this.navigator._isPushing)&&(event.preventDefault(),event.stopPropagation())},this._pointerEvents.forEach(function(event){return _this.element.addEventListener(event,_this._blockEvents)},!1)}return _createClass(NavigatorPage,[{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler}},{key:"getPageView",value:function(){if(!this._page&&(this._page=util.findParent("ons-page"),!this._page))throw new Error("Fail to fetch ons-page element.");return this._page}},{key:"destroy",value:function(){var _this2=this;this._pointerEvents.forEach(function(event){return _this2.element.removeEventListener(event,_this2._blockEvents)},!1),this.element._destroy();var index=this.navigator._pages.indexOf(this);-1!==index&&this.navigator._pages.splice(index,1),this.element=this._page=this.options=this.navigator=null}},{key:"_pointerEvents",get:function(){return["touchmove"]}}]),NavigatorPage}();window.ons._internal.NavigatorPage=NavigatorPage}(window.ons=window.ons||{}),function(ons){"use strict";ons._internal=ons._internal||{},ons._internal.nullElement=document.createElement("div"),ons._internal.isEnabledAutoStatusBarFill=function(){return!!ons._config.autoStatusBarFill},ons._internal.normalizePageHTML=function(html){return html=(""+html).trim(),html.match(/^<ons-page/)||(html="<ons-page _muted>"+html+"</ons-page>"),html},ons._internal.waitDOMContentLoaded=function(callback){"loading"===document.readyState||"uninitialized"==document.readyState?window.document.addEventListener("DOMContentLoaded",callback):setImmediate(callback)},ons._internal.shouldFillStatusBar=function(element){if(ons._internal.isEnabledAutoStatusBarFill()&&ons.platform.isWebView()&&ons.platform.isIOS7above()){if(!(element instanceof HTMLElement))throw new Error("element must be an instance of HTMLElement");for(;;){if(element.hasAttribute("no-status-bar-fill"))return!1;if(element=element.parentNode,!element||!element.hasAttribute)return!0}}return!1},ons._internal.templateStore={_storage:{},get:function(key){return ons._internal.templateStore._storage[key]||null},set:function(key,template){ons._internal.templateStore._storage[key]=template}},document.addEventListener("_templateloaded",function(e){"ons-template"===e.target.nodeName.toLowerCase()&&ons._internal.templateStore.set(e.templateId,e.template)},!1),document.addEventListener("DOMContentLoaded",function(){function register(query){for(var templates=document.querySelectorAll(query),i=0;i<templates.length;i++)ons._internal.templateStore.set(templates[i].getAttribute("id"),templates[i].textContent)}register('script[type="text/ons-template"]'),register('script[type="text/template"]'),register('script[type="text/ng-template"]')},!1),ons._internal.getTemplateHTMLAsync=function(page){return new Promise(function(resolve,reject){setImmediate(function(){var cache=ons._internal.templateStore.get(page);if(cache){var html="string"==typeof cache?cache:cache[1];resolve(html)}else!function(){var xhr=new XMLHttpRequest;xhr.open("GET",page,!0),xhr.onload=function(response){var html=xhr.responseText;xhr.status>=400&&xhr.status<600?reject(html):resolve(html)},xhr.onerror=function(){throw new Error("The page is not found: "+page)},xhr.send(null)}()})})},ons._internal.getPageHTMLAsync=function(page){var pages=ons.pageAttributeExpression.evaluate(page),getPage=function getPage(page){return"string"!=typeof page?Promise.reject("Must specify a page."):ons._internal.getTemplateHTMLAsync(page).then(function(html){return ons._internal.normalizePageHTML(html)},function(error){return 0===pages.length?Promise.reject(error):getPage(pages.shift())}).then(function(html){return ons._internal.normalizePageHTML(html)})};return getPage(pages.shift())}}(window.ons=window.ons||{}),function(ons){"use strict";var util=ons._util;ons.notification={},ons.notification._createAlertDialog=function(title,message,buttonLabels,primaryButtonIndex,modifier,animation,_callback,messageIsHTML,cancelable,promptDialog,autofocus,placeholder,defaultValue,submitOnEnter,compile){compile=compile||function(object){return object};var dialogElement=util.createElement("<ons-alert-dialog></ons-alert-dialog>"),titleElement=util.createElement('<div class="alert-dialog-title"></div>'),messageElement=util.createElement('<div class="alert-dialog-content"></div>'),footerElement=util.createElement('<div class="alert-dialog-footer"></div>'),inputElement=void 0;dialogElement.setAttribute("animation",animation),messageIsHTML?messageElement.innerHTML=message:messageElement.textContent=message,dialogElement.appendChild(titleElement),dialogElement.appendChild(messageElement),promptDialog&&(inputElement=util.createElement('<input class="text-input" type="text"></input>'),modifier&&inputElement.classList.add("text-input--"+modifier),inputElement.setAttribute("placeholder",placeholder),inputElement.value=defaultValue,inputElement.style.width="100%",inputElement.style.marginTop="10px",messageElement.appendChild(inputElement),submitOnEnter&&inputElement.addEventListener("keypress",function(event){13===event.keyCode&&dialogElement.hide({callback:function(){_callback(inputElement.value),dialogElement.destroy(),dialogElement=null}})},!1)),dialogElement.appendChild(footerElement),document.body.appendChild(dialogElement),compile(dialogElement),buttonLabels.length<=2&&footerElement.classList.add("alert-dialog-footer--one");for(var createButton=function(i){var buttonElement=util.createElement('<button class="alert-dialog-button"></button>');buttonElement.textContent=buttonLabels[i],i==primaryButtonIndex&&buttonElement.classList.add("alert-dialog-button--primal"),buttonLabels.length<=2&&buttonElement.classList.add("alert-dialog-button--one");var onClick=function onClick(){buttonElement.removeEventListener("click",onClick,!1),dialogElement.hide({callback:function(){_callback(promptDialog?inputElement.value:i),dialogElement.destroy(),dialogElement=inputElement=buttonElement=null}})};buttonElement.addEventListener("click",onClick,!1),footerElement.appendChild(buttonElement)},i=0;i<buttonLabels.length;i++)createButton(i);return cancelable&&(dialogElement.setCancelable(cancelable),dialogElement.addEventListener("cancel",function(){_callback(promptDialog?null:-1),setTimeout(function(){dialogElement.destroy(),dialogElement=null,inputElement=null})},!1)),dialogElement.show({callback:function(){inputElement&&promptDialog&&autofocus&&inputElement.focus()}}),titleElement=messageElement=footerElement=null,modifier&&dialogElement.setAttribute("modifier",modifier),Promise.resolve(dialogElement)},ons.notification._alertOriginal=function(options){var defaults={buttonLabel:"OK",animation:"default",title:"Alert",callback:function(){}};if(options=util.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Alert dialog must contain a message.");return ons.notification._createAlertDialog(options.title,options.message||options.messageHTML,[options.buttonLabel],0,options.modifier,options.animation,options.callback,options.message?!1:!0,!1,!1,!1,"","",!1,options.compile)},ons.notification.alert=ons.notification._alertOriginal,ons.notification._confirmOriginal=function(options){var defaults={buttonLabels:["Cancel","OK"],primaryButtonIndex:1,animation:"default",title:"Confirm",callback:function(){},cancelable:!1};if(options=util.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Confirm dialog must contain a message.");return ons.notification._createAlertDialog(options.title,options.message||options.messageHTML,options.buttonLabels,options.primaryButtonIndex,options.modifier,options.animation,options.callback,options.message?!1:!0,options.cancelable,!1,!1,"","",!1,options.compile)},ons.notification.confirm=ons.notification._confirmOriginal,ons.notification._promptOriginal=function(options){var defaults={buttonLabel:"OK",animation:"default",title:"Alert",defaultValue:"",placeholder:"",callback:function(){},cancelable:!1,autofocus:!0,submitOnEnter:!0};if(options=util.extend({},defaults,options),!options.message&&!options.messageHTML)throw new Error("Prompt dialog must contain a message.");return ons.notification._createAlertDialog(options.title,options.message||options.messageHTML,[options.buttonLabel],0,options.modifier,options.animation,options.callback,options.message?!1:!0,options.cancelable,!0,options.autofocus,options.placeholder,options.defaultValue,options.submitOnEnter,options.compile)},ons.notification.prompt=ons.notification._promptOriginal}(window.ons=window.ons||{}),function(ons){var create=function(){var obj={_isPortrait:!1,isPortrait:function(){return this._isPortrait()},isLandscape:function(){return!this.isPortrait()},_init:function(){return document.addEventListener("DOMContentLoaded",this._onDOMContentLoaded.bind(this),!1),"orientation"in window?window.addEventListener("orientationchange",this._onOrientationChange.bind(this),!1):window.addEventListener("resize",this._onResize.bind(this),!1),this._isPortrait=function(){return window.innerHeight>window.innerWidth},this},_onDOMContentLoaded:function(){this._installIsPortraitImplementation(),this.emit("change",{isPortrait:this.isPortrait()})},_installIsPortraitImplementation:function(){var isPortrait=window.innerWidth<window.innerHeight;"orientation"in window?window.orientation%180===0?this._isPortrait=function(){return 0===Math.abs(window.orientation%180)?isPortrait:!isPortrait}:this._isPortrait=function(){return 90===Math.abs(window.orientation%180)?isPortrait:!isPortrait}:this._isPortrait=function(){return window.innerHeight>window.innerWidth}},_onOrientationChange:function(){var _this=this,isPortrait=this._isPortrait(),nIter=0,interval=setInterval(function(){nIter++;var w=window.innerWidth,h=window.innerHeight;isPortrait&&h>=w||!isPortrait&&w>=h?(_this.emit("change",{isPortrait:isPortrait}),clearInterval(interval)):50===nIter&&(_this.emit("change",{isPortrait:isPortrait}),clearInterval(interval))},20)},_onResize:function(){this.emit("change",{isPortrait:this.isPortrait()})}};return MicroEvent.mixin(obj),obj};ons.orientation=create()._init()}(window.ons=window.ons||{}),function(ons){ons.pageAttributeExpression={_variables:{},defineVariable:function(name,value){var overwrite=arguments.length<=2||void 0===arguments[2]?!1:arguments[2];if("string"!=typeof name)throw new Error("Variable name must be a string.");if("string"!=typeof value&&"function"!=typeof value)throw new Error("Variable value must be a string or a function.");if(this._variables.hasOwnProperty(name)&&!overwrite)throw new Error('"'+name+'" is already defined.');this._variables[name]=value},getVariable:function(name){return this._variables.hasOwnProperty(name)?this._variables[name]:null},removeVariable:function(name){delete this._variables[name]},getAllVariables:function(){return this._variables},_parsePart:function(part){var c=void 0,inInterpolation=!1,currentIndex=0,tokens=[];if(0===part.length)throw new Error("Unable to parse empty string.");for(var i=0;i<part.length;i++)if(c=part.charAt(i),"$"===c&&"{"===part.charAt(i+1)){if(inInterpolation)throw new Error("Nested interpolation not supported.");var token=part.substring(currentIndex,i);token.length>0&&tokens.push(part.substring(currentIndex,i)),currentIndex=i,inInterpolation=!0}else if("}"===c){if(!inInterpolation)throw new Error("} must be preceeded by ${");var token=part.substring(currentIndex,i+1);token.length>0&&tokens.push(part.substring(currentIndex,i+1)),currentIndex=i+1,inInterpolation=!1}if(inInterpolation)throw new Error("Unterminated interpolation.");return tokens.push(part.substring(currentIndex,part.length)),tokens},_replaceToken:function(token){var re=/^\${(.*?)}$/,match=token.match(re);if(match){var _name=match[1].trim(),variable=this.getVariable(_name);if(null===variable)throw new Error('Variable "'+_name+'" does not exist.');if("string"==typeof variable)return variable;var rv=variable();if("string"!=typeof rv)throw new Error("Must return a string.");return rv}return token},_replaceTokens:function(tokens){return tokens.map(this._replaceToken.bind(this))},_parseExpression:function(expression){return expression.split(",").map(function(part){return part.trim()}).map(this._parsePart.bind(this)).map(this._replaceTokens.bind(this)).map(function(part){return part.join("")})},evaluate:function(expression){return expression?this._parseExpression(expression):[]}},ons.pageAttributeExpression.defineVariable("mobileOS",ons.platform.getMobileOS()),ons.pageAttributeExpression.defineVariable("iOSDevice",ons.platform.getIOSDevice()),ons.pageAttributeExpression.defineVariable("runtime",function(){return ons.platform.isWebView()?"cordova":"browser"})}(window.ons=window.ons||{}),function(ons){"use strict";ons.softwareKeyboard=new MicroEvent,ons.softwareKeyboard._visible=!1;var onShow=function(){ons.softwareKeyboard._visible=!0,ons.softwareKeyboard.emit("show")},onHide=function(){ons.softwareKeyboard._visible=!1,ons.softwareKeyboard.emit("hide")},bindEvents=function(){return"undefined"!=typeof Keyboard?(Keyboard.onshow=onShow,Keyboard.onhide=onHide,ons.softwareKeyboard.emit("init",{visible:Keyboard.isVisible}),!0):"undefined"!=typeof cordova.plugins&&"undefined"!=typeof cordova.plugins.Keyboard?(window.addEventListener("native.keyboardshow",onShow),window.addEventListener("native.keyboardhide",onHide),ons.softwareKeyboard.emit("init",{visible:cordova.plugins.Keyboard.isVisible}),!0):!1},noPluginError=function(){console.warn("ons-keyboard: Cordova Keyboard plugin is not present.")};document.addEventListener("deviceready",function(){bindEvents()||((document.querySelector("[ons-keyboard-active]")||document.querySelector("[ons-keyboard-inactive]"))&&noPluginError(),ons.softwareKeyboard.on=noPluginError)})}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(ons){"use strict";var NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,SimpleSlideNavigatorTransitionAnimator=(ons._util,function(_NavigatorTransitionAnimator){function SimpleSlideNavigatorTransitionAnimator(options){_classCallCheck(this,SimpleSlideNavigatorTransitionAnimator),options=ons._util.extend({duration:.3,timing:"cubic-bezier(.1, .7, .4, 1)",delay:0},options||{}),_get(Object.getPrototypeOf(SimpleSlideNavigatorTransitionAnimator.prototype),"constructor",this).call(this,options),this.backgroundMask=ons._util.createElement('\n <div style="position: absolute; width: 100%; height: 100%; z-index: 2;\n background-color: black; opacity: 0;"></div>\n '),this.blackMaskOpacity=.4}return _inherits(SimpleSlideNavigatorTransitionAnimator,_NavigatorTransitionAnimator),_createClass(SimpleSlideNavigatorTransitionAnimator,[{key:"push",value:function(enterPage,leavePage,callback){var _this=this;this.backgroundMask.remove(),leavePage.element.parentElement.insertBefore(this.backgroundMask,leavePage.element.nextSibling),animit.runAll(animit(this.backgroundMask).saveStyle().queue({opacity:0,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:this.blackMaskOpacity},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this.backgroundMask.remove(),done()}),animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(100%, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0, 0, 0)"},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).saveStyle().queue({css:{transform:"translate3D(0, 0, 0)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(-45%, 0px, 0px)"},duration:this.duration,timing:this.timing}).restoreStyle().wait(.2).queue(function(done){callback(),done()}))}},{key:"pop",value:function(enterPage,leavePage,done){var _this2=this;this.backgroundMask.remove(),enterPage.element.parentNode.insertBefore(this.backgroundMask,enterPage.element.nextSibling),animit.runAll(animit(this.backgroundMask).saveStyle().queue({opacity:this.blackMaskOpacity,transform:"translate3d(0, 0, 0)"}).wait(this.delay).queue({opacity:0},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(done){_this2.backgroundMask.remove(),done()}),animit(enterPage.element).saveStyle().queue({css:{transform:"translate3D(-45%, 0px, 0px)",opacity:.9},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(0px, 0px, 0px)",opacity:1},duration:this.duration,timing:this.timing}).restoreStyle(),animit(leavePage.element).queue({css:{transform:"translate3D(0px, 0px, 0px)"},duration:0}).wait(this.delay).queue({css:{transform:"translate3D(100%, 0px, 0px)"},duration:this.duration,timing:this.timing}).wait(.2).queue(function(finish){done(),finish()}))}}]),SimpleSlideNavigatorTransitionAnimator}(NavigatorTransitionAnimator));ons._internal=ons._internal||{},ons._internal.SimpleSlideNavigatorTransitionAnimator=SimpleSlideNavigatorTransitionAnimator}(window.ons=window.ons||{});var _get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(ons){"use strict";var TabbarAnimator=function(){function TabbarAnimator(options){_classCallCheck(this,TabbarAnimator),options=options||{},this.timing=options.timing||"linear",this.duration=void 0!==options.duration?options.duration:"0.4",this.delay=void 0!==options.delay?options.delay:"0"}return _createClass(TabbarAnimator,[{key:"apply",value:function(enterPage,leavePage,enterPageIndex,leavePageIndex,done){throw new Error("This method must be implemented.")}}]),TabbarAnimator}(),TabbarNoneAnimator=function(_TabbarAnimator){function TabbarNoneAnimator(){_classCallCheck(this,TabbarNoneAnimator),_get(Object.getPrototypeOf(TabbarNoneAnimator.prototype),"constructor",this).apply(this,arguments)}return _inherits(TabbarNoneAnimator,_TabbarAnimator),_createClass(TabbarNoneAnimator,[{key:"apply",value:function(enterPage,leavePage,enterIndex,leaveIndex,done){done()}}]),TabbarNoneAnimator}(TabbarAnimator),TabbarFadeAnimator=function(_TabbarAnimator2){function TabbarFadeAnimator(options){_classCallCheck(this,TabbarFadeAnimator),options.timing=void 0!==options.timing?options.timing:"linear",options.duration=void 0!==options.duration?options.duration:"0.4",options.delay=void 0!==options.delay?options.delay:"0",_get(Object.getPrototypeOf(TabbarFadeAnimator.prototype),"constructor",this).call(this,options)}return _inherits(TabbarFadeAnimator,_TabbarAnimator2), _createClass(TabbarFadeAnimator,[{key:"apply",value:function(enterPage,leavePage,enterPageIndex,leavePageIndex,done){animit.runAll(animit(enterPage).saveStyle().queue({transform:"translate3D(0, 0, 0)",opacity:0}).wait(this.delay).queue({transform:"translate3D(0, 0, 0)",opacity:1},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(callback){done(),callback()}),animit(leavePage).queue({transform:"translate3D(0, 0, 0)",opacity:1}).wait(this.delay).queue({transform:"translate3D(0, 0, 0)",opacity:0},{duration:this.duration,timing:this.timing}))}}]),TabbarFadeAnimator}(TabbarAnimator),TabbarSlideAnimator=function(_TabbarAnimator3){function TabbarSlideAnimator(options){_classCallCheck(this,TabbarSlideAnimator),options.timing=void 0!==options.timing?options.timing:"ease-in",options.duration=void 0!==options.duration?options.duration:"0.15",options.delay=void 0!==options.delay?options.delay:"0",_get(Object.getPrototypeOf(TabbarSlideAnimator.prototype),"constructor",this).call(this,options)}return _inherits(TabbarSlideAnimator,_TabbarAnimator3),_createClass(TabbarSlideAnimator,[{key:"apply",value:function(enterPage,leavePage,enterIndex,leaveIndex,done){var sgn=enterIndex>leaveIndex;animit.runAll(animit(enterPage).saveStyle().queue({transform:"translate3D("+(sgn?"":"-")+"100%, 0, 0)"}).wait(this.delay).queue({transform:"translate3D(0, 0, 0)"},{duration:this.duration,timing:this.timing}).restoreStyle().queue(function(callback){done(),callback()}),animit(leavePage).queue({transform:"translate3D(0, 0, 0)"}).wait(this.delay).queue({transform:"translate3D("+(sgn?"-":"")+"100%, 0, 0)"},{duration:this.duration,timing:this.timing}))}}]),TabbarSlideAnimator}(TabbarAnimator);ons._internal=ons._internal||{},ons._internal.TabbarAnimator=TabbarAnimator,ons._internal.TabbarFadeAnimator=TabbarFadeAnimator,ons._internal.TabbarNoneAnimator=TabbarNoneAnimator,ons._internal.TabbarSlideAnimator=TabbarSlideAnimator}(window.ons=window.ons||{}),function(window){"use strict";function setup(){GestureDetector.READY||(Event.determineEventTypes(),Utils.each(GestureDetector.gestures,function(gesture){Detection.register(gesture)}),Event.onTouch(GestureDetector.DOCUMENT,EVENT_MOVE,Detection.detect),Event.onTouch(GestureDetector.DOCUMENT,EVENT_END,Detection.detect),GestureDetector.READY=!0)}var GestureDetector=function GestureDetector(element,options){return new GestureDetector.Instance(element,options||{})};GestureDetector.defaults={behavior:{userSelect:"none",touchAction:"pan-y",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}},GestureDetector.DOCUMENT=document,GestureDetector.HAS_POINTEREVENTS=navigator.pointerEnabled||navigator.msPointerEnabled,GestureDetector.HAS_TOUCHEVENTS="ontouchstart"in window,GestureDetector.IS_MOBILE=/mobile|tablet|ip(ad|hone|od)|android|silk/i.test(navigator.userAgent),GestureDetector.NO_MOUSEEVENTS=GestureDetector.HAS_TOUCHEVENTS&&GestureDetector.IS_MOBILE||GestureDetector.HAS_POINTEREVENTS,GestureDetector.CALCULATE_INTERVAL=25;var EVENT_TYPES={},DIRECTION_DOWN=GestureDetector.DIRECTION_DOWN="down",DIRECTION_LEFT=GestureDetector.DIRECTION_LEFT="left",DIRECTION_UP=GestureDetector.DIRECTION_UP="up",DIRECTION_RIGHT=GestureDetector.DIRECTION_RIGHT="right",POINTER_MOUSE=GestureDetector.POINTER_MOUSE="mouse",POINTER_TOUCH=GestureDetector.POINTER_TOUCH="touch",POINTER_PEN=GestureDetector.POINTER_PEN="pen",EVENT_START=GestureDetector.EVENT_START="start",EVENT_MOVE=GestureDetector.EVENT_MOVE="move",EVENT_END=GestureDetector.EVENT_END="end",EVENT_RELEASE=GestureDetector.EVENT_RELEASE="release",EVENT_TOUCH=GestureDetector.EVENT_TOUCH="touch";GestureDetector.READY=!1,GestureDetector.plugins=GestureDetector.plugins||{},GestureDetector.gestures=GestureDetector.gestures||{};var Utils=GestureDetector.utils={extend:function(dest,src,merge){for(var key in src)!src.hasOwnProperty(key)||void 0!==dest[key]&&merge||(dest[key]=src[key]);return dest},on:function(element,type,handler){element.addEventListener(type,handler,!1)},off:function(element,type,handler){element.removeEventListener(type,handler,!1)},each:function(obj,iterator,context){var i,len;if("forEach"in obj)obj.forEach(iterator,context);else if(void 0!==obj.length){for(i=0,len=obj.length;len>i;i++)if(iterator.call(context,obj[i],i,obj)===!1)return}else for(i in obj)if(obj.hasOwnProperty(i)&&iterator.call(context,obj[i],i,obj)===!1)return},inStr:function(src,find){return src.indexOf(find)>-1},inArray:function(src,find){if(src.indexOf){var index=src.indexOf(find);return-1===index?!1:index}for(var i=0,len=src.length;len>i;i++)if(src[i]===find)return i;return!1},toArray:function(obj){return Array.prototype.slice.call(obj,0)},hasParent:function(node,parent){for(;node;){if(node==parent)return!0;node=node.parentNode}return!1},getCenter:function(touches){var pageX=[],pageY=[],clientX=[],clientY=[],min=Math.min,max=Math.max;return 1===touches.length?{pageX:touches[0].pageX,pageY:touches[0].pageY,clientX:touches[0].clientX,clientY:touches[0].clientY}:(Utils.each(touches,function(touch){pageX.push(touch.pageX),pageY.push(touch.pageY),clientX.push(touch.clientX),clientY.push(touch.clientY)}),{pageX:(min.apply(Math,pageX)+max.apply(Math,pageX))/2,pageY:(min.apply(Math,pageY)+max.apply(Math,pageY))/2,clientX:(min.apply(Math,clientX)+max.apply(Math,clientX))/2,clientY:(min.apply(Math,clientY)+max.apply(Math,clientY))/2})},getVelocity:function(deltaTime,deltaX,deltaY){return{x:Math.abs(deltaX/deltaTime)||0,y:Math.abs(deltaY/deltaTime)||0}},getAngle:function(touch1,touch2){var x=touch2.clientX-touch1.clientX,y=touch2.clientY-touch1.clientY;return 180*Math.atan2(y,x)/Math.PI},getDirection:function(touch1,touch2){var x=Math.abs(touch1.clientX-touch2.clientX),y=Math.abs(touch1.clientY-touch2.clientY);return x>=y?touch1.clientX-touch2.clientX>0?DIRECTION_LEFT:DIRECTION_RIGHT:touch1.clientY-touch2.clientY>0?DIRECTION_UP:DIRECTION_DOWN},getDistance:function(touch1,touch2){var x=touch2.clientX-touch1.clientX,y=touch2.clientY-touch1.clientY;return Math.sqrt(x*x+y*y)},getScale:function(start,end){return start.length>=2&&end.length>=2?this.getDistance(end[0],end[1])/this.getDistance(start[0],start[1]):1},getRotation:function(start,end){return start.length>=2&&end.length>=2?this.getAngle(end[1],end[0])-this.getAngle(start[1],start[0]):0},isVertical:function(direction){return direction==DIRECTION_UP||direction==DIRECTION_DOWN},setPrefixedCss:function(element,prop,value,toggle){var prefixes=["","Webkit","Moz","O","ms"];prop=Utils.toCamelCase(prop);for(var i=0;i<prefixes.length;i++){var p=prop;if(prefixes[i]&&(p=prefixes[i]+p.slice(0,1).toUpperCase()+p.slice(1)),p in element.style){element.style[p]=(null===toggle||toggle)&&value||"";break}}},toggleBehavior:function(element,props,toggle){if(props&&element&&element.style){Utils.each(props,function(value,prop){Utils.setPrefixedCss(element,prop,value,toggle)});var falseFn=toggle&&function(){return!1};"none"==props.userSelect&&(element.onselectstart=falseFn),"none"==props.userDrag&&(element.ondragstart=falseFn)}},toCamelCase:function(str){return str.replace(/[_-]([a-z])/g,function(s){return s[1].toUpperCase()})}},Event=GestureDetector.event={preventMouseEvents:!1,started:!1,shouldDetect:!1,on:function(element,type,handler,hook){var types=type.split(" ");Utils.each(types,function(type){Utils.on(element,type,handler),hook&&hook(type)})},off:function(element,type,handler,hook){var types=type.split(" ");Utils.each(types,function(type){Utils.off(element,type,handler),hook&&hook(type)})},onTouch:function(element,eventType,handler){var self=this,onTouchHandler=function(ev){var triggerType,srcType=ev.type.toLowerCase(),isPointer=GestureDetector.HAS_POINTEREVENTS,isMouse=Utils.inStr(srcType,"mouse");isMouse&&self.preventMouseEvents||(isMouse&&eventType==EVENT_START&&0===ev.button?(self.preventMouseEvents=!1,self.shouldDetect=!0):isPointer&&eventType==EVENT_START?self.shouldDetect=1===ev.buttons||PointerEvent.matchType(POINTER_TOUCH,ev):isMouse||eventType!=EVENT_START||(self.preventMouseEvents=!0,self.shouldDetect=!0),isPointer&&eventType!=EVENT_END&&PointerEvent.updatePointer(eventType,ev),self.shouldDetect&&(triggerType=self.doDetect.call(self,ev,eventType,element,handler)),triggerType==EVENT_END&&(self.preventMouseEvents=!1,self.shouldDetect=!1,PointerEvent.reset()),isPointer&&eventType==EVENT_END&&PointerEvent.updatePointer(eventType,ev))};return this.on(element,EVENT_TYPES[eventType],onTouchHandler),onTouchHandler},doDetect:function(ev,eventType,element,handler){var touchList=this.getTouchList(ev,eventType),touchListLength=touchList.length,triggerType=eventType,triggerChange=touchList.trigger,changedLength=touchListLength;eventType==EVENT_START?triggerChange=EVENT_TOUCH:eventType==EVENT_END&&(triggerChange=EVENT_RELEASE,changedLength=touchList.length-(ev.changedTouches?ev.changedTouches.length:1)),changedLength>0&&this.started&&(triggerType=EVENT_MOVE),this.started=!0;var evData=this.collectEventData(element,triggerType,touchList,ev);return eventType!=EVENT_END&&handler.call(Detection,evData),triggerChange&&(evData.changedLength=changedLength,evData.eventType=triggerChange,handler.call(Detection,evData),evData.eventType=triggerType,delete evData.changedLength),triggerType==EVENT_END&&(handler.call(Detection,evData),this.started=!1),triggerType},determineEventTypes:function(){var types;return types=GestureDetector.HAS_POINTEREVENTS?window.PointerEvent?["pointerdown","pointermove","pointerup pointercancel lostpointercapture"]:["MSPointerDown","MSPointerMove","MSPointerUp MSPointerCancel MSLostPointerCapture"]:GestureDetector.NO_MOUSEEVENTS?["touchstart","touchmove","touchend touchcancel"]:["touchstart mousedown","touchmove mousemove","touchend touchcancel mouseup"],EVENT_TYPES[EVENT_START]=types[0],EVENT_TYPES[EVENT_MOVE]=types[1],EVENT_TYPES[EVENT_END]=types[2],EVENT_TYPES},getTouchList:function(ev,eventType){if(GestureDetector.HAS_POINTEREVENTS)return PointerEvent.getTouchList();if(ev.touches){if(eventType==EVENT_MOVE)return ev.touches;var identifiers=[],concat=[].concat(Utils.toArray(ev.touches),Utils.toArray(ev.changedTouches)),touchList=[];return Utils.each(concat,function(touch){Utils.inArray(identifiers,touch.identifier)===!1&&touchList.push(touch),identifiers.push(touch.identifier)}),touchList}return ev.identifier=1,[ev]},collectEventData:function(element,eventType,touches,ev){var pointerType=POINTER_TOUCH;return Utils.inStr(ev.type,"mouse")||PointerEvent.matchType(POINTER_MOUSE,ev)?pointerType=POINTER_MOUSE:PointerEvent.matchType(POINTER_PEN,ev)&&(pointerType=POINTER_PEN),{center:Utils.getCenter(touches),timeStamp:Date.now(),target:ev.target,touches:touches,eventType:eventType,pointerType:pointerType,srcEvent:ev,preventDefault:function(){var srcEvent=this.srcEvent;srcEvent.preventManipulation&&srcEvent.preventManipulation(),srcEvent.preventDefault&&srcEvent.preventDefault()},stopPropagation:function(){this.srcEvent.stopPropagation()},stopDetect:function(){return Detection.stopDetect()}}}},PointerEvent=GestureDetector.PointerEvent={pointers:{},getTouchList:function(){var touchlist=[];return Utils.each(this.pointers,function(pointer){touchlist.push(pointer)}),touchlist},updatePointer:function(eventType,pointerEvent){eventType==EVENT_END||eventType!=EVENT_END&&1!==pointerEvent.buttons?delete this.pointers[pointerEvent.pointerId]:(pointerEvent.identifier=pointerEvent.pointerId,this.pointers[pointerEvent.pointerId]=pointerEvent)},matchType:function(pointerType,ev){if(!ev.pointerType)return!1;var pt=ev.pointerType,types={};return types[POINTER_MOUSE]=pt===(ev.MSPOINTER_TYPE_MOUSE||POINTER_MOUSE),types[POINTER_TOUCH]=pt===(ev.MSPOINTER_TYPE_TOUCH||POINTER_TOUCH),types[POINTER_PEN]=pt===(ev.MSPOINTER_TYPE_PEN||POINTER_PEN),types[pointerType]},reset:function(){this.pointers={}}},Detection=GestureDetector.detection={gestures:[],current:null,previous:null,stopped:!1,startDetect:function(inst,eventData){this.current||(this.stopped=!1,this.current={inst:inst,startEvent:Utils.extend({},eventData),lastEvent:!1,lastCalcEvent:!1,futureCalcEvent:!1,lastCalcData:{},name:""},this.detect(eventData))},detect:function(eventData){if(this.current&&!this.stopped){eventData=this.extendEventData(eventData);var inst=this.current.inst,instOptions=inst.options;return Utils.each(this.gestures,function(gesture){!this.stopped&&inst.enabled&&instOptions[gesture.name]&&gesture.handler.call(gesture,eventData,inst)},this),this.current&&(this.current.lastEvent=eventData),eventData.eventType==EVENT_END&&this.stopDetect(),eventData}},stopDetect:function(){this.previous=Utils.extend({},this.current),this.current=null,this.stopped=!0},getCalculatedData:function(ev,center,deltaTime,deltaX,deltaY){var cur=this.current,recalc=!1,calcEv=cur.lastCalcEvent,calcData=cur.lastCalcData;calcEv&&ev.timeStamp-calcEv.timeStamp>GestureDetector.CALCULATE_INTERVAL&&(center=calcEv.center,deltaTime=ev.timeStamp-calcEv.timeStamp,deltaX=ev.center.clientX-calcEv.center.clientX,deltaY=ev.center.clientY-calcEv.center.clientY,recalc=!0),(ev.eventType==EVENT_TOUCH||ev.eventType==EVENT_RELEASE)&&(cur.futureCalcEvent=ev),(!cur.lastCalcEvent||recalc)&&(calcData.velocity=Utils.getVelocity(deltaTime,deltaX,deltaY),calcData.angle=Utils.getAngle(center,ev.center),calcData.direction=Utils.getDirection(center,ev.center),cur.lastCalcEvent=cur.futureCalcEvent||ev,cur.futureCalcEvent=ev),ev.velocityX=calcData.velocity.x,ev.velocityY=calcData.velocity.y,ev.interimAngle=calcData.angle,ev.interimDirection=calcData.direction},extendEventData:function(ev){var cur=this.current,startEv=cur.startEvent,lastEv=cur.lastEvent||startEv;(ev.eventType==EVENT_TOUCH||ev.eventType==EVENT_RELEASE)&&(startEv.touches=[],Utils.each(ev.touches,function(touch){startEv.touches.push({clientX:touch.clientX,clientY:touch.clientY})}));var deltaTime=ev.timeStamp-startEv.timeStamp,deltaX=ev.center.clientX-startEv.center.clientX,deltaY=ev.center.clientY-startEv.center.clientY;return this.getCalculatedData(ev,lastEv.center,deltaTime,deltaX,deltaY),Utils.extend(ev,{startEvent:startEv,deltaTime:deltaTime,deltaX:deltaX,deltaY:deltaY,distance:Utils.getDistance(startEv.center,ev.center),angle:Utils.getAngle(startEv.center,ev.center),direction:Utils.getDirection(startEv.center,ev.center),scale:Utils.getScale(startEv.touches,ev.touches),rotation:Utils.getRotation(startEv.touches,ev.touches)}),ev},register:function(gesture){var options=gesture.defaults||{};return void 0===options[gesture.name]&&(options[gesture.name]=!0),Utils.extend(GestureDetector.defaults,options,!0),gesture.index=gesture.index||1e3,this.gestures.push(gesture),this.gestures.sort(function(a,b){return a.index<b.index?-1:a.index>b.index?1:0}),this.gestures}};GestureDetector.Instance=function(element,options){var self=this;setup(),this.element=element,this.enabled=!0,Utils.each(options,function(value,name){delete options[name],options[Utils.toCamelCase(name)]=value}),this.options=Utils.extend(Utils.extend({},GestureDetector.defaults),options||{}),this.options.behavior&&Utils.toggleBehavior(this.element,this.options.behavior,!0),this.eventStartHandler=Event.onTouch(element,EVENT_START,function(ev){self.enabled&&ev.eventType==EVENT_START?Detection.startDetect(self,ev):ev.eventType==EVENT_TOUCH&&Detection.detect(ev)}),this.eventHandlers=[]},GestureDetector.Instance.prototype={on:function(gestures,handler){var self=this;return Event.on(self.element,gestures,handler,function(type){self.eventHandlers.push({gesture:type,handler:handler})}),self},off:function(gestures,handler){var self=this;return Event.off(self.element,gestures,handler,function(type){var index=Utils.inArray({gesture:type,handler:handler});index!==!1&&self.eventHandlers.splice(index,1)}),self},trigger:function(gesture,eventData){eventData||(eventData={});var event=GestureDetector.DOCUMENT.createEvent("Event");event.initEvent(gesture,!0,!0),event.gesture=eventData;var element=this.element;return Utils.hasParent(eventData.target,element)&&(element=eventData.target),element.dispatchEvent(event),this},enable:function(state){return this.enabled=state,this},dispose:function(){var i,eh;for(Utils.toggleBehavior(this.element,this.options.behavior,!1),i=-1;eh=this.eventHandlers[++i];)Utils.off(this.element,eh.gesture,eh.handler);return this.eventHandlers=[],Event.off(this.element,EVENT_TYPES[EVENT_START],this.eventStartHandler),null}},function(name){function dragGesture(ev,inst){var cur=Detection.current;if(!(inst.options.dragMaxTouches>0&&ev.touches.length>inst.options.dragMaxTouches))switch(ev.eventType){case EVENT_START:triggered=!1;break;case EVENT_MOVE:if(ev.distance<inst.options.dragMinDistance&&cur.name!=name)return;var startCenter=cur.startEvent.center;if(cur.name!=name&&(cur.name=name,inst.options.dragDistanceCorrection&&ev.distance>0)){var factor=Math.abs(inst.options.dragMinDistance/ev.distance);startCenter.pageX+=ev.deltaX*factor,startCenter.pageY+=ev.deltaY*factor,startCenter.clientX+=ev.deltaX*factor,startCenter.clientY+=ev.deltaY*factor,ev=Detection.extendEventData(ev)}(cur.lastEvent.dragLockToAxis||inst.options.dragLockToAxis&&inst.options.dragLockMinDistance<=ev.distance)&&(ev.dragLockToAxis=!0);var lastDirection=cur.lastEvent.direction;ev.dragLockToAxis&&lastDirection!==ev.direction&&(Utils.isVertical(lastDirection)?ev.direction=ev.deltaY<0?DIRECTION_UP:DIRECTION_DOWN:ev.direction=ev.deltaX<0?DIRECTION_LEFT:DIRECTION_RIGHT),triggered||(inst.trigger(name+"start",ev),triggered=!0),inst.trigger(name,ev),inst.trigger(name+ev.direction,ev);var isVertical=Utils.isVertical(ev.direction);(inst.options.dragBlockVertical&&isVertical||inst.options.dragBlockHorizontal&&!isVertical)&&ev.preventDefault();break;case EVENT_RELEASE:triggered&&ev.changedLength<=inst.options.dragMaxTouches&&(inst.trigger(name+"end",ev),triggered=!1);break;case EVENT_END:triggered=!1}}var triggered=!1;GestureDetector.gestures.Drag={name:name,index:50,handler:dragGesture,defaults:{dragMinDistance:10,dragDistanceCorrection:!0,dragMaxTouches:1,dragBlockHorizontal:!1,dragBlockVertical:!1,dragLockToAxis:!1,dragLockMinDistance:25}}}("drag"),GestureDetector.gestures.Gesture={name:"gesture",index:1337,handler:function(ev,inst){inst.trigger(this.name,ev)}},function(name){function holdGesture(ev,inst){var options=inst.options,current=Detection.current;switch(ev.eventType){case EVENT_START:clearTimeout(timer),current.name=name,timer=setTimeout(function(){current&&current.name==name&&inst.trigger(name,ev)},options.holdTimeout);break;case EVENT_MOVE:ev.distance>options.holdThreshold&&clearTimeout(timer);break;case EVENT_RELEASE:clearTimeout(timer)}}var timer;GestureDetector.gestures.Hold={name:name,index:10,defaults:{holdTimeout:500,holdThreshold:2},handler:holdGesture}}("hold"),GestureDetector.gestures.Release={name:"release",index:1/0,handler:function(ev,inst){ev.eventType==EVENT_RELEASE&&inst.trigger(this.name,ev)}},GestureDetector.gestures.Swipe={name:"swipe",index:40,defaults:{swipeMinTouches:1,swipeMaxTouches:1,swipeVelocityX:.6,swipeVelocityY:.6},handler:function(ev,inst){if(ev.eventType==EVENT_RELEASE){var touches=ev.touches.length,options=inst.options;if(touches<options.swipeMinTouches||touches>options.swipeMaxTouches)return;(ev.velocityX>options.swipeVelocityX||ev.velocityY>options.swipeVelocityY)&&(inst.trigger(this.name,ev),inst.trigger(this.name+ev.direction,ev))}}},function(name){function tapGesture(ev,inst){var sincePrev,didDoubleTap,options=inst.options,current=Detection.current,prev=Detection.previous;switch(ev.eventType){case EVENT_START:hasMoved=!1;break;case EVENT_MOVE:hasMoved=hasMoved||ev.distance>options.tapMaxDistance;break;case EVENT_END:!Utils.inStr(ev.srcEvent.type,"cancel")&&ev.deltaTime<options.tapMaxTime&&!hasMoved&&(sincePrev=prev&&prev.lastEvent&&ev.timeStamp-prev.lastEvent.timeStamp,didDoubleTap=!1,prev&&prev.name==name&&sincePrev&&sincePrev<options.doubleTapInterval&&ev.distance<options.doubleTapDistance&&(inst.trigger("doubletap",ev),didDoubleTap=!0),(!didDoubleTap||options.tapAlways)&&(current.name=name,inst.trigger(current.name,ev)))}}var hasMoved=!1;GestureDetector.gestures.Tap={name:name,index:100,handler:tapGesture,defaults:{tapMaxTime:250,tapMaxDistance:10,tapAlways:!0,doubleTapDistance:20,doubleTapInterval:300}}}("tap"),GestureDetector.gestures.Touch={name:"touch",index:-(1/0),defaults:{preventDefault:!1,preventMouse:!1},handler:function(ev,inst){return inst.options.preventMouse&&ev.pointerType==POINTER_MOUSE?void ev.stopDetect():(inst.options.preventDefault&&ev.preventDefault(),void(ev.eventType==EVENT_TOUCH&&inst.trigger("touch",ev)))}},function(name){function transformGesture(ev,inst){switch(ev.eventType){case EVENT_START:triggered=!1;break;case EVENT_MOVE:if(ev.touches.length<2)return;var scaleThreshold=Math.abs(1-ev.scale),rotationThreshold=Math.abs(ev.rotation);if(scaleThreshold<inst.options.transformMinScale&&rotationThreshold<inst.options.transformMinRotation)return;Detection.current.name=name,triggered||(inst.trigger(name+"start",ev),triggered=!0),inst.trigger(name,ev),rotationThreshold>inst.options.transformMinRotation&&inst.trigger("rotate",ev),scaleThreshold>inst.options.transformMinScale&&(inst.trigger("pinch",ev),inst.trigger("pinch"+(ev.scale<1?"in":"out"),ev));break;case EVENT_RELEASE:triggered&&ev.changedLength<2&&(inst.trigger(name+"end",ev),triggered=!1)}}var triggered=!1;GestureDetector.gestures.Transform={name:name,index:45,defaults:{transformMinScale:.01,transformMinRotation:1},handler:transformGesture}}("transform"),"function"==typeof define&&define.amd?define(function(){return GestureDetector}):"undefined"!=typeof module&&module.exports?module.exports=GestureDetector:(window.ons=window.ons||{},window.ons.GestureDetector=GestureDetector)}(window),window.styler=function(){"use strict";var styler=function(element,style){return styler.css.apply(styler,arguments)};return styler.css=function(element,styles){var keys=Object.keys(styles);return keys.forEach(function(key){key in element.style?element.style[key]=styles[key]:styler._prefix(key)in element.style?element.style[styler._prefix(key)]=styles[key]:console.warn("No such style property: "+key)}),element},styler._prefix=function(){var styles=window.getComputedStyle(document.documentElement,""),prefix=(Array.prototype.slice.call(styles).join("").match(/-(moz|webkit|ms)-/)||""===styles.OLink&&["","o"])[1];return function(name){return prefix+name.substr(0,1).toUpperCase()+name.substr(1)}}(),styler.clear=function(element){styler._clear(element)},styler._clear=function(element){for(var len=element.style.length,style=element.style,keys=[],i=0;len>i;i++)keys.push(style[i]);keys.forEach(function(key){style[key]=""})},styler}(),function(ons){window.addEventListener("load",function(){return FastClick.attach(document.body)},!1),window.addEventListener("DOMContentLoaded",function(){ons._defaultDeviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(window.document.body,function(){navigator.app.exitApp()})},!1),ons.ready(function(){ons._setupLoadingPlaceHolders()}),(new Viewport).setup(),Modernizr.testStyles("#modernizr { -webkit-overflow-scrolling:touch }",function(elem,rule){Modernizr.addTest("overflowtouch",window.getComputedStyle&&"touch"==window.getComputedStyle(elem).getPropertyValue("-webkit-overflow-scrolling"))}),"function"!=typeof HTMLElement?(ons._BaseElement=function(){},ons._BaseElement.prototype=document.createElement("div")):ons._BaseElement=HTMLElement}(window.ons=window.ons||{});var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={"":"alert-dialog--*",".alert-dialog-title":"alert-dialog-title--*",".alert-dialog-content":"alert-dialog-content--*",".alert-dialog-footer":"alert-dialog-footer--*",".alert-dialog-button":"alert-dialog-button--*",".alert-dialog-footer--one":"alert-dialog-footer--one--*",".alert-dialog-button--one":"alert-dialog-button--one--*",".alert-dialog-button--primal":"alert-dialog-button--primal--*"},AnimatorFactory=ons._internal.AnimatorFactory,AndroidAlertDialogAnimator=ons._internal.AndroidAlertDialogAnimator,IOSAlertDialogAnimator=ons._internal.IOSAlertDialogAnimator,SlideDialogAnimator=ons._internal.SlideDialogAnimator,AlertDialogAnimator=ons._internal.AlertDialogAnimator,AlertDialogElement=function(_ons$_BaseElement){function AlertDialogElement(){_classCallCheck(this,AlertDialogElement),_get(Object.getPrototypeOf(AlertDialogElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(AlertDialogElement,_ons$_BaseElement),_createClass(AlertDialogElement,[{key:"createdCallback",value:function(){this._compile(),this._mask=this._createMask(this.getAttribute("mask-color")),ModifierUtil.initModifier(this,scheme),this._animatorFactory=new AnimatorFactory({animators:OnsAlertDialogElement._animatorDict,baseClass:AlertDialogAnimator,baseClassName:"AlertDialogAnimator",defaultAnimation:this.getAttribute("animation")}),this._visible=!1,this._doorLock=new DoorLock,this._boundCancel=this._cancel.bind(this)}},{key:"_compile",value:function(){if(this.style.display="none",this.style.zIndex="20001",this.classList.add("alert-dialog"),ons.platform.isAndroid()){var modifier=this.hasAttribute("modifier")?this.getAttribute("modifier"):"";this.setAttribute("modifier",(modifier+" android").trim())}}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"setCancelable",value:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this.setAttribute("cancelable",""):this.removeAttribute("cancelable")}},{key:"show",value:function(){var _this=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel2=!1,callback=options.callback||function(){};options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),util.triggerElementEvent(this,"preshow",{alertDialog:this,cancel:function(){_cancel2=!0}}),_cancel2||this._doorLock.waitUnlock(function(){var unlock=_this._doorLock.lock();_this._mask.style.display="block",_this._mask.style.opacity=1,_this.style.display="block";var animator=_this._animatorFactory.newAnimator(options);animator.show(_this,function(){_this._visible=!0,unlock(),util.triggerElementEvent(_this,"postshow",{alertDialog:_this}),callback()})})}},{key:"hide",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel3=!1,callback=options.callback||function(){};util.triggerElementEvent(this,"prehide",{alertDialog:this,cancel:function(){_cancel3=!0}}),_cancel3||this._doorLock.waitUnlock(function(){var unlock=_this2._doorLock.lock(),animator=_this2._animatorFactory.newAnimator(options);animator.hide(_this2,function(){_this2.style.display="none",_this2._mask.style.display="none",_this2._visible=!1,unlock(),util.triggerElementEvent(_this2,"posthide",{alertDialog:_this2}),callback()})})}},{key:"isShown",value:function(){return this._visible}},{key:"destroy",value:function(){this.parentElement&&this.parentElement.removeChild(this),this._mask.parentElement&&this._mask.parentElement.removeChild(this._mask)}},{key:"isCancelable",value:function(){return this.hasAttribute("cancelable")}},{key:"_onDeviceBackButton",value:function(event){this.isCancelable()?this._cancel():event.callParentHandler()}},{key:"_cancel",value:function(){var _this3=this;this.isCancelable()&&this.hide({callback:function(){util.triggerElementEvent(_this3,"cancel")}})}},{key:"_createMask",value:function(color){return this._mask=util.createElement("<div></div>"),this._mask.classList.add("alert-dialog-mask"),this._mask.style.zIndex=2e4,this._mask.style.display="none",color&&(this._mask.style.backgroundColor=color),document.body.appendChild(this._mask),this._mask}},{key:"attachedCallback",value:function(){this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this)),this._mask.addEventListener("click",this._boundCancel,!1)}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this._mask.removeEventListener("click",this._boundCancel.bind(this),!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"_titleElement",get:function(){return util.findChild(this,".alert-dialog-title")}},{key:"_contentElement",get:function(){return util.findChild(this,".alert-dialog-content")}},{key:"_dialog",get:function(){return this}}]),AlertDialogElement}(ons._BaseElement);window.OnsAlertDialogElement||(window.OnsAlertDialogElement=document.registerElement("ons-alert-dialog",{prototype:AlertDialogElement.prototype}),window.OnsAlertDialogElement._animatorDict={"default":ons.platform.isAndroid()?AndroidAlertDialogAnimator:IOSAlertDialogAnimator,fade:ons.platform.isAndroid()?AndroidAlertDialogAnimator:IOSAlertDialogAnimator,slide:SlideDialogAnimator,none:AlertDialogAnimator},window.OnsAlertDialogElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof AlertDialogAnimator))throw new Error('"Animator" param must inherit DialogAnimator');this._animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,templateElement=util.createElement('\n <span\n class="toolbar-button--quiet"\n style="height: 44px; line-height: 0; padding: 0 10px 0 0; position: relative;">\n\n <i class="ion-ios-arrow-back ons-back-button__icon"\n style="\n vertical-align: top;\n background-color: transparent;\n height: 44px;\n line-height: 44px;\n font-size: 36px;\n margin-left: 8px;\n margin-right: 2px;\n width: 16px;\n display: inline-block;\n padding-top: 1px;"></i>\n\n <span\n style="vertical-align: top; display: inline-block; line-height: 44px; height: 44px;"\n class="back-button__label"></span>\n </span>\n '),scheme={ ".toolbar-button--quiet":"toolbar-button--*"},BackButtonElement=function(_ons$_BaseElement){function BackButtonElement(){_classCallCheck(this,BackButtonElement),_get(Object.getPrototypeOf(BackButtonElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(BackButtonElement,_ons$_BaseElement),_createClass(BackButtonElement,[{key:"createdCallback",value:function(){this._compile(),this._boundOnClick=this._onClick.bind(this),ModifierUtil.initModifier(this,scheme)}},{key:"_compile",value:function(){for(var template=templateElement.cloneNode(!0),inner=template.querySelector(".back-button__label");this.childNodes[0];)inner.appendChild(this.childNodes[0]);""===inner.innerHTML.trim()&&(inner.textContent="Back"),this.appendChild(template)}},{key:"_onClick",value:function(){var navigator=util.findParent(this,"ons-navigator");navigator&&navigator.popPage({cancelIfRunning:!0})}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick,!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}}]),BackButtonElement}(ons._BaseElement);window.OnsBackButtonElement||(window.OnsBackButtonElement=document.registerElement("ons-back-button",{prototype:BackButtonElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var scheme={"":"bottom-bar--*"},ModifierUtil=ons._internal.ModifierUtil,BottomToolbarElement=function(_ons$_BaseElement){function BottomToolbarElement(){_classCallCheck(this,BottomToolbarElement),_get(Object.getPrototypeOf(BottomToolbarElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(BottomToolbarElement,_ons$_BaseElement),_createClass(BottomToolbarElement,[{key:"createdCallback",value:function(){this.classList.add("bottom-bar"),this.style.zIndex="0",this._update(),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){if("inline"===name)this._update();else if("modifier"===name)return ModifierUtil.onModifierChanged(last,current,this,scheme)}},{key:"_update",value:function(){var inline="string"==typeof this.getAttribute("inline");this.style.position=inline?"static":"absolute"}}]),BottomToolbarElement}(ons._BaseElement);window.OnsBottomToolbarElement||(window.OnsBottomToolbarElement=document.registerElement("ons-bottom-toolbar",{prototype:BottomToolbarElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var scheme={"":"button--*"},ModifierUtil=ons._internal.ModifierUtil,ButtonElement=function(_ons$_BaseElement){function ButtonElement(){_classCallCheck(this,ButtonElement),_get(Object.getPrototypeOf(ButtonElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ButtonElement,_ons$_BaseElement),_createClass(ButtonElement,[{key:"createdCallback",value:function(){this.classList.add("button"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ButtonElement}(ons._BaseElement);window.OnsButtonElement||(window.OnsButtonElement=document.registerElement("ons-button",{prototype:ButtonElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var ModifierUtil=ons._internal.ModifierUtil,scheme={"":"carousel-item--*"},CarouselItemElement=function(_ons$_BaseElement){function CarouselItemElement(){_classCallCheck(this,CarouselItemElement),_get(Object.getPrototypeOf(CarouselItemElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(CarouselItemElement,_ons$_BaseElement),_createClass(CarouselItemElement,[{key:"createdCallback",value:function(){this.style.width="100%",ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),CarouselItemElement}(ons._BaseElement);window.OnsCarouselItemElement||(window.OnsCarouselItemElement=document.registerElement("ons-carousel-item",{prototype:CarouselItemElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var ModifierUtil=ons._internal.ModifierUtil,util=ons._util,scheme={"":"carousel--*"},VerticalModeTrait={_getScrollDelta:function(event){return event.gesture.deltaY},_getScrollVelocity:function(event){return event.gesture.velocityY},_getElementSize:function(){return this._currentElementSize||(this._currentElementSize=this.getBoundingClientRect().height),this._currentElementSize},_generateScrollTransform:function(scroll){return"translate3d(0px, "+-scroll+"px, 0px)"},_layoutCarouselItems:function(){for(var children=this._getCarouselItemElements(),sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),computedStyle=window.getComputedStyle(this),totalWidth=this.getBoundingClientRect().width||0,finalWidth=totalWidth-parseInt(computedStyle.paddingLeft,10)-parseInt(computedStyle.paddingRight,10),i=0;i<children.length;i++)children[i].style.position="absolute",children[i].style.height=sizeAttr,children[i].style.width=finalWidth+"px",children[i].style.visibility="visible",children[i].style.top=i*sizeInfo.number+sizeInfo.unit}},HorizontalModeTrait={_getScrollDelta:function(event){return event.gesture.deltaX},_getScrollVelocity:function(event){return event.gesture.velocityX},_getElementSize:function(){return this._currentElementSize||(this._currentElementSize=this.getBoundingClientRect().width),this._currentElementSize},_generateScrollTransform:function(scroll){return"translate3d("+-scroll+"px, 0px, 0px)"},_layoutCarouselItems:function(){for(var children=this._getCarouselItemElements(),sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),computedStyle=window.getComputedStyle(this),totalHeight=this.getBoundingClientRect().height||0,finalHeight=totalHeight-parseInt(computedStyle.paddingTop,10)-parseInt(computedStyle.paddingBottom,10),i=0;i<children.length;i++)children[i].style.position="absolute",children[i].style.height=finalHeight+"px",children[i].style.width=sizeAttr,children[i].style.visibility="visible",children[i].style.left=i*sizeInfo.number+sizeInfo.unit}},CarouselElement=function(_ons$_BaseElement){function CarouselElement(){_classCallCheck(this,CarouselElement),_get(Object.getPrototypeOf(CarouselElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(CarouselElement,_ons$_BaseElement),_createClass(CarouselElement,[{key:"createdCallback",value:function(){ModifierUtil.initModifier(this,scheme),this._doorLock=new DoorLock,this._scroll=0,this._lastActiveIndex=0,this._boundOnDrag=this._onDrag.bind(this),this._boundOnDragEnd=this._onDragEnd.bind(this),this._boundOnResize=this._onResize.bind(this),this._mixin(this._isVertical()?VerticalModeTrait:HorizontalModeTrait),this._layoutCarouselItems(),this._setupInitialIndex(),this._saveLastState()}},{key:"_onResize",value:function(){this.refresh()}},{key:"_onDirectionChange",value:function(){this._isVertical()?(this.style.overflowX="auto",this.style.overflowY=""):(this.style.overflowX="",this.style.overflowY="auto"),this.refresh()}},{key:"_saveLastState",value:function(){this._lastState={elementSize:this._getCarouselItemSize(),carouselElementCount:this.getCarouselItemCount(),width:this._getCarouselItemSize()*this.getCarouselItemCount()}}},{key:"_getCarouselItemSize",value:function(){var sizeAttr=this._getCarouselItemSizeAttr(),sizeInfo=this._decomposeSizeString(sizeAttr),elementSize=this._getElementSize();if("%"===sizeInfo.unit)return Math.round(sizeInfo.number/100*elementSize);if("px"===sizeInfo.unit)return sizeInfo.number;throw new Error("Invalid state")}},{key:"_getInitialIndex",value:function(){var index=parseInt(this.getAttribute("initial-index"),10);return"number"!=typeof index||isNaN(index)?0:Math.max(Math.min(index,this.getCarouselItemCount()-1),0)}},{key:"_getCarouselItemSizeAttr",value:function(){var attrName="item-"+(this._isVertical()?"height":"width"),itemSizeAttr=(""+this.getAttribute(attrName)).trim();return itemSizeAttr.match(/^\d+(px|%)$/)?itemSizeAttr:"100%"}},{key:"_decomposeSizeString",value:function(size){var matches=size.match(/^(\d+)(px|%)/);return{number:parseInt(matches[1],10),unit:matches[2]}}},{key:"_setupInitialIndex",value:function(){this._scroll=this._getCarouselItemSize()*this._getInitialIndex(),this._lastActiveIndex=this._getInitialIndex(),this._scrollTo(this._scroll)}},{key:"setSwipeable",value:function(swipeable){swipeable?this.setAttribute("swipeable",""):this.removeAttribute("swipeable")}},{key:"isSwipeable",value:function(){return this.hasAttribute("swipeable")}},{key:"setAutoScrollRatio",value:function(ratio){if(0>ratio||ratio>1)throw new Error("Invalid ratio.");this.setAttribute("auto-scroll-ratio",ratio)}},{key:"getAutoScrollRatio",value:function(){var attr=this.getAttribute("auto-scroll-ratio");if(!attr)return.5;var scrollRatio=parseFloat(attr);if(0>scrollRatio||scrollRatio>1)throw new Error("Invalid ratio.");return isNaN(scrollRatio)?.5:scrollRatio}},{key:"setActiveCarouselItemIndex",value:function(index,options){options=options||{},index=Math.max(0,Math.min(index,this.getCarouselItemCount()-1));var scroll=this._getCarouselItemSize()*index,max=this._calculateMaxScroll();this._scroll=Math.max(0,Math.min(max,scroll)),this._scrollTo(this._scroll,{animate:"none"!==options.animation,callback:options.callback}),this._tryFirePostChangeEvent()}},{key:"getActiveCarouselItemIndex",value:function(){var scroll=this._scroll,count=this.getCarouselItemCount(),size=this._getCarouselItemSize();if(0>scroll)return 0;var i=void 0;for(i=0;count>i;i++)if(scroll>=size*i&&size*(i+1)>scroll)return i;return i}},{key:"next",value:function(options){return this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex()+1,options)}},{key:"prev",value:function(options){return this.setActiveCarouselItemIndex(this.getActiveCarouselItemIndex()-1,options)}},{key:"setAutoScrollEnabled",value:function(enabled){enabled?this.setAttribute("auto-scroll",""):this.removeAttribute("auto-scroll")}},{key:"isAutoScrollEnabled",value:function(){return this.hasAttribute("auto-scroll")}},{key:"setDisabled",value:function(disabled){disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"setOverscrollable",value:function(scrollable){scrollable?this.setAttribute("overscrollable",""):this.removeAttribute("overscrollable")}},{key:"isOverscrollable",value:function(){return this.hasAttribute("overscrollable")}},{key:"_isEnabledChangeEvent",value:function(){var elementSize=this._getElementSize(),carouselItemSize=this._getCarouselItemSize();return this.isAutoScrollEnabled()&&elementSize===carouselItemSize}},{key:"_isVertical",value:function(){return"vertical"===this.getAttribute("direction")}},{key:"_prepareEventListeners",value:function(){this._gestureDetector=new ons.GestureDetector(this,{dragMinDistance:1}),this._gestureDetector.on("drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown",this._boundOnDrag),this._gestureDetector.on("dragend",this._boundOnDragEnd),window.addEventListener("resize",this._boundOnResize,!0)}},{key:"_removeEventListeners",value:function(){this._gestureDetector.off("drag dragleft dragright dragup dragdown swipe swipeleft swiperight swipeup swipedown",this._boundOnDrag),this._gestureDetector.off("dragend",this._boundOnDragEnd),this._gestureDetector.dispose(),window.removeEventListener("resize",this._boundOnResize,!0)}},{key:"_tryFirePostChangeEvent",value:function(){var currentIndex=this.getActiveCarouselItemIndex();if(this._lastActiveIndex!==currentIndex){var lastActiveIndex=this._lastActiveIndex;this._lastActiveIndex=currentIndex,util.triggerElementEvent(this,"postchange",{carousel:this,activeIndex:currentIndex,lastActiveIndex:lastActiveIndex})}}},{key:"_onDrag",value:function(event){if(this.isSwipeable()){var direction=event.gesture.direction;if((!this._isVertical()||"left"!==direction&&"right"!==direction)&&(this._isVertical()||"up"!==direction&&"down"!==direction)){event.stopPropagation(),this._lastDragEvent=event;var scroll=this._scroll-this._getScrollDelta(event);this._scrollTo(scroll),event.gesture.preventDefault(),this._tryFirePostChangeEvent()}}}},{key:"_onDragEnd",value:function(event){var _this=this;if(this._currentElementSize=void 0,this.isSwipeable()){if(this._scroll=this._scroll-this._getScrollDelta(event),0!==this._getScrollDelta(event)&&event.stopPropagation(),this._isOverScroll(this._scroll)){var waitForAction=!1;util.triggerElementEvent(this,"overscroll",{carousel:this,activeIndex:this.getActiveCarouselItemIndex(),direction:this._getOverScrollDirection(),waitToReturn:function(promise){waitForAction=!0,promise.then(function(){return _this._scrollToKillOverScroll()})}}),waitForAction||this._scrollToKillOverScroll()}else this._startMomentumScroll();this._lastDragEvent=null,event.gesture.preventDefault()}}},{key:"_mixin",value:function(trait){Object.keys(trait).forEach(function(key){this[key]=trait[key]}.bind(this))}},{key:"_startMomentumScroll",value:function(){if(this._lastDragEvent){var velocity=this._getScrollVelocity(this._lastDragEvent),duration=.3,scrollDelta=100*duration*velocity,_scroll=this._normalizeScrollPosition(this._scroll+(this._getScrollDelta(this._lastDragEvent)>0?-scrollDelta:scrollDelta));this._scroll=_scroll,animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(this._scroll)},{duration:duration,timing:"cubic-bezier(.1, .7, .1, 1)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).play()}}},{key:"_normalizeScrollPosition",value:function(scroll){var _this2=this,max=this._calculateMaxScroll();if(!this.isAutoScrollEnabled())return Math.max(0,Math.min(max,scroll));var _ret=function(){for(var arr=[],size=_this2._getCarouselItemSize(),i=0;i<_this2.getCarouselItemCount();i++)max>=i*size&&arr.push(i*size);arr.push(max),arr.sort(function(left,right){return left=Math.abs(left-scroll),right=Math.abs(right-scroll),left-right}),arr=arr.filter(function(item,pos){return!pos||item!=arr[pos-1]});var lastScroll=_this2._lastActiveIndex*size,scrollRatio=Math.abs(scroll-lastScroll)/size;return scrollRatio<=_this2.getAutoScrollRatio()?{v:lastScroll}:scrollRatio>_this2.getAutoScrollRatio()&&1>scrollRatio&&arr[0]===lastScroll&&arr.length>1?{v:arr[1]}:{v:arr[0]}}();return"object"==typeof _ret?_ret.v:void 0}},{key:"_getCarouselItemElements",value:function(){return ons._util.arrayFrom(this.children).filter(function(child){return"ons-carousel-item"===child.nodeName.toLowerCase()})}},{key:"_scrollTo",value:function(scroll,options){var _this3=this;options=options||{};var isOverscrollable=this.isOverscrollable(),normalizeScroll=function(scroll){var ratio=.35;if(0>scroll)return isOverscrollable?Math.round(scroll*ratio):0;var maxScroll=_this3._calculateMaxScroll();return scroll>maxScroll?isOverscrollable?maxScroll+Math.round((scroll-maxScroll)*ratio):maxScroll:scroll};options.animate?animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(normalizeScroll(scroll))},{duration:.3,timing:"cubic-bezier(.1, .7, .1, 1)"}).play(options.callback):animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(normalizeScroll(scroll))}).play(options.callback)}},{key:"_calculateMaxScroll",value:function(){var max=this.getCarouselItemCount()*this._getCarouselItemSize()-this._getElementSize();return Math.ceil(0>max?0:max)}},{key:"_isOverScroll",value:function(scroll){return 0>scroll||scroll>this._calculateMaxScroll()?!0:!1}},{key:"_getOverScrollDirection",value:function(){return this._isVertical()?this._scroll<=0?"up":"down":this._scroll<=0?"left":"right"}},{key:"_scrollToKillOverScroll",value:function(){var duration=.4;if(this._scroll<0)return animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(0)},{duration:duration,timing:"cubic-bezier(.1, .4, .1, 1)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).play(),void(this._scroll=0);var maxScroll=this._calculateMaxScroll();return maxScroll<this._scroll?(animit(this._getCarouselItemElements()).queue({transform:this._generateScrollTransform(maxScroll)},{duration:duration,timing:"cubic-bezier(.1, .4, .1, 1)"}).queue(function(done){done(),this._tryFirePostChangeEvent()}.bind(this)).play(),void(this._scroll=maxScroll)):void 0}},{key:"getCarouselItemCount",value:function(){return this._getCarouselItemElements().length}},{key:"refresh",value:function(){if(0!==this._getCarouselItemSize()){if(this._mixin(this._isVertical()?VerticalModeTrait:HorizontalModeTrait),this._layoutCarouselItems(),this._lastState&&this._lastState.width>0){var _scroll2=this._scroll;this._isOverScroll(_scroll2)?this._scrollToKillOverScroll():(this.isAutoScrollEnabled()&&(_scroll2=this._normalizeScrollPosition(_scroll2)),this._scrollTo(_scroll2))}this._saveLastState(),util.triggerElementEvent(this,"refresh",{carousel:this})}}},{key:"first",value:function(){this.setActiveCarouselItemIndex(0)}},{key:"last",value:function(){this.setActiveCarouselItemIndex(Math.max(this.getCarouselItemCount()-1,0))}},{key:"attachedCallback",value:function(){this._prepareEventListeners(),this._layoutCarouselItems(),this._setupInitialIndex(),this._saveLastState()}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("direction"===name&&this._onDirectionChange())}},{key:"detachedCallback",value:function(){this._removeEventListeners()}}]),CarouselElement}(ons._BaseElement);window.OnsCarouselElement||(window.OnsCarouselElement=document.registerElement("ons-carousel",{prototype:CarouselElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var ColumnElement=function(_ons$_BaseElement){function ColumnElement(){_classCallCheck(this,ColumnElement),_get(Object.getPrototypeOf(ColumnElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ColumnElement,_ons$_BaseElement),_createClass(ColumnElement,[{key:"createdCallback",value:function(){this.getAttribute("width")&&this._updateWidth()}},{key:"attributeChangedCallback",value:function(name,last,current){"width"===name&&this._updateWidth()}},{key:"_updateWidth",value:function(){var width=this.getAttribute("width");"string"==typeof width&&(width=(""+width).trim(),width=width.match(/^\d+$/)?width+"%":width,this.style.webkitBoxFlex="0",this.style.webkitFlex="0 0 "+width,this.style.mozBoxFlex="0",this.style.mozFlex="0 0 "+width,this.style.msFlex="0 0 "+width,this.style.flex="0 0 "+width,this.style.maxWidth=width)}}]),ColumnElement}(ons._BaseElement);window.OnsColElement||(window.OnsColElement=document.registerElement("ons-col",{prototype:ColumnElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={".dialog":"dialog--*"},AnimatorFactory=ons._internal.AnimatorFactory,AndroidDialogAnimator=ons._internal.AndroidDialogAnimator,IOSDialogAnimator=ons._internal.IOSDialogAnimator,SlideDialogAnimator=ons._internal.SlideDialogAnimator,DialogAnimator=ons._internal.DialogAnimator,templateSource=util.createElement('\n <div>\n <div class="dialog-mask"></div>\n <div class="dialog"></div>\n </div>\n '),DialogElement=function(_ons$_BaseElement){function DialogElement(){_classCallCheck(this,DialogElement),_get(Object.getPrototypeOf(DialogElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(DialogElement,_ons$_BaseElement),_createClass(DialogElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this._visible=!1,this._doorLock=new DoorLock,this._boundCancel=this._cancel.bind(this),this._animatorFactory=new AnimatorFactory({animators:OnsDialogElement._animatorDict,baseClass:DialogAnimator,baseClassName:"DialogAnimator",defaultAnimation:this.getAttribute("animation")})}},{key:"_compile",value:function(){var style=this.getAttribute("style");this.style.display="none";var template=templateSource.cloneNode(!0),dialog=template.children[1];for(style&&dialog.setAttribute("style",style);this.firstChild;)dialog.appendChild(this.firstChild);for(;template.firstChild;)this.appendChild(template.firstChild);this._dialog.style.zIndex=20001,this._mask.style.zIndex=2e4,this.setAttribute("no-status-bar-fill","")}},{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler}},{key:"_onDeviceBackButton",value:function(event){this.isCancelable()?this._cancel():event.callParentHandler()}},{key:"_cancel",value:function(){var _this=this;this.isCancelable()&&this.hide({callback:function(){util.triggerElementEvent(_this,"cancel")}})}},{key:"show",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel2=!1,callback=options.callback||function(){};util.triggerElementEvent(this,"preshow",{dialog:this,cancel:function(){_cancel2=!0}}),options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),_cancel2||this._doorLock.waitUnlock(function(){var unlock=_this2._doorLock.lock();_this2.style.display="block",_this2._mask.style.opacity="1";var animator=_this2._animatorFactory.newAnimator(options);animator.show(_this2,function(){_this2._visible=!0,unlock(),util.triggerElementEvent(_this2,"postshow",{dialog:_this2}),callback()})})}},{key:"hide",value:function(){var _this3=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],_cancel3=!1,callback=options.callback||function(){};util.triggerElementEvent(this,"prehide",{dialog:this,cancel:function(){_cancel3=!0}}),options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),_cancel3||this._doorLock.waitUnlock(function(){var unlock=_this3._doorLock.lock(),animator=_this3._animatorFactory.newAnimator(options);animator.hide(_this3,function(){_this3.style.display="none",_this3._visible=!1,unlock(),util.triggerElementEvent(_this3,"posthide",{dialog:_this3}),callback()})})}},{key:"destroy",value:function(){this.parentElement&&this.parentElement.removeChild(this)}},{key:"isShown",value:function(){return this._visible}},{key:"isCancelable",value:function(){return this.hasAttribute("cancelable")}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"setCancelable",value:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this.setAttribute("cancelable",""):this.removeAttribute("cancelable")}},{key:"attachedCallback",value:function(){this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this)),this._mask.addEventListener("click",this._boundCancel,!1)}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this._mask.removeEventListener("click",this._boundCancel.bind(this),!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"_mask",get:function(){return util.findChild(this,".dialog-mask")}},{key:"_dialog",get:function(){return util.findChild(this,".dialog")}}]),DialogElement}(ons._BaseElement);window.OnsDialogElement||(window.OnsDialogElement=document.registerElement("ons-dialog",{prototype:DialogElement.prototype}),window.OnsDialogElement._animatorDict={"default":ons.platform.isAndroid()?AndroidDialogAnimator:IOSDialogAnimator,fade:ons.platform.isAndroid()?AndroidDialogAnimator:IOSDialogAnimator,slide:SlideDialogAnimator,none:DialogAnimator},window.OnsDialogElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof DialogAnimator))throw new Error('"Animator" param must inherit DialogAnimator');this._animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0}};!function(){"use strict";var scheme={"":"fab--*"},ModifierUtil=ons._internal.ModifierUtil,FabElement=function(_ons$_BaseElement){function FabElement(){_classCallCheck(this,FabElement),_get(Object.getPrototypeOf(FabElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(FabElement,_ons$_BaseElement),_createClass(FabElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this.classList.add("fab"),this._updatePosition(),this.show()}},{key:"_compile",value:function(){var content=document.createElement("span");content.classList.add("fab__icon");ons._util.arrayFrom(this.childNodes).forEach(function(element){return content.appendChild(element)});this.insertBefore(content,this.firstChild)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("position"===name&&this._updatePosition()); }},{key:"_show",value:function(){this.isInline()||this.show()}},{key:"_hide",value:function(){this.isInline()||this.hide()}},{key:"_updatePosition",value:function(){var position=this.getAttribute("position");switch(this.classList.remove("fab--top__left","fab--bottom__right","fab--bottom__left","fab--top__right","fab--top__center","fab--bottom__center"),position){case"top right":case"right top":this.classList.add("fab--top__right");break;case"top left":case"left top":this.classList.add("fab--top__left");break;case"bottom right":case"right bottom":this.classList.add("fab--bottom__right");break;case"bottom left":case"left bottom":this.classList.add("fab--bottom__left");break;case"center top":case"top center":this.classList.add("fab--top__center");break;case"center bottom":case"bottom center":this.classList.add("fab--bottom__center")}}},{key:"show",value:function(){arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.style.transform="scale(1)",this.style.webkitTransform="scale(1)"}},{key:"hide",value:function(){arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.style.transform="scale(0)",this.style.webkitTransform="scale(0)"}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"isInline",value:function(){return this.hasAttribute("inline")}},{key:"isShown",value:function(){return"scale(1)"===this.style.transform&&"none"!==this.style.display}},{key:"toggle",value:function(){this.isShown()?this.hide():this.show()}}]),FabElement}(ons._BaseElement);window.OnsFabElement||(window.OnsFabElement=document.registerElement("ons-fab",{prototype:FabElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var GestureDetectorElement=function(_ons$_BaseElement){function GestureDetectorElement(){_classCallCheck(this,GestureDetectorElement),_get(Object.getPrototypeOf(GestureDetectorElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(GestureDetectorElement,_ons$_BaseElement),_createClass(GestureDetectorElement,[{key:"createdCallback",value:function(){this._gestureDetector=new ons.GestureDetector(this)}}]),GestureDetectorElement}(ons._BaseElement);window.OnsGestureDetectorElement||(window.OnsGestureDetectorElement=document.registerElement("ons-gesture-detector",{prototype:GestureDetectorElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var IconElement=function(_ons$_BaseElement){function IconElement(){_classCallCheck(this,IconElement),_get(Object.getPrototypeOf(IconElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(IconElement,_ons$_BaseElement),_createClass(IconElement,[{key:"createdCallback",value:function(){this._update()}},{key:"attributeChangedCallback",value:function(name,last,current){-1!==["icon","size"].indexOf(name)&&this._update()}},{key:"_update",value:function(){var _this=this;this._cleanClassAttribute();var builded=this._buildClassAndStyle(this);for(var key in builded.style)builded.style.hasOwnProperty(key)&&(this.style[key]=builded.style[key]);builded.classList.forEach(function(className){return _this.classList.add(className)})}},{key:"_cleanClassAttribute",value:function(){var classList=this.classList;Array.apply(null,this.classList).filter(function(klass){return"fa"===klass||0===klass.indexOf("fa-")||0===klass.indexOf("ion-")||0===klass.indexOf("zmdi-")}).forEach(function(className){classList.remove(className)}),classList.remove("zmdi"),classList.remove("ons-icon--ion")}},{key:"_buildClassAndStyle",value:function(){var classList=["ons-icon"],style={},iconName=this._iconName;0===iconName.indexOf("ion-")?(classList.push(iconName),classList.push("ons-icon--ion")):0===iconName.indexOf("fa-")?(classList.push(iconName),classList.push("fa")):0===iconName.indexOf("md-")?(classList.push("zmdi"),classList.push("zmdi-"+iconName.split(/\-(.+)?/)[1])):(classList.push("fa"),classList.push("fa-"+iconName));var size=""+this.getAttribute("size");return size.match(/^[1-5]x|lg$/)?(classList.push("fa-"+size),this.style.removeProperty("font-size")):style.fontSize=size,{classList:classList,style:style}}},{key:"_iconName",get:function(){return""+this.getAttribute("icon")}}]),IconElement}(ons._BaseElement);window.OnsIconElement||(window.OnsIconElement=document.registerElement("ons-icon",{prototype:IconElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var scheme={"":"list__header--*"},ModifierUtil=ons._internal.ModifierUtil,ListHeaderElement=function(_ons$_BaseElement){function ListHeaderElement(){_classCallCheck(this,ListHeaderElement),_get(Object.getPrototypeOf(ListHeaderElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ListHeaderElement,_ons$_BaseElement),_createClass(ListHeaderElement,[{key:"createdCallback",value:function(){this.classList.add("list__header"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ListHeaderElement}(ons._BaseElement);window.OnsListHeaderElement||(window.OnsListHeaderElement=document.registerElement("ons-list-header",{prototype:ListHeaderElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var scheme={"":"list__item--*"},ModifierUtil=ons._internal.ModifierUtil,ListItemElement=function(_ons$_BaseElement){function ListItemElement(){_classCallCheck(this,ListItemElement),_get(Object.getPrototypeOf(ListItemElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ListItemElement,_ons$_BaseElement),_createClass(ListItemElement,[{key:"createdCallback",value:function(){this.classList.add("list__item"),ModifierUtil.initModifier(this,scheme),this._gestureDetector=new ons.GestureDetector(this),this._boundOnDrag=this._onDrag.bind(this)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"attachedCallback",value:function(){this.addEventListener("drag",this._boundOnDrag)}},{key:"detachedCallback",value:function(){this.removeEventListener("drag",this._boundOnDrag)}},{key:"_onDrag",value:function(event){var g=event.gesture;this._shouldLockOnDrag()&&["left","right"].indexOf(g.direction)>-1&&g.preventDefault()}},{key:"_shouldLockOnDrag",value:function(){return this.hasAttribute("lock-on-drag")}}]),ListItemElement}(ons._BaseElement);window.OnsListItemElement||(window.OnsListItemElement=document.registerElement("ons-list-item",{prototype:ListItemElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var scheme={"":"list--*"},ModifierUtil=ons._internal.ModifierUtil,ListElement=function(_ons$_BaseElement){function ListElement(){_classCallCheck(this,ListElement),_get(Object.getPrototypeOf(ListElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ListElement,_ons$_BaseElement),_createClass(ListElement,[{key:"createdCallback",value:function(){this.classList.add("list"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ListElement}(ons._BaseElement);window.OnsListElement||(window.OnsListElement=document.registerElement("ons-list",{prototype:ListElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var scheme={".text-input--material":"text-input--material--*",".text-input--material__label":"text-input--material__label--*"},ModifierUtil=ons._internal.ModifierUtil,INPUT_ATTRIBUTES=["autocapitalize","autocomplete","autocorrect","autofocus","disabled","inputmode","max","maxlength","min","minlength","name","pattern","placeholder","readonly","size","step","type","validator","value"],MaterialInputElement=function(_ons$_BaseElement){function MaterialInputElement(){_classCallCheck(this,MaterialInputElement),_get(Object.getPrototypeOf(MaterialInputElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(MaterialInputElement,_ons$_BaseElement),_createClass(MaterialInputElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this._updateLabel(),this._updateLabelColor(),this._updateBoundAttributes(),this._boundOnInput=this._onInput.bind(this),this._boundOnFocusin=this._onFocusin.bind(this),this._boundOnFocusout=this._onFocusout.bind(this)}},{key:"_compile",value:function(){this.appendChild(document.createElement("input")),this._input.classList.add("text-input--material"),this.appendChild(document.createElement("span")),this._label.classList.add("text-input--material__label")}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):"label"===name?this._updateLabel():INPUT_ATTRIBUTES.indexOf(name)>=0?this._updateBoundAttributes():void 0}},{key:"attachedCallback",value:function(){this._input.addEventListener("input",this._boundOnInput),this._input.addEventListener("focusin",this._boundOnFocusin),this._input.addEventListener("focusout",this._boundOnFocusout)}},{key:"detachedCallback",value:function(){this._input.removeEventListener("input",this._boundOnInput),this._input.removeEventListener("focusin",this._boundOnFocusin),this._input.removeEventListener("focusout",this._boundOnFocusout)}},{key:"_setLabel",value:function(value){"undefined"!=typeof this._label.textContent?this._label.textContent=value:this._label.innerText=value}},{key:"_updateLabel",value:function(){this._setLabel(this.hasAttribute("label")?this.getAttribute("label"):"")}},{key:"_updateBoundAttributes",value:function(){var _this=this;INPUT_ATTRIBUTES.forEach(function(attr){_this.hasAttribute(attr)?_this._input.setAttribute(attr,_this.getAttribute(attr)):_this._input.removeAttribute(attr)})}},{key:"_updateLabelColor",value:function(){this.value.length>0&&this._input===document.activeElement?this._label.style.color="":this._label.style.color="rgba(0, 0, 0, 0.5)"}},{key:"_onInput",value:function(event){""===this.value?this._label.classList.remove("text-input--material__label--active"):this._label.classList.add("text-input--material__label--active"),this._updateLabelColor()}},{key:"_onFocusin",value:function(event){this._updateLabelColor()}},{key:"_onFocusout",value:function(event){this._updateLabelColor()}},{key:"_input",get:function(){return this.querySelector("input")}},{key:"_label",get:function(){return this.querySelector("span")}},{key:"value",get:function(){return this._input.value},set:function(val){return this._input.value=val,this._onInput(),this._input.val}}]),MaterialInputElement}(ons._BaseElement);window.OnsMaterialInputElement||(window.OnsMaterialInputElement=document.registerElement("ons-material-input",{prototype:MaterialInputElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0}};!function(){"use strict";var scheme={"":"modal--*",modal__content:"modal--*__content"},AnimatorFactory=ons._internal.AnimatorFactory,ModalAnimator=ons._internal.ModalAnimator,FadeModalAnimator=ons._internal.FadeModalAnimator,ModifierUtil=ons._internal.ModifierUtil,util=ons._util,ModalElement=function(_ons$_BaseElement){function ModalElement(){_classCallCheck(this,ModalElement),_get(Object.getPrototypeOf(ModalElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ModalElement,_ons$_BaseElement),_createClass(ModalElement,[{key:"createdCallback",value:function(){this._doorLock=new DoorLock,this._animatorFactory=new AnimatorFactory({animators:OnsModalElement._animatorDict,baseClass:ModalAnimator,baseClassName:"ModalAnimator",defaultAnimation:this.getAttribute("animation")}),this._compile(),ModifierUtil.initModifier(this,scheme)}},{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler}},{key:"setDeviceBackButtonHandler",value:function(callback){this._deviceBackButtonHandler&&this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,callback),this._onDeviceBackButton=callback}},{key:"_onDeviceBackButton",value:function(){}},{key:"_compile",value:function(){this.style.display="none",this.classList.add("modal");var wrapper=document.createElement("div");for(wrapper.classList.add("modal__content");this.childNodes[0];){var node=this.childNodes[0];this.removeChild(node),wrapper.insertBefore(node,null)}this.appendChild(wrapper)}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler&&this._deviceBackButtonHandler.destroy()}},{key:"attachedCallback",value:function(){setImmediate(this._ensureNodePosition.bind(this)),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this))}},{key:"_ensureNodePosition",value:function(){if(this.parentNode&&!this.hasAttribute("inline")&&"ons-page"!==this.parentNode.nodeName.toLowerCase()){for(var page=this;;){if(page=page.parentNode,!page)return;if("ons-page"===page.nodeName.toLowerCase())break}page._registerExtraElement(this)}}},{key:"isShown",value:function(){return"none"!==this.style.display}},{key:"show",value:function(){var _this=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var callback=options.callback||function(){};this._doorLock.waitUnlock(function(){var unlock=_this._doorLock.lock(),animator=_this._animatorFactory.newAnimator(options);_this.style.display="table",animator.show(_this,function(){unlock(),callback()})})}},{key:"toggle",value:function(){return this.isShown()?this.hide.apply(this,arguments):this.show.apply(this,arguments)}},{key:"hide",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var callback=options.callback||function(){};this._doorLock.waitUnlock(function(){var unlock=_this2._doorLock.lock(),animator=_this2._animatorFactory.newAnimator(options);animator.hide(_this2,function(){_this2.style.display="none",unlock(),callback()})})}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ModalElement}(ons._BaseElement);window.OnsModalElement||(window.OnsModalElement=document.registerElement("ons-modal",{prototype:ModalElement.prototype}),window.OnsModalElement._animatorDict={"default":ModalAnimator,fade:FadeModalAnimator,none:ModalAnimator},window.OnsModalElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof ModalAnimator))throw new Error('"Animator" param must inherit ModalAnimator');this._animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var AnimatorFactory=ons._internal.AnimatorFactory,NavigatorTransitionAnimator=ons._internal.NavigatorTransitionAnimator,IOSSlideNavigatorTransitionAnimator=ons._internal.IOSSlideNavigatorTransitionAnimator,SimpleSlideNavigatorTransitionAnimator=ons._internal.SimpleSlideNavigatorTransitionAnimator,LiftNavigatorTransitionAnimator=ons._internal.LiftNavigatorTransitionAnimator,FadeNavigatorTransitionAnimator=ons._internal.FadeNavigatorTransitionAnimator,NoneNavigatorTransitionAnimator=ons._internal.NoneNavigatorTransitionAnimator,util=ons._util,NavigatorPage=ons._internal.NavigatorPage,NavigatorElement=function(_ons$_BaseElement){function NavigatorElement(){_classCallCheck(this,NavigatorElement),_get(Object.getPrototypeOf(NavigatorElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(NavigatorElement,_ons$_BaseElement),_createClass(NavigatorElement,[{key:"createdCallback",value:function(){this._doorLock=new DoorLock,this._pages=[],this._boundOnDeviceBackButton=this._onDeviceBackButton.bind(this),this._isPushing=this._isPopping=!1,this._initialHTML=this.innerHTML,this.innerHTML="",this._animatorFactory=new AnimatorFactory({animators:window.OnsNavigatorElement._transitionAnimatorDict,baseClass:NavigatorTransitionAnimator,baseClassName:"NavigatorTransitionAnimator",defaultAnimation:this.getAttribute("animation")})}},{key:"canPopPage",value:function(){return this._pages.length>1}},{key:"replacePage",value:function(page,options){var _this=this;options=options||{};var onTransitionEnd=options.onTransitionEnd||function(){};return options.onTransitionEnd=function(){_this._pages.length>1&&_this._pages[_this._pages.length-2].destroy(),onTransitionEnd()},this.pushPage(page,options)}},{key:"popPage",value:function(options){var _this2=this;options=options||{},options.cancelIfRunning&&this._isPopping||(options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),this._doorLock.waitUnlock(function(){if(_this2._pages.length<=1)throw new Error("ons-navigator's page stack is empty.");if(!_this2._emitPrePopEvent()){var unlock=_this2._doorLock.lock();options.refresh?!function(){var index=_this2.pages.length-2;if(!_this2._pages[index].page)throw new Error("Refresh option cannot be used with pages directly inside the Navigator. Use ons-template instead.");ons._internal.getPageHTMLAsync(_this2._pages[index].page).then(function(templateHTML){var element=_this2._createPageElement(templateHTML),pageObject=_this2._createPageObject(_this2._pages[index].page,element,options);window.OnsNavigatorElement.rewritables.link(_this2,element,function(element){_this2.insertBefore(element,_this2._pages[index]?_this2._pages[index].element:null),_this2._pages.splice(index,0,pageObject),_this2._pages[index+1].destroy(),_this2._popPage(options,unlock)})})}():_this2._popPage(options,unlock)}}))}},{key:"_popPage",value:function(options,unlock){var _this3=this;options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var leavePage=this._pages.pop(),enterPage=this._pages[this._pages.length-1];leavePage.element._hide(),enterPage&&(enterPage.element.style.display="block",enterPage.element._show());var eventDetail={leavePage:leavePage,enterPage:this._pages[this._pages.length-1],navigator:this},callback=function(){leavePage.destroy(),_this3._isPopping=!1,unlock();var event=util.triggerElementEvent(_this3,"postpop",eventDetail);event.leavePage=null,"function"==typeof options.onTransitionEnd&&options.onTransitionEnd()};this._isPopping=!0;var animator=this._animatorFactory.newAnimator(options,leavePage.options.animator);animator.pop(enterPage,leavePage,callback)}},{key:"insertPage",value:function(index,page,options){var _this4=this;if(options=options||{},options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);return index=this._normalizeIndex(index),index>=this.pages.length?this.pushPage.apply(this,[].slice.call(arguments,1)):void this._doorLock.waitUnlock(function(){var unlock=_this4._doorLock.lock();ons._internal.getPageHTMLAsync(page).then(function(templateHTML){var element=_this4._createPageElement(templateHTML),pageObject=_this4._createPageObject(page,element,options);window.OnsNavigatorElement.rewritables.link(_this4,element,function(element){element.style.display="none",_this4.insertBefore(element,_this4._pages[index].element),_this4._pages.splice(index,0,pageObject),setTimeout(function(){unlock(),element=null},1e3/60)})})})}},{key:"_normalizeIndex",value:function(index){return 0>index&&(index=Math.abs(this.pages.length+index)%this.pages.length),index}},{key:"getCurrentPage",value:function(){if(this._pages.length<=0)throw new Error("Invalid state");return this._pages[this._pages.length-1]}},{key:"_show",value:function(){this._pages[this._pages.length-1]&&this._pages[this._pages.length-1].element._show()}},{key:"_hide",value:function(){this._pages[this._pages.length-1]&&this._pages[this._pages.length-1].element._hide()}},{key:"_destroy",value:function(){for(var i=this._pages.length-1;i>=0;i--)this._pages[i].destroy();this.remove()}},{key:"_onDeviceBackButton",value:function(event){this._pages.length>1?this.popPage():event.callParentHandler()}},{key:"resetToPage",value:function(page,options){var _this5=this;options=options||{},options.animator||options.animation||(options.animation="none");var onTransitionEnd=options.onTransitionEnd||function(){};options.onTransitionEnd=function(){for(;_this5._pages.length>1;)_this5._pages.shift().destroy();onTransitionEnd()},(void 0===page||""===page)&&(this.hasAttribute("page")?page=this.getAttribute("page"):(options.pageHTML=this._initialHTML,page="")),this.pushPage(page,options)}},{key:"attributeChangedCallback",value:function(name,last,current){}},{key:"attachedCallback",value:function(){var _this6=this;this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._boundOnDeviceBackButton),window.OnsNavigatorElement.rewritables.ready(this,function(){if(0===_this6._pages.length)if(_this6.getAttribute("page"))_this6.pushPage(_this6.getAttribute("page"),{animation:"none"});else{var element=_this6._createPageElement(_this6._initialHTML||"");_this6._pushPageDOM(_this6._createPageObject("",element,{}),function(){})}})}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null}},{key:"pushPage",value:function(page,options){var _this7=this;if(options=options||{},options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))),!options.cancelIfRunning||!this._isPushing){if(options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);this._emitPrePushEvent()||this._doorLock.waitUnlock(function(){return _this7._pushPage(page,options)})}}},{key:"_pushPage",value:function(page,options){var _this8=this,unlock=this._doorLock.lock(),done=function(){unlock()},run=function(templateHTML){var element=_this8._createPageElement(templateHTML);_this8._pushPageDOM(_this8._createPageObject(page,element,options),done)};options.pageHTML?run(options.pageHTML):ons._internal.getPageHTMLAsync(page).then(run)}},{key:"_pushPageDOM",value:function(pageObject,unlock){var _this9=this;unlock=unlock||function(){};var element=pageObject.element,options=pageObject.options,eventDetail={enterPage:pageObject,leavePage:this._pages[this._pages.length-1],navigator:this};this._pages.push(pageObject);var done=function(){_this9._pages[_this9._pages.length-2]&&(_this9._pages[_this9._pages.length-2].element.style.display="none"),_this9._isPushing=!1,unlock(),util.triggerElementEvent(_this9,"postpush",eventDetail),"function"==typeof options.onTransitionEnd&&options.onTransitionEnd(),element=null};this._isPushing=!0,window.OnsNavigatorElement.rewritables.link(this,element,function(element){setTimeout(function(){if(_this9._pages.length>1){var leavePage=_this9._pages.slice(-2)[0],enterPage=_this9._pages.slice(-1)[0];_this9.appendChild(element),leavePage.element._hide(),enterPage.element._show(),options.animator.push(enterPage,leavePage,done)}else _this9.appendChild(element),element._show(),done()},1e3/60)})}},{key:"bringPageTop",value:function(item,options){var _this10=this;if(options=options||{},options&&"object"!=typeof options)throw new Error("options must be an object. You supplied "+options);if(!(options.cancelIfRunning&&this._isPushing||this._emitPrePushEvent())){var index=void 0,page=void 0;if("string"==typeof item)page=item,index=this._lastIndexOfPage(page);else{if("number"!=typeof item)throw new Error("First argument must be a page name or the index of an existing page. You supplied "+item);if(index=this._normalizeIndex(item),item>=this._pages.length)throw new Error("The provided index does not match an existing page.");page=this._pages[index].page}0>index?this._doorLock.waitUnlock(function(){return _this10._pushPage(page,options)}):index<this._pages.length-1&&this._doorLock.waitUnlock(function(){var unlock=_this10._doorLock.lock(),done=function(){unlock()},pageObject=_this10._pages.splice(index,1)[0];pageObject.element.style.display="block", pageObject.element.setAttribute("_skipinit",""),options.animator=_this10._animatorFactory.newAnimator(options),pageObject.options=options,_this10._pushPageDOM(pageObject,done)})}}},{key:"_lastIndexOfPage",value:function(page){var index=void 0;for(index=this._pages.length-1;index>=0&&this._pages[index].page!==page;index--);return index}},{key:"_emitPrePushEvent",value:function(){var isCanceled=!1;return util.triggerElementEvent(this,"prepush",{navigator:this,currentPage:this._pages.length>0?this.getCurrentPage():void 0,cancel:function(){isCanceled=!0}}),isCanceled}},{key:"_emitPrePopEvent",value:function(){var isCanceled=!1,leavePage=this.getCurrentPage();return util.triggerElementEvent(this,"prepop",{navigator:this,currentPage:leavePage,leavePage:leavePage,enterPage:this._pages[this._pages.length-2],cancel:function(){isCanceled=!0}}),isCanceled}},{key:"_createPageObject",value:function(page,element,options){return options.animator=this._animatorFactory.newAnimator(options),new NavigatorPage({page:page,element:element,options:options,navigator:this})}},{key:"_createPageElement",value:function(templateHTML){var pageElement=util.createElement(ons._internal.normalizePageHTML(templateHTML));if("ons-page"!==pageElement.nodeName.toLowerCase())throw new Error('You must supply an "ons-page" element to "ons-navigator".');return pageElement}},{key:"pages",get:function(){return this._pages.slice(0)}}]),NavigatorElement}(ons._BaseElement);window.OnsNavigatorElement||(window.OnsNavigatorElement=document.registerElement("ons-navigator",{prototype:NavigatorElement.prototype}),window.OnsNavigatorElement._transitionAnimatorDict={"default":ons.platform.isAndroid()?SimpleSlideNavigatorTransitionAnimator:IOSSlideNavigatorTransitionAnimator,slide:ons.platform.isAndroid()?SimpleSlideNavigatorTransitionAnimator:IOSSlideNavigatorTransitionAnimator,simpleslide:SimpleSlideNavigatorTransitionAnimator,lift:LiftNavigatorTransitionAnimator,fade:FadeNavigatorTransitionAnimator,none:NoneNavigatorTransitionAnimator},window.OnsNavigatorElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof NavigatorTransitionAnimator))throw new Error('"Animator" param must inherit NavigatorTransitionAnimator');this._transitionAnimatorDict[name]=Animator},window.OnsNavigatorElement.rewritables={ready:function(navigatorElement,callback){callback()},link:function(navigatorElement,target,callback){callback(target)}})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var scheme={"":"page--*",".page__content":"page--*__content",".page__background":"page--*__background"},ModifierUtil=ons._internal.ModifierUtil,nullToolbarElement=document.createElement("ons-toolbar"),util=ons._util,PageElement=function(_ons$_BaseElement){function PageElement(){_classCallCheck(this,PageElement),_get(Object.getPrototypeOf(PageElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(PageElement,_ons$_BaseElement),_createClass(PageElement,[{key:"createdCallback",value:function(){this.classList.add("page"),this._compile(),ModifierUtil.initModifier(this,scheme),this._isShown=!1,this._isMuted=this.hasAttribute("_muted"),this._skipInit=this.hasAttribute("_skipinit"),this.eventDetail={page:this}}},{key:"attachedCallback",value:function(){this._isMuted||(this._skipInit?this.removeAttribute("_skipinit"):util.triggerElementEvent(this,"init",this.eventDetail)),util.hasAnyComponentAsParent(this)||this._show()}},{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler||null}},{key:"setDeviceBackButtonHandler",value:function(callback){this._deviceBackButtonHandler&&this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,callback)}},{key:"_getContentElement",value:function(){var result=ons._util.findChild(this,".page__content");if(result)return result;throw Error('fail to get ".page__content" element.')}},{key:"_hasToolbarElement",value:function(){return!!ons._util.findChild(this,"ons-toolbar")}},{key:"_canAnimateToolbar",value:function(){var toolbar=ons._util.findChild(this,"ons-toolbar");if(toolbar)return!0;for(var elements=this._getContentElement().children,i=0;i<elements.length;i++)if("ons-toolbar"===elements[i].nodeName.toLowerCase()&&!elements[i].hasAttribute("inline"))return!0;return!1}},{key:"_getBackgroundElement",value:function(){var result=ons._util.findChild(this,".page__background");if(result)return result;throw Error('fail to get ".page__background" element.')}},{key:"_getBottomToolbarElement",value:function(){return ons._util.findChild(this,"ons-bottom-toolbar")||ons._internal.nullElement}},{key:"_getToolbarElement",value:function(){return ons._util.findChild(this,"ons-toolbar")||nullToolbarElement}},{key:"_registerToolbar",value:function(element){this._getContentElement().setAttribute("no-status-bar-fill",""),ons._util.findChild(this,".page__status-bar-fill")?this.insertBefore(element,this.children[1]):this.insertBefore(element,this.children[0])}},{key:"_registerBottomToolbar",value:function(element){if(!ons._util.findChild(this,".page__status-bar-fill")){var fill=document.createElement("div");fill.classList.add("page__bottom-bar-fill"),fill.style.width="0px",fill.style.height="0px",this.insertBefore(fill,this.children[0]),this.insertBefore(element,null)}}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("_muted"===name?this._isMuted=this.hasAttribute("_muted"):"_skipinit"===name&&(this._skipInit=this.hasAttribute("_skipinit")))}},{key:"_compile",value:function(){if(!ons._util.findChild(this,".page__background")||!ons._util.findChild(this,".page__content")){var background=document.createElement("div");background.classList.add("page__background");var content=document.createElement("div");for(content.classList.add("page__content");this.childNodes[0];)content.appendChild(this.childNodes[0]);this.hasAttribute("style")&&(background.setAttribute("style",this.getAttribute("style")),this.removeAttribute("style",null));var fragment=document.createDocumentFragment();fragment.appendChild(background),fragment.appendChild(content),this.appendChild(fragment)}}},{key:"_registerExtraElement",value:function(element){var extra=ons._util.findChild(this,".page__extra");extra||(extra=document.createElement("div"),extra.classList.add("page__extra"),extra.style.zIndex="10001",this.insertBefore(extra,null)),extra.insertBefore(element,null)}},{key:"_tryToFillStatusBar",value:function(){if(ons._internal.shouldFillStatusBar(this)){var fill=document.createElement("div");fill.classList.add("page__status-bar-fill"),fill.style.width="0px",fill.style.height="0px",this.insertBefore(fill,this.children[0])}}},{key:"_show",value:function(){!this.isShown&&ons._util.isAttached(this)&&(this.isShown=!0,this._isMuted||util.triggerElementEvent(this,"show",this.eventDetail),ons._util.propagateAction(this._getContentElement(),"_show"))}},{key:"_hide",value:function(){this.isShown&&(this.isShown=!1,this._isMuted||util.triggerElementEvent(this,"hide",this.eventDetail),ons._util.propagateAction(this._getContentElement(),"_hide"))}},{key:"_destroy",value:function(){this._hide(),this._isMuted||util.triggerElementEvent(this,"destroy",this.eventDetail),this.getDeviceBackButtonHandler()&&this.getDeviceBackButtonHandler().destroy(),ons._util.propagateAction(this._getContentElement(),"_destroy"),this.remove()}},{key:"isShown",get:function(){return this._isShown},set:function(value){this._isShown=value}}]),PageElement}(ons._BaseElement);window.OnsPageElement||(window.OnsPageElement=document.registerElement("ons-page",{prototype:PageElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={".popover":"popover--*",".popover__content":"popover__content--*"},PopoverAnimator=ons._internal.PopoverAnimator,FadePopoverAnimator=ons._internal.FadePopoverAnimator,templateSource=util.createElement('\n <div>\n <div class="popover-mask"></div>\n <div class="popover">\n <div class="popover__content"></div>\n <div class="popover__arrow"></div>\n </div>\n </div>\n '),AnimatorFactory=ons._internal.AnimatorFactory,PopoverElement=function(_ons$_BaseElement){function PopoverElement(){_classCallCheck(this,PopoverElement),_get(Object.getPrototypeOf(PopoverElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(PopoverElement,_ons$_BaseElement),_createClass(PopoverElement,[{key:"createdCallback",value:function(){this._compile(),this.style.display="none",ModifierUtil.initModifier(this,scheme),this._mask.style.zIndex="20000",this._popover.style.zIndex="20001",this.hasAttribute("mask-color")&&(this._mask.style.backgroundColor=this.getAttribute("mask-color")),this._visible=!1,this._doorLock=new DoorLock,this._boundOnChange=this._onChange.bind(this),this._boundCancel=this._cancel.bind(this),this._animatorFactory=this._createAnimatorFactory()}},{key:"_createAnimatorFactory",value:function(){return new AnimatorFactory({animators:window.OnsPopoverElement._animatorDict,baseClass:PopoverAnimator,baseClassName:"PopoverAnimator",defaultAnimation:this.getAttribute("animation")||"fade"})}},{key:"_onDeviceBackButton",value:function(event){this.isCancelable()?this._cancel():event.callParentHandler()}},{key:"_setDirection",value:function(direction){var arrowPosition=void 0;if("up"===direction)arrowPosition="bottom";else if("left"===direction)arrowPosition="right";else if("down"===direction)arrowPosition="top";else{if("right"!=direction)throw new Error("Invalid direction.");arrowPosition="left"}var popoverClassList=this._popover.classList;popoverClassList.remove("popover--up"),popoverClassList.remove("popover--down"),popoverClassList.remove("popover--left"),popoverClassList.remove("popover--right"),popoverClassList.add("popover--"+direction);var arrowClassList=this._arrow.classList;arrowClassList.remove("popover__top-arrow"),arrowClassList.remove("popover__bottom-arrow"),arrowClassList.remove("popover__left-arrow"),arrowClassList.remove("popover__right-arrow"),arrowClassList.add("popover__"+arrowPosition+"-arrow")}},{key:"_positionPopoverByDirection",value:function(target,direction){var el=this._popover,pos=target.getBoundingClientRect(),own=el.getBoundingClientRect(),arrow=el.children[1],offset=14,margin=6,radius=parseInt(window.getComputedStyle(el.querySelector(".popover__content")).borderRadius);arrow.style.top="",arrow.style.left="",this._setDirection(direction),["left","right"].indexOf(direction)>-1?("left"==direction?el.style.left=pos.right-pos.width-own.width-offset+"px":el.style.left=pos.right+offset+"px",el.style.top=pos.bottom-pos.height/2-own.height/2+"px"):("up"==direction?el.style.top=pos.bottom-pos.height-own.height-offset+"px":el.style.top=pos.bottom+offset+"px",el.style.left=pos.right-pos.width/2-own.width/2+"px"),own=el.getBoundingClientRect();var diff=function(x){return x/2*Math.sqrt(2)-x/2}(parseInt(window.getComputedStyle(arrow).width)),limit=margin+radius+diff+2;["left","right"].indexOf(direction)>-1?own.top<margin?(arrow.style.top=Math.max(own.height/2+own.top-margin,limit)+"px",el.style.top=margin+"px"):own.bottom>window.innerHeight-margin&&(arrow.style.top=Math.min(own.height/2-(window.innerHeight-own.bottom)+margin,own.height-limit)+"px",el.style.top=window.innerHeight-own.height-margin+"px"):own.left<margin?(arrow.style.left=Math.max(own.width/2+own.left-margin,limit)+"px",el.style.left=margin+"px"):own.right>window.innerWidth-margin&&(arrow.style.left=Math.min(own.width/2-(window.innerWidth-own.right)+margin,own.width-limit)+"px",el.style.left=window.innerWidth-own.width-margin+"px"),el.removeAttribute("data-animit-orig-style")}},{key:"_positionPopover",value:function(target){for(var _this=this,directions=function(){return _this.hasAttribute("direction")?_this.getAttribute("direction").split(/\s+/):["up","down","left","right"]}(),position=target.getBoundingClientRect(),scores={left:position.left,right:window.innerWidth-position.right,up:position.top,down:window.innerHeight-position.bottom},orderedDirections=Object.keys(scores).sort(function(a,b){return-(scores[a]-scores[b])}),i=0,l=orderedDirections.length;l>i;i++){var direction=orderedDirections[i];if(directions.indexOf(direction)>-1)return void this._positionPopoverByDirection(target,direction)}}},{key:"_onChange",value:function(){var _this2=this;setImmediate(function(){_this2._currentTarget&&_this2._positionPopover(_this2._currentTarget)})}},{key:"_compile",value:function(){var templateElement=templateSource.cloneNode(!0),content=templateElement.querySelector(".popover__content"),style=this.getAttribute("style");for(style&&this.removeAttribute("style");this.childNodes[0];)content.appendChild(this.childNodes[0]);for(;templateElement.children[0];)this.appendChild(templateElement.children[0]);style&&this._popover.setAttribute("style",style)}},{key:"show",value:function(target,options){var _this3=this;if("string"==typeof target?target=document.querySelector(target):target instanceof Event&&(target=target.target),!target)throw new Error("Target undefined");if(options=options||{},options.animation&&!(options.animation in window.OnsPopoverElement._animatorDict))throw new Error("Animator "+options.animation+" is not registered.");options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var canceled=!1;util.triggerElementEvent(this,"preshow",{popover:this,cancel:function(){canceled=!0}}),canceled||this._doorLock.waitUnlock(function(){var unlock=_this3._doorLock.lock();_this3.style.display="block",_this3._currentTarget=target,_this3._positionPopover(target);var animator=_this3._animatorFactory.newAnimator(options);animator.show(_this3,function(){_this3._visible=!0,unlock(),util.triggerElementEvent(_this3,"postshow",{popover:_this3})})})}},{key:"hide",value:function(options){var _this4=this;options=options||{};var canceled=!1;util.triggerElementEvent(this,"prehide",{popover:this,cancel:function(){canceled=!0}}),canceled||this._doorLock.waitUnlock(function(){var unlock=_this4._doorLock.lock(),animator=_this4._animatorFactory.newAnimator(options);animator.hide(_this4,function(){_this4.style.display="none",_this4._visible=!1,unlock(),util.triggerElementEvent(_this4,"posthide",{popover:_this4})})})}},{key:"isShown",value:function(){return this._visible}},{key:"attachedCallback",value:function(){this._mask.addEventListener("click",this._boundCancel,!1),this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._onDeviceBackButton.bind(this)),this._popover.addEventListener("DOMNodeInserted",this._boundOnChange,!1),this._popover.addEventListener("DOMNodeRemoved",this._boundOnChange,!1),window.addEventListener("resize",this._boundOnChange,!1)}},{key:"detachedCallback",value:function(){this._mask.removeEventListener("click",this._boundCancel,!1),this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this._popover.removeEventListener("DOMNodeInserted",this._boundOnChange,!1),this._popover.removeEventListener("DOMNodeRemoved",this._boundOnChange,!1),window.removeEventListener("resize",this._boundOnChange,!1)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("direction"===name?this._boundOnChange():("animation"===name||"animation-options"===name)&&(this._animatorFactory=this._createAnimatorFactory()))}},{key:"setCancelable",value:function(cancelable){if("boolean"!=typeof cancelable)throw new Error("Argument must be a boolean.");cancelable?this.setAttribute("cancelable",""):this.removeAttribute("cancelable")}},{key:"isCancelable",value:function(){return this.hasAttribute("cancelable")}},{key:"destroy",value:function(){this.parentElement&&this.parentElement.removeChild(this)}},{key:"_cancel",value:function(){this.isCancelable()&&this.hide()}},{key:"_mask",get:function(){return this.children[0]}},{key:"_popover",get:function(){return this.children[1]}},{key:"_content",get:function(){return this._popover.children[0]}},{key:"_arrow",get:function(){return this._popover.children[1]}}]),PopoverElement}(ons._BaseElement);window.OnsPopoverElement||(window.OnsPopoverElement=document.registerElement("ons-popover",{prototype:PopoverElement.prototype}),window.OnsPopoverElement._animatorDict={fade:FadePopoverAnimator,none:PopoverAnimator},window.OnsPopoverElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof PopoverAnimator))throw new Error('"Animator" param must inherit PopoverAnimator');this._animatorDict[name]=Animator})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var util=ons._util,ModifierUtil=ons._internal.ModifierUtil,scheme={".progress-bar":"progress-bar--*",".progress-circular":"progress-circular--*",".progress-circular__primary":"progress-circular__primary--*",".progress-circular__secondary":"progress-circular__secondary--*",".progress-bar__primary":"progress-bar__primary--*",".progress-bar__secondary":"progress-bar__secondary--*"},barTemplate=util.createElement('\n <div class="progress-bar">\n <div class="progress-bar__secondary"></div>\n <div class="progress-bar__primary"></div>\n </div>\n '),circularTemplate=util.createElement('\n <svg class="progress-circular">\n <circle class="progress-circular__secondary" cx="50%" cy="50%" r="40%" fill="none" stroke-width="10%" stroke-miterlimit="10"/>\n <circle class="progress-circular__primary" cx="50%" cy="50%" r="40%" fill="none" stroke-width="10%" stroke-miterlimit="10"/>\n </svg>\n '),ProgressElement=function(_ons$_BaseElement){function ProgressElement(){_classCallCheck(this,ProgressElement),_get(Object.getPrototypeOf(ProgressElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ProgressElement,_ons$_BaseElement),_createClass(ProgressElement,[{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){if("modifier"===name)return ModifierUtil.onModifierChanged(last,current,this,scheme);if("value"===name||"secondary-value"===name)this._updateValue();else{if("type"===name)throw new Error("Can not change type attribute.");"indeterminate"===name&&this._updateDeterminate()}}},{key:"_updateDeterminate",value:function(){this.hasAttribute("indeterminate")?(this._template.classList.add("progress-"+this._type+"--indeterminate"),this._template.classList.remove("progress-"+this._type+"--determinate")):(this._template.classList.add("progress-"+this._type+"--determinate"),this._template.classList.remove("progress-"+this._type+"--indeterminate"))}},{key:"_updateValue",value:function(){if("bar"===this._type)this._primary.style.width=this.hasAttribute("value")?this.getAttribute("value")+"%":"0%",this._secondary.style.width=this.hasAttribute("secondary-value")?this.getAttribute("secondary-value")+"%":"0%";else{if(this.hasAttribute("value")){var per=Math.ceil(251.32*this.getAttribute("value")*.01);this._primary.style["stroke-dasharray"]=per+"%, 251.32%"}if(this.hasAttribute("secondary-value")){var per=Math.ceil(251.32*this.getAttribute("secondary-value")*.01);this._secondary.style["stroke-dasharray"]=per+"%, 251.32%"}}}},{key:"_compile",value:function(){"bar"===this._type?this._template=barTemplate.cloneNode(!0):this._template=circularTemplate.cloneNode(!0),this._primary=this._template.children[1],this._secondary=this._template.children[0],this._updateDeterminate(),this._updateValue(),this.appendChild(this._template)}},{key:"_type",get:function(){return this.hasAttribute("type")&&"circular"===this.getAttribute("type")?"circular":"bar"}}]),ProgressElement}(ons._BaseElement);window.OnsProgressElement||(window.OnsProgressElement=document.registerElement("ons-progress",{prototype:ProgressElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x2,_x3,_x4){for(var _again=!0;_again;){var object=_x2,property=_x3,receiver=_x4;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x2=parent,_x3=property,_x4=receiver,_again=!0}};!function(){"use strict";var STATE_INITIAL="initial",STATE_PREACTION="preaction",STATE_ACTION="action",util=ons._util,PullHookElement=function(_ons$_BaseElement){function PullHookElement(){_classCallCheck(this,PullHookElement),_get(Object.getPrototypeOf(PullHookElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(PullHookElement,_ons$_BaseElement),_createClass(PullHookElement,[{key:"createdCallback",value:function(){if(this._scrollElement=this._createScrollElement(),this._pageElement=this._scrollElement.parentElement,!this._pageElement.classList.contains("page__content")&&!this._pageElement.classList.contains("ons-scroller__content"))throw new Error("<ons-pull-hook> must be a direct descendant of an <ons-page> or an <ons-scroller> element.");this._boundOnDrag=this._onDrag.bind(this),this._boundOnDragStart=this._onDragStart.bind(this),this._boundOnDragEnd=this._onDragEnd.bind(this),this._boundOnScroll=this._onScroll.bind(this),this._currentTranslation=0,this._setState(STATE_INITIAL,!0),this._setStyle()}},{key:"_createScrollElement",value:function(){var scrollElement=util.createElement('<div class="scroll"><div>'),pageElement=this.parentElement;for(scrollElement.appendChild(this);pageElement.firstChild;)scrollElement.appendChild(pageElement.firstChild);return pageElement.appendChild(scrollElement),scrollElement}},{key:"_setStyle",value:function(){var height=this.getHeight();this.style.top="-"+height+"px",this.style.height=height+"px",this.style.lineHeight=height+"px"}},{key:"_onScroll",value:function(event){var element=this._pageElement;element.scrollTop<0&&(element.scrollTop=0)}},{key:"_generateTranslationTransform",value:function(scroll){return"translate3d(0px, "+scroll+"px, 0px)"}},{key:"_onDrag",value:function(event){var _this=this;if(!this.isDisabled()&&"left"!==event.gesture.direction&&"right"!==event.gesture.direction){var element=this._pageElement;if(element.scrollTop=this._startScroll-event.gesture.deltaY,element.scrollTop<window.innerHeight&&"up"!==event.gesture.direction&&event.gesture.preventDefault(),0===this._currentTranslation&&0===this._getCurrentScroll()){this._transitionDragLength=event.gesture.deltaY;var direction=event.gesture.interimDirection;"down"===direction?this._transitionDragLength-=1:this._transitionDragLength+=1}var scroll=Math.max(event.gesture.deltaY-this._startScroll,0);this._thresholdHeightEnabled()&&scroll>=this.getThresholdHeight()?(event.gesture.stopDetect(),setImmediate(function(){_this._setState(STATE_ACTION),_this._translateTo(_this.getHeight(),{animate:!0}),_this._waitForAction(_this._onDone.bind(_this))})):scroll>=this.getHeight()?this._setState(STATE_PREACTION):this._setState(STATE_INITIAL),event.stopPropagation(),this._translateTo(scroll)}}},{key:"_onDragStart",value:function(event){this.isDisabled()||(this._startScroll=this._getCurrentScroll())}},{key:"_onDragEnd",value:function(event){if(!this.isDisabled()&&this._currentTranslation>0){var _scroll=this._currentTranslation;_scroll>this.getHeight()?(this._setState(STATE_ACTION),this._translateTo(this.getHeight(),{animate:!0}),this._waitForAction(this._onDone.bind(this))):this._translateTo(0,{animate:!0})}}},{key:"setActionCallback",value:function(callback){this._callback=callback}},{key:"_waitForAction",value:function(done){this._callback instanceof Function?this._callback.call(null,done):done()}},{key:"_onDone",value:function(done){this._translateTo(0,{animate:!0}),this._setState(STATE_INITIAL)}},{key:"getHeight",value:function(){return parseInt(this.getAttribute("height")||"64",10)}},{key:"setHeight",value:function(height){this.setAttribute("height",height+"px"),this._setStyle()}},{key:"setThresholdHeight",value:function(thresholdHeight){this.setAttribute("threshold-height",thresholdHeight+"px")}},{key:"getThresholdHeight",value:function(){return parseInt(this.getAttribute("threshold-height")||"96",10)}},{key:"_thresholdHeightEnabled",value:function(){var th=this.getThresholdHeight();return th>0&&th>=this.getHeight()}},{key:"_setState",value:function(state,noEvent){var lastState=this._getState();this.setAttribute("state",state),noEvent||lastState===this._getState()||util.triggerElementEvent(this,"changestate",{pullHook:this,state:state,lastState:lastState})}},{key:"_getState",value:function(){return this.getAttribute("state")}},{key:"getCurrentState",value:function(){return this._getState()}},{key:"_getCurrentScroll",value:function(){return this._pageElement.scrollTop}},{key:"getPullDistance",value:function(){return this._currentTranslation}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"_isContentFixed",value:function(){return this.hasAttribute("fixed-content")}},{key:"setDisabled",value:function(disabled){disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"_getScrollableElement",value:function(){return this._isContentFixed()?this:this._scrollElement}},{key:"_translateTo",value:function(scroll){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];this._currentTranslation=scroll,options.animate?animit(this._getScrollableElement()).queue({transform:this._generateTranslationTransform(scroll)},{duration:.3,timing:"cubic-bezier(.1, .7, .1, 1)"}).play(options.callback):animit(this._getScrollableElement()).queue({transform:this._generateTranslationTransform(scroll)}).play(options.callback)}},{key:"_getMinimumScroll",value:function(){var scrollHeight=this._scrollElement.getBoundingClientRect().height,pageHeight=this._pageElement.getBoundingClientRect().height;return scrollHeight>pageHeight?-(scrollHeight-pageHeight):0}},{key:"_createEventListeners",value:function(){this._gestureDetector=new ons.GestureDetector(this._pageElement,{dragMinDistance:1,dragDistanceCorrection:!1}),this._gestureDetector.on("drag",this._boundOnDrag),this._gestureDetector.on("dragstart",this._boundOnDragStart),this._gestureDetector.on("dragend",this._boundOnDragEnd),this._scrollElement.parentElement.addEventListener("scroll",this._boundOnScroll,!1)}},{key:"_destroyEventListeners",value:function(){this._gestureDetector.off("drag",this._boundOnDrag),this._gestureDetector.off("dragstart",this._boundOnDragStart),this._gestureDetector.off("dragend",this._boundOnDragEnd),this._gestureDetector.dispose(),this._gestureDetector=null,this._scrollElement.parentElement.removeEventListener("scroll",this._boundOnScroll,!1)}},{key:"attachedCallback",value:function(){this._createEventListeners()}},{key:"detachedCallback",value:function(){this._destroyEventListeners()}},{key:"attributeChangedCallback",value:function(name,last,current){}}]),PullHookElement}(ons._BaseElement);window.OnsPullHookElement||(window.OnsPullHookElement=document.registerElement("ons-pull-hook",{prototype:PullHookElement.prototype}),window.OnsPullHookElement.STATE_ACTION=STATE_ACTION,window.OnsPullHookElement.STATE_INITIAL=STATE_INITIAL,window.OnsPullHookElement.STATE_PREACTION=STATE_PREACTION)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var RippleElement=function(_ons$_BaseElement){function RippleElement(){_classCallCheck(this,RippleElement),_get(Object.getPrototypeOf(RippleElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(RippleElement,_ons$_BaseElement), _createClass(RippleElement,[{key:"createdCallback",value:function(){this.classList.add("ripple"),this._compile(),this._boundOnClick=this._onMouseDown.bind(this)}},{key:"_compile",value:function(){this._wave=document.createElement("span"),this._wave.classList.add("ripple__wave"),this.insertBefore(this._wave,this.children[0]),this.hasAttribute("color")&&(this._wave.style.background=this.getAttribute("color"))}},{key:"_updateTarget",value:function(){this.hasAttribute("target")&&"children"===this.getAttribute("target")?(this._target=this,this.style.display="inline-block",this.style.position="relative"):(this._target=this.parentNode,"static"===window.getComputedStyle(this._target).getPropertyValue("position")&&(this._target.style.position="relative"),this.style.display="block",this.style.position="absolute")}},{key:"_updateCenter",value:function(){this.hasAttribute("center")?this._center=!0:this._center=!1,this._wave.classList.remove("ripple__wave--done-center"),this._wave.classList.remove("ripple__wave--animate-center"),this._wave.classList.remove("ripple__wave--done"),this._wave.classList.remove("ripple__wave--animate")}},{key:"attributeChangedCallback",value:function(name,last,current){"target"===name&&this._updateTarget(),"color"===name&&(this._wave.style.background=current),"center"===name&&this._updateCenter()}},{key:"_isTouchDevice",value:function(){return"ontouchstart"in window||"onmsgesturechange"in window}},{key:"_addListener",value:function(){this._isTouchDevice()?this.addEventListener("touchstart",this._boundOnClick):this.addEventListener("mousedown",this._boundOnClick)}},{key:"_removeListener",value:function(){this._isTouchDevice()?this.removeEventListener("touchstart",this._boundOnClick):this.removeEventListener("mousedown",this._boundOnClick)}},{key:"attachedCallback",value:function(){this._updateCenter(),this._updateTarget(),this._addListener()}},{key:"detachedCallback",value:function(){this._removeListener()}},{key:"_onMouseDown",value:function(e){var _this=this,eventType=e.type,wave=this._wave,el=this._target,pos=el.getBoundingClientRect();if(!this.isDisabled()){this._center?(wave.classList.remove("ripple__wave--done-center"),wave.classList.remove("ripple__wave--animate-center")):(wave.classList.remove("ripple__wave--done"),wave.classList.remove("ripple__wave--animate"));var animationEnded=new Promise(function(resolve){var onAnimationEnd=function onAnimationEnd(){_this.removeEventListener("webkitAnimationEnd",onAnimationEnd),_this.removeEventListener("animationend",onAnimationEnd),resolve()};_this.addEventListener("webkitAnimationEnd",onAnimationEnd),_this.addEventListener("animationend",onAnimationEnd)}),mouseReleased=new Promise(function(resolve){var onMouseUp=function onMouseUp(){document.removeEventListener("webkitAnimationEnd",onMouseUp),document.removeEventListener("animationend",onMouseUp),resolve()};document.addEventListener("mouseup",onMouseUp),document.addEventListener("touchend",onMouseUp)});Promise.all([animationEnded,mouseReleased]).then(function(){_this._center?(wave.classList.remove("ripple__wave--animate-center"),wave.classList.add("ripple__wave--done-center")):(wave.classList.remove("ripple__wave--animate"),wave.classList.add("ripple__wave--done"))});var x=e.clientX,y=e.clientY;"touchstart"===eventType&&(x=e.changedTouches[0].clientX,y=e.changedTouches[0].clientY);var sizeX=void 0,sizeY=0;this._center?(sizeX=el.offsetWidth,sizeY=el.offsetHeight,sizeX=sizeX-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-left-width"))-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-right-width")),sizeY=sizeY-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-top-width"))-parseFloat(window.getComputedStyle(el,null).getPropertyValue("border-bottom-width"))):sizeX=sizeY=Math.max(el.offsetWidth,el.offsetHeight),wave.style.width=sizeX+"px",wave.style.height=sizeY+"px",x=x-pos.left-sizeX/2,y=y-pos.top-sizeY/2,wave.style.left=x+"px",wave.style.top=y+"px",this._center?wave.classList.add("ripple__wave--animate-center"):wave.classList.add("ripple__wave--animate")}}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}}]),RippleElement}(ons._BaseElement);window.OnsRippleElement||(window.OnsRippleElement=document.registerElement("ons-ripple",{prototype:RippleElement.prototype}))}(),window.OnsRowElement=window.OnsRowElement?window.OnsRowElement:document.registerElement("ons-row"),window.OnsScrollerElement=window.OnsScrollerElement?window.OnsScrollerElement:document.registerElement("ons-scroller");var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var scheme={"":"speed-dial__item--*"},ModifierUtil=ons._internal.ModifierUtil,SpeedDialItemElement=function(_ons$_BaseElement){function SpeedDialItemElement(){_classCallCheck(this,SpeedDialItemElement),_get(Object.getPrototypeOf(SpeedDialItemElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SpeedDialItemElement,_ons$_BaseElement),_createClass(SpeedDialItemElement,[{key:"createdCallback",value:function(){ModifierUtil.initModifier(this,scheme),this.classList.add("fab"),this.classList.add("fab--mini"),this.classList.add("speed-dial__item"),this._boundOnClick=this._onClick.bind(this)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick,!1)}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}},{key:"_onClick",value:function(e){e.stopPropagation()}}]),SpeedDialItemElement}(ons._BaseElement);window.OnsSpeedDialItemElement||(window.OnsSpeedDialItemElement=document.registerElement("ons-speed-dial-item",{prototype:SpeedDialItemElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x3,_x4,_x5){for(var _again=!0;_again;){var object=_x3,property=_x4,receiver=_x5;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x3=parent,_x4=property,_x5=receiver,_again=!0}};!function(){"use strict";var scheme={"":"speed-dial--*"},ModifierUtil=ons._internal.ModifierUtil,SpeedDialElement=function(_ons$_BaseElement){function SpeedDialElement(){_classCallCheck(this,SpeedDialElement),_get(Object.getPrototypeOf(SpeedDialElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SpeedDialElement,_ons$_BaseElement),_createClass(SpeedDialElement,[{key:"createdCallback",value:function(){this._compile(),this._shown=!0,this._itemShown=!1,ModifierUtil.initModifier(this,scheme),this._boundOnClick=this._onClick.bind(this),this.classList.add("speed__dial"),this.hasAttribute("direction")?this._updateDirection(this.getAttribute("direction")):this._updateDirection("up"),this._updatePosition(),this.hasAttribute("disabled")&&this.setDisabled(!0)}},{key:"_compile",value:function(){var content=document.createElement("ons-fab");ons._util.arrayFrom(this.childNodes).forEach(function(element){return"ons-speed-dial-item"!==element.nodeName.toLowerCase()?content.firstChild.appendChild(element):!0});this.insertBefore(content,this.firstChild)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("direction"===name?this._updateDirection(current):"position"===name?this._updatePosition():"disabled"===name&&(null!==current?this.setDisabled(!0):this.setDisabled(!1)))}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick,!1)}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}},{key:"_onClick",value:function(e){this.isDisabled()||this.toggleItems()}},{key:"_show",value:function(){this.isInline()||this.show()}},{key:"_hide",value:function(){this.isInline()||this.hide()}},{key:"_updateDirection",value:function(direction){for(var children=this.items,i=0;i<children.length;i++)children[i].style.transitionDelay=25*i+"ms",children[i].style.webkitTransitionDelay=25*i+"ms",children[i].style.bottom="auto",children[i].style.right="auto",children[i].style.top="auto",children[i].style.left="auto";switch(direction){case"up":for(var i=0;i<children.length;i++)children[i].style.bottom=72+56*i+"px",children[i].style.right="8px";break;case"down":for(var i=0;i<children.length;i++)children[i].style.top=72+56*i+"px",children[i].style.left="8px";break;case"left":for(var i=0;i<children.length;i++)children[i].style.top="8px",children[i].style.right=72+56*i+"px";break;case"right":for(var i=0;i<children.length;i++)children[i].style.top="8px",children[i].style.left=72+56*i+"px";break;default:throw new Error("Argument must be one of up, down, left or right.")}}},{key:"_updatePosition",value:function(){var position=this.getAttribute("position");switch(this.classList.remove("fab--top__left","fab--bottom__right","fab--bottom__left","fab--top__right","fab--top__center","fab--bottom__center"),position){case"top right":case"right top":this.classList.add("fab--top__right");break;case"top left":case"left top":this.classList.add("fab--top__left");break;case"bottom right":case"right bottom":this.classList.add("fab--bottom__right");break;case"bottom left":case"left bottom":this.classList.add("fab--bottom__left");break;case"center top":case"top center":this.classList.add("fab--top__center");break;case"center bottom":case"bottom center":this.classList.add("fab--bottom__center")}}},{key:"show",value:function(){arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.querySelector("ons-fab").show(),this._shown=!0}},{key:"hide",value:function(){var _this=this;arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.hideItems(),setTimeout(function(){_this.querySelector("ons-fab").hide()},200),this._shown=!1}},{key:"showItems",value:function(){if(!this._itemShown)for(var children=this.items,i=0;i<children.length;i++)children[i].style.transform="scale(1)",children[i].style.webkitTransform="scale(1)",children[i].style.transitionDelay=25*i+"ms",children[i].style.webkitTransitionDelay=25*i+"ms";this._itemShown=!0}},{key:"hideItems",value:function(){if(this._itemShown)for(var children=this.items,i=0;i<children.length;i++)children[i].style.transform="scale(0)",children[i].style.webkitTransform="scale(0)",children[i].style.transitionDelay=25*(children.length-i)+"ms",children[i].style.webkitTransitionDelay=25*(children.length-i)+"ms";this._itemShown=!1}},{key:"setDisabled",value:function(disabled){if("boolean"!=typeof disabled)throw new Error("Argument must be a boolean.");disabled?(this.hideItems(),this.setAttribute("disabled",""),ons._util.arrayFrom(this.childNodes).forEach(function(element){return element.classList.contains("fab")?element.setAttribute("disabled",""):!0})):(this.removeAttribute("disabled"),ons._util.arrayFrom(this.childNodes).forEach(function(element){return element.classList.contains("fab")?element.removeAttribute("disabled"):!0}))}},{key:"isDisabled",value:function(){return this.hasAttribute("disabled")}},{key:"isInline",value:function(){return this.hasAttribute("inline")}},{key:"isShown",value:function(){return this._shown&&"none"!==this.style.display}},{key:"isItemShown",value:function(){return this._itemShown}},{key:"toggle",value:function(){this.isShown()?this.hide():this.show()}},{key:"toggleItems",value:function(){this.isItemShown()?this.hideItems():this.showItems()}},{key:"items",get:function(){return ons._util.arrayFrom(this.querySelectorAll("ons-speed-dial-item"))}}]),SpeedDialElement}(ons._BaseElement);window.OnsSpeedDialElement||(window.OnsSpeedDialElement=document.registerElement("ons-speed-dial",{prototype:SpeedDialElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x2,_x3,_x4){for(var _again=!0;_again;){var object=_x2,property=_x3,receiver=_x4;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x2=parent,_x3=property,_x4=receiver,_again=!0}};!function(){"use strict";var util=ons._util,SplitterContentElement=function(_ons$_BaseElement){function SplitterContentElement(){_classCallCheck(this,SplitterContentElement),_get(Object.getPrototypeOf(SplitterContentElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterContentElement,_ons$_BaseElement),_createClass(SplitterContentElement,[{key:"createdCallback",value:function(){this._page=null}},{key:"load",value:function(page){var _this=this,options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];this._page=page,options.callback=options.callback instanceof Function?options.callback:function(){},ons._internal.getPageHTMLAsync(page).then(function(html){window.OnsSplitterContentElement.rewritables.link(_this,util.createFragment(html),function(fragment){for(;_this.childNodes[0];)_this.childNodes[0]._hide instanceof Function&&_this.childNodes[0]._hide(),_this.removeChild(_this.childNodes[0]);_this.appendChild(fragment),util.arrayOf(fragment.children).forEach(function(child){child._show instanceof Function&&child._show()}),options.callback()})})}},{key:"attachedCallback",value:function(){var _this2=this;this._assertParent(),this.hasAttribute("page")&&window.OnsSplitterContentElement.rewritables.ready(this,function(){return _this2.load(_this2.getAttribute("page"))})}},{key:"detachedCallback",value:function(){}},{key:"_show",value:function(){util.arrayOf(this.children).forEach(function(child){child._show instanceof Function&&child._show()})}},{key:"_hide",value:function(){util.arrayOf(this.children).forEach(function(child){child._hide instanceof Function&&child._hide()})}},{key:"_destroy",value:function(){util.arrayOf(this.children).forEach(function(child){child._destroy instanceof Function&&child._destroy()}),this.remove()}},{key:"_assertParent",value:function(){var parentElementName=this.parentElement.nodeName.toLowerCase();if("ons-splitter"!==parentElementName)throw new Error('"'+parentElementName+'" element is not allowed as parent element.')}},{key:"page",get:function(){return this._page}}]),SplitterContentElement}(ons._BaseElement);window.OnsSplitterContentElement||(window.OnsSplitterContentElement=document.registerElement("ons-splitter-content",{prototype:SplitterContentElement.prototype}),window.OnsSplitterContentElement.rewritables={ready:function(splitterSideElement,callback){setImmediate(callback)},link:function(splitterSideElement,target,callback){callback(target)}})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var SplitterMaskElement=function(_ons$_BaseElement){function SplitterMaskElement(){_classCallCheck(this,SplitterMaskElement),_get(Object.getPrototypeOf(SplitterMaskElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterMaskElement,_ons$_BaseElement),_createClass(SplitterMaskElement,[{key:"createdCallback",value:function(){this._boundOnClick=this._onClick.bind(this)}},{key:"_onClick",value:function(event){this.parentElement&&"ons-splitter"===this.parentElement.nodeName.toLowerCase()&&(this.parentElement.closeRight(),this.parentElement.closeLeft()),event.stopPropagation()}},{key:"attributeChangedCallback",value:function(name,last,current){}},{key:"attachedCallback",value:function(){this.addEventListener("click",this._boundOnClick)}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick)}}]),SplitterMaskElement}(ons._BaseElement);window.OnsSplitterMaskElement||(window.OnsSplitterMaskElement=document.registerElement("ons-splitter-mask",{prototype:SplitterMaskElement.prototype}))}();var _slicedToArray=function(){function sliceIterator(arr,i){var _arr=[],_n=!0,_d=!1,_e=void 0;try{for(var _s,_i=arr[Symbol.iterator]();!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{!_n&&_i["return"]&&_i["return"]()}finally{if(_d)throw _e}}return _arr}return function(arr,i){if(Array.isArray(arr))return arr;if(Symbol.iterator in Object(arr))return sliceIterator(arr,i);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),_get=function(_x9,_x10,_x11){for(var _again=!0;_again;){var object=_x9,property=_x10,receiver=_x11;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x9=parent,_x10=property,_x11=receiver,_again=!0}},_createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}();!function(){"use strict";var util=ons._util,AnimatorFactory=ons._internal.AnimatorFactory,SPLIT_MODE="split",COLLAPSE_MODE="collapse",CollapseDetection=function(){function CollapseDetection(){_classCallCheck(this,CollapseDetection)}return _createClass(CollapseDetection,[{key:"activate",value:function(element){}},{key:"inactivate",value:function(){}}]),CollapseDetection}(),OrientationCollapseDetection=function(_CollapseDetection){function OrientationCollapseDetection(orientation){if(_classCallCheck(this,OrientationCollapseDetection),_get(Object.getPrototypeOf(OrientationCollapseDetection.prototype),"constructor",this).call(this),"portrait"!==orientation&&"landscape"!==orientation)throw new Error("Invalid orientation: "+orientation);this._boundOnOrientationChange=this._onOrientationChange.bind(this),this._targetOrientation=orientation}return _inherits(OrientationCollapseDetection,_CollapseDetection),_createClass(OrientationCollapseDetection,[{key:"activate",value:function(element){this._element=element,ons.orientation.on("change",this._boundOnOrientationChange),this._update(ons.orientation.isPortrait())}},{key:"_onOrientationChange",value:function(info){this._update(info.isPortrait)}},{key:"_update",value:function(isPortrait){isPortrait&&"portrait"===this._targetOrientation?this._element._updateMode(COLLAPSE_MODE):isPortrait||"landscape"!==this._targetOrientation?this._element._updateMode(SPLIT_MODE):this._element._updateMode(COLLAPSE_MODE)}},{key:"inactivate",value:function(){this._element=null,ons.orientation.off("change",this._boundOnOrientationChange)}}]),OrientationCollapseDetection}(CollapseDetection),StaticCollapseDetection=function(_CollapseDetection2){function StaticCollapseDetection(){_classCallCheck(this,StaticCollapseDetection),_get(Object.getPrototypeOf(StaticCollapseDetection.prototype),"constructor",this).apply(this,arguments)}return _inherits(StaticCollapseDetection,_CollapseDetection2),_createClass(StaticCollapseDetection,[{key:"activate",value:function(element){element._updateMode(COLLAPSE_MODE)}}]),StaticCollapseDetection}(CollapseDetection),MediaQueryCollapseDetection=function(_CollapseDetection3){function MediaQueryCollapseDetection(query){_classCallCheck(this,MediaQueryCollapseDetection),_get(Object.getPrototypeOf(MediaQueryCollapseDetection.prototype),"constructor",this).call(this),this._mediaQueryString=query,this._boundOnChange=this._onChange.bind(this)}return _inherits(MediaQueryCollapseDetection,_CollapseDetection3),_createClass(MediaQueryCollapseDetection,[{key:"_onChange",value:function(queryList){this._element._updateMode(queryList.matches?COLLAPSE_MODE:SPLIT_MODE)}},{key:"activate",value:function(element){this._element=element,this._queryResult=window.matchMedia(this._mediaQueryString),this._queryResult.addListener(this._boundOnChange),this._onChange(this._queryResult)}},{key:"inactivate",value:function(){this._element=null,this._queryResult.removeListener(this._boundOnChange),this._queryResult=null}}]),MediaQueryCollapseDetection}(CollapseDetection),BaseMode=function(){function BaseMode(){_classCallCheck(this,BaseMode)}return _createClass(BaseMode,[{key:"isOpened",value:function(){return!1}},{key:"openMenu",value:function(){return!1}},{key:"closeMenu",value:function(){return!1}},{key:"enterMode",value:function(){}},{key:"exitMode",value:function(){}},{key:"handleGesture",value:function(){}}]),BaseMode}(),SplitMode=function(_BaseMode){function SplitMode(element){_classCallCheck(this,SplitMode),_get(Object.getPrototypeOf(SplitMode.prototype),"constructor",this).call(this),this._element=element}return _inherits(SplitMode,_BaseMode),_createClass(SplitMode,[{key:"isOpened",value:function(){return!1}},{key:"layout",value:function(){var element=this._element;element.style.width=element._getWidth(),element._isLeftSide()?(element.style.left="0",element.style.right="auto"):(element.style.left="auto",element.style.right="0")}},{key:"enterMode",value:function(){this.layout()}},{key:"exitMode",value:function(){var element=this._element;element.style.left="",element.style.right="",element.style.width="",element.style.zIndex=""}}]),SplitMode}(BaseMode),CollapseMode=function(_BaseMode2){function CollapseMode(element){_classCallCheck(this,CollapseMode),_get(Object.getPrototypeOf(CollapseMode.prototype),"constructor",this).call(this),this._state=CollapseMode.CLOSED_STATE,this._distance=0,this._element=element,this._lock=new DoorLock}return _inherits(CollapseMode,_BaseMode2),_createClass(CollapseMode,[{key:"_animator",get:function(){return this._element._getAnimator()}}],[{key:"CLOSED_STATE",get:function(){return"closed"}},{key:"OPENED_STATE",get:function(){return"opened"}},{key:"CHANGING_STATE",get:function(){return"changing"}}]),_createClass(CollapseMode,[{key:"_isLocked",value:function(){return this._lock.isLocked()}},{key:"isOpened",value:function(){return this._state!==CollapseMode.CLOSED_STATE}},{key:"isClosed",value:function(){return this._state===CollapseMode.CLOSED_STATE}},{key:"handleGesture",value:function(event){if(!this._isLocked()&&!this._openedOtherSideMenu())if("dragstart"===event.type)this._onDragStart(event);else if("dragleft"===event.type||"dragright"===event.type)this._ignoreDrag||this._onDrag(event);else{if("dragend"!==event.type)throw new Error("Invalid state");this._ignoreDrag||this._onDragEnd(event)}}},{key:"_onDragStart",value:function(event){if(this._ignoreDrag=!1,!this.isOpened()&&this._openedOtherSideMenu())this._ignoreDrag=!0;else if(this._element._swipeTargetWidth>0){var distance=this._element._isLeftSide()?event.gesture.center.clientX:window.innerWidth-event.gesture.center.clientX;distance>this._element._swipeTargetWidth&&(this._ignoreDrag=!0)}}},{key:"_onDrag",value:function(event){event.gesture.preventDefault();var deltaX=event.gesture.deltaX,deltaDistance=this._element._isLeftSide()?deltaX:-deltaX,startEvent=event.gesture.startEvent;"isOpened"in startEvent||(startEvent.isOpened=this.isOpened(),startEvent.distance=startEvent.isOpened?this._element._getWidthInPixel():0,startEvent.width=this._element._getWidthInPixel());var width=startEvent.width;if(!(0>deltaDistance&&startEvent.distance<=0||deltaDistance>0&&startEvent.distance>=width)){var distance=startEvent.isOpened?deltaDistance+width:deltaDistance,normalizedDistance=Math.max(0,Math.min(width,distance));startEvent.distance=normalizedDistance,this._state=CollapseMode.CHANGING_STATE,this._animator.translate(normalizedDistance)}}},{key:"_onDragEnd",value:function(event){var deltaX=event.gesture.deltaX,deltaDistance=this._element._isLeftSide()?deltaX:-deltaX,width=event.gesture.startEvent.width,distance=event.gesture.startEvent.isOpened?deltaDistance+width:deltaDistance,direction=event.gesture.interimDirection,shouldOpen=this._element._isLeftSide()&&"right"===direction&&distance>width*this._element._getThresholdRatioIfShouldOpen()||!this._element._isLeftSide()&&"left"===direction&&distance>width*this._element._getThresholdRatioIfShouldOpen();shouldOpen?this._openMenu():this._closeMenu()}},{key:"layout",value:function(){if(this._state!==CollapseMode.CHANGING_STATE)if(this._state===CollapseMode.CLOSED_STATE)this._animator.isActivated()&&this._animator.layoutOnClose();else{if(this._state!==CollapseMode.OPENED_STATE)throw new Error("Invalid state");this._animator.isActivated()&&this._animator.layoutOnOpen()}}},{key:"enterMode",value:function(){this._animator.activate(this._element._getContentElement(),this._element,this._element._getMaskElement()),this.layout()}},{key:"exitMode",value:function(){this._animator.inactivate()}},{key:"_openedOtherSideMenu",value:function(){var _this=this;return util.arrayFrom(this._element.parentElement.children).filter(function(child){return"ons-splitter-side"===child.nodeName.toLowerCase()&&_this._element!==child}).filter(function(side){return side.isOpened()}).length>0}},{key:"openMenu",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._state!==CollapseMode.CLOSED_STATE?!1:this._openMenu(options)}},{key:"_openMenu",value:function(){var _this2=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];if(this._isLocked())return!1;if(this._openedOtherSideMenu())return!1;if(this._element._emitPreOpenEvent())return!1;options.callback=options.callback instanceof Function?options.callback:function(){};var unlock=this._lock.lock(),done=function(){unlock(),_this2._element._emitPostOpenEvent(),options.callback()};return options.withoutAnimation?(this._state=CollapseMode.OPENED_STATE,this.layout(),done()):(this._state=CollapseMode.CHANGING_STATE,this._animator.open(function(){_this2._state=CollapseMode.OPENED_STATE,_this2.layout(),done()})),!0}},{key:"closeMenu",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._state!==CollapseMode.OPENED_STATE?!1:this._closeMenu(options)}},{key:"_closeMenu",value:function(){var _this3=this,options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];if(this._isLocked())return!1;if(this._element._emitPreCloseEvent())return!1;options.callback=options.callback instanceof Function?options.callback:function(){};var unlock=this._lock.lock(),done=function(){unlock(),_this3._element._emitPostCloseEvent(),setImmediate(options.callback)};return options.withoutAnimation?(this._state=CollapseMode.CLOSED_STATE,this.layout(),done()):(this._state=CollapseMode.CHANGING_STATE,this._animator.close(function(){_this3._state=CollapseMode.CLOSED_STATE,_this3.layout(),done()})),!0}}]),CollapseMode}(BaseMode),SplitterSideElement=function(_ons$_BaseElement){function SplitterSideElement(){_classCallCheck(this,SplitterSideElement),_get(Object.getPrototypeOf(SplitterSideElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterSideElement,_ons$_BaseElement),_createClass(SplitterSideElement,[{key:"_updateForAnimationOptionsAttribute",value:function(){this._animationOptions=util.parseJSONObjectSafely(this.getAttribute("animation-options"),{})}},{key:"_getMaskElement",value:function(){return util.findChild(this.parentElement,"ons-splitter-mask")}},{key:"_getContentElement",value:function(){return util.findChild(this.parentElement,"ons-splitter-content")}},{key:"_getModeStrategy",value:function(){return this._mode===COLLAPSE_MODE?this._collapseMode:this._mode===SPLIT_MODE?this._splitMode:void 0}},{key:"createdCallback",value:function(){this._mode=null,this._page=null,this._isAttached=!1,this._collapseStrategy=new CollapseDetection,this._animatorFactory=new AnimatorFactory({animators:window.OnsSplitterElement._animatorDict,baseClass:ons._internal.SplitterAnimator,baseClassName:"SplitterAnimator",defaultAnimation:this.getAttribute("animation")}),this._collapseMode=new CollapseMode(this),this._splitMode=new SplitMode(this),this._boundHandleGesture=this._handleGesture.bind(this),this._cancelModeDetection=function(){},this._updateMode(SPLIT_MODE),this._updateForAnimationAttribute(),this._updateForWidthAttribute(),this._updateForSideAttribute(),this._updateForCollapseAttribute(),this._updateForSwipeableAttribute(),this._updateForSwipeTargetWidthAttribute(),this._updateForAnimationOptionsAttribute()}},{key:"_getAnimator",value:function(){return this._animator}},{key:"isSwipeable",value:function(){return this.hasAttribute("swipeable")}},{key:"_emitPostOpenEvent",value:function(){util.triggerElementEvent(this,"postopen",{side:this})}},{key:"_emitPostCloseEvent", value:function(){util.triggerElementEvent(this,"postclose",{side:this})}},{key:"_emitPreOpenEvent",value:function(){return this._emitCancelableEvent("preopen")}},{key:"_emitCancelableEvent",value:function(name){var isCanceled=!1;return util.triggerElementEvent(this,name,{side:this,cancel:function(){return isCanceled=!0}}),isCanceled}},{key:"_emitPreCloseEvent",value:function(){return this._emitCancelableEvent("preclose")}},{key:"_updateForCollapseAttribute",value:function(){if(!this.hasAttribute("collapse"))return void this._updateMode(SPLIT_MODE);var collapse=(""+this.getAttribute("collapse")).trim();""===collapse?this._updateCollapseStrategy(new StaticCollapseDetection):"portrait"===collapse||"landscape"===collapse?this._updateCollapseStrategy(new OrientationCollapseDetection(collapse)):this._updateCollapseStrategy(new MediaQueryCollapseDetection(collapse))}},{key:"_updateCollapseStrategy",value:function(strategy){this._isAttached&&(this._collapseStrategy.inactivate(),strategy.activate(this)),this._collapseStrategy=strategy}},{key:"_updateMode",value:function(mode){if(mode!==COLLAPSE_MODE&&mode!==SPLIT_MODE)throw new Error("invalid mode: "+mode);if(mode!==this._mode){var lastMode=this._getModeStrategy();lastMode&&lastMode.exitMode(),this._mode=mode;var currentMode=this._getModeStrategy();currentMode.enterMode(),this.setAttribute("mode",mode),util.triggerElementEvent(this,"modechange",{side:this,mode:mode})}}},{key:"_getThresholdRatioIfShouldOpen",value:function(){if(this.hasAttribute("threhold-ratio-should-open")){var value=parseFloat(this.getAttribute("threhold-ratio-should-open"));return Math.max(0,Math.min(1,value))}return.3}},{key:"_layout",value:function(){this._getModeStrategy().layout()}},{key:"_updateForSwipeTargetWidthAttribute",value:function(){this.hasAttribute("swipe-target-width")?this._swipeTargetWidth=Math.max(0,parseInt(this.getAttribute("swipe-target-width"),10)):this._swipeTargetWidth=-1}},{key:"_getWidth",value:function(){function normalize(width){return width=width.trim(),width.match(/^\d+(px|%)$/)?width:"80%"}return this.hasAttribute("width")?normalize(this.getAttribute("width")):"80%"}},{key:"_getWidthInPixel",value:function(){var width=this._getWidth(),_width$match=width.match(/^(\d+)(px|%)$/),_width$match2=_slicedToArray(_width$match,3),num=_width$match2[1],unit=_width$match2[2];if("px"===unit)return parseInt(num,10);if("%"===unit){var percent=parseInt(num,10);return Math.round(this.parentElement.offsetWidth*percent/100)}throw new Error("Invalid state")}},{key:"_getSide",value:function(){function normalize(side){return side=(""+side).trim(),"left"===side||"right"===side?side:"left"}return normalize(this.getAttribute("side"))}},{key:"_isLeftSide",value:function(){return"left"===this._getSide()}},{key:"_updateForWidthAttribute",value:function(){this._getModeStrategy().layout()}},{key:"_updateForSideAttribute",value:function(){this._getModeStrategy().layout()}},{key:"getCurrentMode",value:function(){return this._mode}},{key:"isOpened",value:function(){return this._getModeStrategy().isOpened()}},{key:"open",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._getModeStrategy().openMenu(options)}},{key:"close",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._getModeStrategy().closeMenu(options)}},{key:"load",value:function(page){var _this4=this,options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];this._page=page,options.callback=options.callback instanceof Function?options.callback:function(){},ons._internal.getPageHTMLAsync(page).then(function(html){window.OnsSplitterSideElement.rewritables.link(_this4,util.createFragment(html),function(fragment){for(;_this4.childNodes[0];)_this4.childNodes[0]._hide instanceof Function&&_this4.childNodes[0]._hide(),_this4.removeChild(_this4.childNodes[0]);_this4.appendChild(fragment),util.arrayOf(fragment.childNodes).forEach(function(node){node._show instanceof Function&&node._show()}),options.callback()})})}},{key:"toggle",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this.isOpened()?this.close(options):this.open(options)}},{key:"attributeChangedCallback",value:function(name,last,current){"width"===name?this._updateForWidthAttribute():"side"===name?this._updateForSideAttribute():"collapse"===name?this._updateForCollapseAttribute():"swipeable"===name?this._updateForSwipeableAttribute():"swipe-target-width"===name?this._updateForSwipeTargetWidthAttribute():"animation-options"===name?this._updateForAnimationOptionsAttribute():"animation"===name&&this._updateForAnimationAttribute()}},{key:"_updateForAnimationAttribute",value:function(){var isActivated=this._animator&&this._animator.isActivated();isActivated&&this._animator.inactivate(),this._animator=this._createAnimator(),isActivated&&this._animator.activate(this._getContentElement(),this,this._getMaskElement())}},{key:"_updateForSwipeableAttribute",value:function(){this._gestureDetector&&(this.isSwipeable()?this._gestureDetector.on("dragstart dragleft dragright dragend",this._boundHandleGesture):this._gestureDetector.off("dragstart dragleft dragright dragend",this._boundHandleGesture))}},{key:"_assertParent",value:function(){var parentElementName=this.parentElement.nodeName.toLowerCase();if("ons-splitter"!==parentElementName)throw new Error('"'+parentElementName+'" element is not allowed as parent element.')}},{key:"attachedCallback",value:function(){var _this5=this;this._isAttached=!0,this._collapseStrategy.activate(this),this._assertParent(),this._gestureDetector=new ons.GestureDetector(this.parentElement,{dragMinDistance:1}),this._updateForSwipeableAttribute(),this.hasAttribute("page")&&window.OnsSplitterSideElement.rewritables.ready(this,function(){return _this5.load(_this5.getAttribute("page"))})}},{key:"detachedCallback",value:function(){this._isAttached=!1,this._collapseStrategy.inactivate(),this._gestureDetector.dispose(),this._gestureDetector=null,this._updateForSwipeableAttribute()}},{key:"_handleGesture",value:function(event){return this._getModeStrategy().handleGesture(event)}},{key:"_show",value:function(){util.arrayOf(this.children).forEach(function(child){child._show instanceof Function&&child._show()})}},{key:"_hide",value:function(){util.arrayOf(this.children).forEach(function(child){child._hide instanceof Function&&child._hide()})}},{key:"_destroy",value:function(){util.arrayOf(this.children).forEach(function(child){child._destroy instanceof Function&&child._destroy()}),this.remove()}},{key:"_createAnimator",value:function(){return this._animatorFactory.newAnimator({animation:this.getAttribute("animation"),animationOptions:AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options"))})}},{key:"page",get:function(){return this._page}},{key:"mode",get:function(){this._mode}}]),SplitterSideElement}(ons._BaseElement);window.OnsSplitterSideElement||(window.OnsSplitterSideElement=document.registerElement("ons-splitter-side",{prototype:SplitterSideElement.prototype}),window.OnsSplitterSideElement.rewritables={ready:function(splitterSideElement,callback){setImmediate(callback)},link:function(splitterSideElement,target,callback){callback(target)}})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x11,_x12,_x13){for(var _again=!0;_again;){var object=_x11,property=_x12,receiver=_x13;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x11=parent,_x12=property,_x13=receiver,_again=!0}};!function(){"use strict";var util=ons._util,SplitterElement=function(_ons$_BaseElement){function SplitterElement(){_classCallCheck(this,SplitterElement),_get(Object.getPrototypeOf(SplitterElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SplitterElement,_ons$_BaseElement),_createClass(SplitterElement,[{key:"createdCallback",value:function(){this._boundOnDeviceBackButton=this._onDeviceBackButton.bind(this),this._boundOnModeChange=this._onModeChange.bind(this)}},{key:"_onModeChange",value:function(event){event.target.parentElement===this&&this._layout()}},{key:"_getSideElement",value:function(side){var result=util.findChild(this,function(element){return"ons-splitter-side"===element.nodeName.toLowerCase()&&element.getAttribute("side")===side});return result&&CustomElements.upgrade(result),result}},{key:"_layout",value:function(){var content=this._getContentElement(),left=this._getSideElement("left"),right=this._getSideElement("right");content&&(left&&left.getCurrentMode&&"split"===left.getCurrentMode()?content.style.left=left._getWidth():content.style.left="0px",right&&right.getCurrentMode&&"split"===right.getCurrentMode()?content.style.right=right._getWidth():content.style.right="0px")}},{key:"_getContentElement",value:function(){return util.findChild(this,"ons-splitter-content")}},{key:"attributeChangedCallback",value:function(name,last,current){}},{key:"openRight",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._open("right",options)}},{key:"_getMaskElement",value:function(){var mask=util.findChild(this,"ons-splitter-mask");return mask||this.appendChild(document.createElement("ons-splitter-mask"))}},{key:"openLeft",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._open("left",options)}},{key:"_open",value:function(side){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],menu=this._getSideElement(side);return menu?menu.open(options):!1}},{key:"closeRight",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._close("right",options)}},{key:"closeLeft",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._close("left",options)}},{key:"_close",value:function(side){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],menu=this._getSideElement(side);return menu?menu.close(options):!1}},{key:"toggleLeft",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._toggle("left",options)}},{key:"toggleRight",value:function(){var options=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return this._toggle("right",options)}},{key:"_toggle",value:function(side){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],menu=this._getSideElement(side);return menu?menu.toggle(options):!1}},{key:"leftIsOpened",value:function(){return this._isOpened("left")}},{key:"rightIsOpened",value:function(){return this._isOpened("right")}},{key:"_isOpened",value:function(side){var menu=this._getSideElement(side);return menu?menu.isOpened():!1}},{key:"loadContentPage",value:function(page){var options=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],content=this._getContentElement();if(content)return content.load(page,options);throw new Error('child "ons-splitter-content" element is not found in this element.')}},{key:"_onDeviceBackButton",value:function(handler){var left=this._getSideElement("left"),right=this._getSideElement("right");return left.isOpened()?void left.close():right.isOpened()?void right.close():void handler.callParentHandler()}},{key:"attachedCallback",value:function(){var _this=this;this._deviceBackButtonHandler=ons._deviceBackButtonDispatcher.createHandler(this,this._boundOnDeviceBackButton),this._assertChildren(),this.addEventListener("modechange",this._boundOnModeChange,!1),setImmediate(function(){return _this._layout()})}},{key:"getDeviceBackButtonHandler",value:function(){return this._deviceBackButtonHandler}},{key:"_assertChildren",value:function(){var names=["ons-splitter-content","ons-splitter-side","ons-splitter-mask"],contentCount=0,sideCount=0,maskCount=0;if(util.arrayFrom(this.children).forEach(function(element){var name=element.nodeName.toLowerCase();if(-1===names.indexOf(name))throw new Error('"'+name+'" element is not allowed in "ons-splitter" element.');"ons-splitter-content"===name?contentCount++:"ons-splitter-content"===name?sideCount++:"ons-splitter-mask"===name&&maskCount++}),contentCount>1)throw new Error("too many <ons-splitter-content> elements.");if(sideCount>2)throw new Error("too many <ons-splitter-side> elements.");if(maskCount>1)throw new Error("too many <ons-splitter-mask> elements.");0===maskCount&&this.appendChild(document.createElement("ons-splitter-mask"))}},{key:"detachedCallback",value:function(){this._deviceBackButtonHandler.destroy(),this._deviceBackButtonHandler=null,this.removeEventListener("modechange",this._boundOnModeChange,!1)}},{key:"_show",value:function(){util.arrayOf(this.children).forEach(function(child){child._show instanceof Function&&child._show()})}},{key:"_hide",value:function(){util.arrayOf(this.children).forEach(function(child){child._hide instanceof Function&&child._hide()})}},{key:"_destroy",value:function(){util.arrayOf(this.children).forEach(function(child){child._destroy instanceof Function&&child._destroy()}),this.remove()}}]),SplitterElement}(ons._BaseElement);window.OnsSplitterElement||(window.OnsSplitterElement=document.registerElement("ons-splitter",{prototype:SplitterElement.prototype}),window.OnsSplitterElement._animatorDict={"default":ons._internal.OverlaySplitterAnimator,overlay:ons._internal.OverlaySplitterAnimator},window.OnsSplitterElement.registerAnimator=function(name,Animator){if(!(Animator instanceof ons._internal.SplitterAnimator))throw new Error("Animator parameter must be an instance of SplitterAnimator.");window.OnsSplitterElement._animatorDict[name]=Animator},window.OnsSplitterElement.SplitterAnimator=ons._internal.SplitterAnimator)}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var scheme={"":"switch--*",".switch__input":"switch--*__input",".switch__toggle":"switch--*__toggle"},ModifierUtil=ons._internal.ModifierUtil,templateSource=ons._util.createElement('\n <div>\n <input type="checkbox" class="switch__input">\n <div class="switch__toggle"></div>\n </div>\n '),ExtendableLabelElement=void 0;"function"!=typeof HTMLLabelElement?(ExtendableLabelElement=function(){},ExtendableLabelElement.prototype=document.createElement("label")):ExtendableLabelElement=HTMLLabelElement;var generateId=function(){var i=0;return function(){return"ons-switch-id-"+i++}}(),SwitchElement=function(_ExtendableLabelElement){function SwitchElement(){_classCallCheck(this,SwitchElement),_get(Object.getPrototypeOf(SwitchElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(SwitchElement,_ExtendableLabelElement),_createClass(SwitchElement,[{key:"isChecked",value:function(){return this.checked}},{key:"setChecked",value:function(isChecked){this.checked=!!isChecked}},{key:"getCheckboxElement",value:function(){return this._getCheckbox()}},{key:"createdCallback",value:function(){this._compile(),ModifierUtil.initModifier(this,scheme),this._updateForCheckedAttribute(),this._updateForDisabledAttribute()}},{key:"_updateForCheckedAttribute",value:function(){this.hasAttribute("checked")?this._getCheckbox().checked=!0:this._getCheckbox().checked=!1}},{key:"_updateForDisabledAttribute",value:function(){this.hasAttribute("disabled")?this._getCheckbox().setAttribute("disabled",""):this._getCheckbox().removeAttribute("disabled")}},{key:"_compile",value:function(){this.classList.add("switch");for(var template=templateSource.cloneNode(!0);template.children[0];)this.appendChild(template.children[0]);this._getCheckbox().setAttribute("name",generateId())}},{key:"detachedCallback",value:function(){this._getCheckbox().removeEventListener("change",this._onChangeListener)}},{key:"attachedCallback",value:function(){this._getCheckbox().addEventListener("change",this._onChangeListener)}},{key:"_onChangeListener",value:function(){this.checked!==!0?this.removeAttribute("checked"):this.setAttribute("checked","")}},{key:"_isChecked",value:function(){return this._getCheckbox().checked}},{key:"_setChecked",value:function(isChecked){isChecked=!!isChecked;var checkbox=this._getCheckbox();checkbox.checked!=isChecked&&(checkbox.checked=isChecked)}},{key:"_getCheckbox",value:function(){return this.querySelector("input[type=checkbox]")}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void("checked"===name?this._updateForCheckedAttribute():"disabled"===name&&this._updateForDisabledAttribute())}},{key:"checked",get:function(){return this._getCheckbox().checked},set:function(value){this._getCheckbox().checked=value,this.checked?this.setAttribute("checked",""):this.removeAttribute("checked"),this._updateForCheckedAttribute()}},{key:"disabled",get:function(){return this._getCheckbox().disabled},set:function(value){this._getCheckbox().disabled=value,this.disabled?this.setAttribute("disabled",""):this.removeAttribute("disabled")}}]),SwitchElement}(ExtendableLabelElement);window.OnsSwitchElement||(window.OnsSwitchElement=document.registerElement("ons-switch",{prototype:SwitchElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var scheme={"":"tab-bar--*__item",".tab-bar__button":"tab-bar--*__button"},ModifierUtil=ons._internal.ModifierUtil,util=ons._util,templateSource=util.createElement('\n <div>\n <input type="radio" style="display: none">\n <button class="tab-bar__button tab-bar-inner"></button>\n </div>\n '),defaultInnerTemplateSource=util.createElement('\n <div>\n <div class="tab-bar__icon">\n <ons-icon icon="ion-cloud" style="font-size: 28px; line-height: 34px; vertical-align: top;"></ons-icon>\n </div>\n <div class="tab-bar__label">label</div>\n </div>\n '),TabElement=function(_ons$_BaseElement){function TabElement(){_classCallCheck(this,TabElement),_get(Object.getPrototypeOf(TabElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(TabElement,_ons$_BaseElement),_createClass(TabElement,[{key:"createdCallback",value:function(){this._compile(),this._boundOnClick=this._onClick.bind(this),ModifierUtil.initModifier(this,scheme)}},{key:"_compile",value:function(){for(var fragment=document.createDocumentFragment(),hasChildren=!1;this.childNodes[0];){var node=this.childNodes[0];this.removeChild(node),fragment.appendChild(node),node.nodeType==Node.ELEMENT_NODE&&(hasChildren=!0)}for(var template=templateSource.cloneNode(!0);template.children[0];)this.appendChild(template.children[0]);this.classList.add("tab-bar__item");var button=util.findChild(this,".tab-bar__button");hasChildren?(button.appendChild(fragment),this._hasDefaultTemplate=!1):(this._hasDefaultTemplate=!0,this._updateDefaultTemplate())}},{key:"_updateDefaultTemplate",value:function(){function getLabelElement(){return self.querySelector(".tab-bar__label")}function getIconElement(){return self.querySelector("ons-icon")}if(this._hasDefaultTemplate){for(var button=util.findChild(this,".tab-bar__button"),template=defaultInnerTemplateSource.cloneNode(!0);template.children[0];)button.appendChild(template.children[0]);var self=this,icon=this.getAttribute("icon"),label=this.getAttribute("label");if("string"==typeof icon)getIconElement().setAttribute("icon",icon);else{var wrapper=button.querySelector(".tab-bar__icon");wrapper.parentNode.removeChild(wrapper)}"string"==typeof label?getLabelElement().textContent=label:getLabelElement().parentNode.removeChild(getLabelElement())}}},{key:"_onClick",value:function(){var tabbar=this._findTabbarElement();tabbar&&tabbar.setActiveTab(this._findTabIndex())}},{key:"isPersistent",value:function(){return this.hasAttribute("persistent")}},{key:"setActive",value:function(){var radio=util.findChild(this,"input");radio.checked=!0,this.classList.add("active"),util.arrayFrom(this.querySelectorAll("[ons-tab-inactive]")).forEach(function(element){return element.style.display="none"}),util.arrayFrom(this.querySelectorAll("[ons-tab-active]")).forEach(function(element){return element.style.display="inherit"})}},{key:"setInactive",value:function(){var radio=util.findChild(this,"input");radio.checked=!1,this.classList.remove("active"),util.arrayFrom(this.querySelectorAll("[ons-tab-inactive]")).forEach(function(element){return element.style.display="inherit"}),util.arrayFrom(this.querySelectorAll("[ons-tab-active]")).forEach(function(element){return element.style.display="none"})}},{key:"isLoaded",value:function(){return!1}},{key:"_loadPageElement",value:function(callback,link){var _this=this;this.isPersistent()?this._pageElement?callback(this._pageElement):this._createPageElement(this.getAttribute("page"),function(element){link(element,function(element){_this._pageElement=element,callback(element)})}):(this._pageElement=null,this._createPageElement(this.getAttribute("page"),callback))}},{key:"_createPageElement",value:function(page,callback){ons._internal.getPageHTMLAsync(page).then(function(html){callback(util.createElement(html.trim()))})}},{key:"isActive",value:function(){return this.classList.contains("active")}},{key:"canReload",value:function(){return!this.hasAttribute("no-reload")}},{key:"detachedCallback",value:function(){this.removeEventListener("click",this._boundOnClick,!1)}},{key:"attachedCallback",value:function(){var _this2=this;this._ensureElementPosition(),this.hasAttribute("active")&&!function(){var tabbar=_this2._findTabbarElement(),tabIndex=_this2._findTabIndex();window.OnsTabbarElement.rewritables.ready(tabbar,function(){tabbar.setActiveTab(tabIndex,{animation:"none"})})}(),this.addEventListener("click",this._boundOnClick,!1)}},{key:"_findTabbarElement",value:function(){return this.parentNode&&"ons-tabbar"===this.parentNode.nodeName.toLowerCase()?this.parentNode:this.parentNode.parentNode&&"ons-tabbar"===this.parentNode.parentNode.nodeName.toLowerCase()?this.parentNode.parentNode:null}},{key:"_findTabIndex",value:function(){for(var elements=this.parentNode.children,i=0;i<elements.length;i++)if(this===elements[i])return i}},{key:"_ensureElementPosition",value:function(){if(!this._findTabbarElement())throw new Error("This ons-tab element is must be child of ons-tabbar element.")}},{key:"attributeChangedCallback",value:function(name,last,current){return this._hasDefaultTemplate&&("icon"===name||"label"===name)&&this._updateDefaultTemplate(),"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),TabElement}(ons._BaseElement);window.OnsTabElement||(window.OnsTabElement=document.registerElement("ons-tab",{prototype:TabElement.prototype}),document.registerElement("ons-tabbar-item",{prototype:Object.create(TabElement.prototype)}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var scheme={".tab-bar__content":"tab-bar--*__content",".tab-bar":"tab-bar--*"},AnimatorFactory=ons._internal.AnimatorFactory,TabbarAnimator=ons._internal.TabbarAnimator,TabbarFadeAnimator=ons._internal.TabbarFadeAnimator,TabbarNoneAnimator=ons._internal.TabbarNoneAnimator,TabbarSlideAnimator=ons._internal.TabbarSlideAnimator,ModifierUtil=ons._internal.ModifierUtil,util=ons._util,generateId=function(){var i=0;return function(){return"ons-tabbar-gen-"+i++}}(),TabbarElement=function(_ons$_BaseElement){function TabbarElement(){_classCallCheck(this,TabbarElement),_get(Object.getPrototypeOf(TabbarElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(TabbarElement,_ons$_BaseElement),_createClass(TabbarElement,[{key:"createdCallback",value:function(){this._tabbarId=generateId(),this._animatorFactory=new AnimatorFactory({animators:OnsTabbarElement._animatorDict,baseClass:TabbarAnimator,baseClassName:"TabbarAnimator",defaultAnimation:this.getAttribute("animation")}),this._compile(),this._contentElement=ons._util.findChild(this,".tab-bar__content"),ModifierUtil.initModifier(this,scheme)}},{key:"_compile",value:function(){var wrapper=document.createDocumentFragment(),content=document.createElement("div");content.classList.add("ons-tab-bar__content"),content.classList.add("tab-bar__content");var tabbar=document.createElement("div");for(tabbar.classList.add("tab-bar"),tabbar.classList.add("ons-tab-bar__footer"),tabbar.classList.add("ons-tabbar-inner"),wrapper.appendChild(content),wrapper.appendChild(tabbar);this.childNodes[0];)tabbar.appendChild(this.removeChild(this.childNodes[0]));this.appendChild(wrapper),this._hasTopTabbar()&&this._prepareForTopTabbar()}},{key:"_hasTopTabbar",value:function(){return"top"===this.getAttribute("position")}},{key:"_prepareForTopTabbar",value:function(){var content=ons._util.findChild(this,".tab-bar__content"),tabbar=ons._util.findChild(this,".tab-bar");content.setAttribute("no-status-bar-fill",""),content.classList.add("tab-bar--top__content"),tabbar.classList.add("tab-bar--top");var page=ons._util.findParent(this,"ons-page");if(page&&(this.style.top=window.getComputedStyle(page._getContentElement(),null).getPropertyValue("padding-top")),ons._internal.shouldFillStatusBar(this)){var fill=document.createElement("div");fill.classList.add("tab-bar__status-bar-fill"),fill.style.width="0px",fill.style.height="0px",this.insertBefore(fill,this.children[0])}}},{key:"_getTabbarElement",value:function(){return util.findChild(this,".tab-bar")}},{key:"loadPage",value:function(page,options){return options=options||{},options._removeElement=!0,this._loadPage(page,options)}},{key:"_loadPage",value:function(page,options){var _this=this;OnsTabElement.prototype._createPageElement(page,function(pageElement){_this._loadPageDOMAsync(pageElement,options)})}},{key:"_loadPageDOMAsync",value:function(pageElement,options){var _this2=this;options=options||{},window.OnsTabbarElement.rewritables.link(this,pageElement,function(pageElement){_this2._contentElement.appendChild(pageElement),_this2._switchPage(pageElement,options)})}},{key:"getTabbarId",value:function(){return this._tabbarId}},{key:"_getCurrentPageElement",value:function(){for(var pages=this._contentElement.children,page=null,i=0;i<pages.length;i++)if("none"!==pages[i].style.display){page=pages[i];break}if(page&&"ons-page"!==page.nodeName.toLowerCase())throw new Error('Invalid state: page element must be a "ons-page" element.');return page}},{key:"_switchPage",value:function(element,options){if(-1!==this.getActiveTabIndex()){var oldPageElement=this._contentElement.children.length>1?this._getCurrentPageElement():ons._internal.nullElement,animator=this._animatorFactory.newAnimator(options);animator.apply(element,oldPageElement,options.selectedTabIndex,options.previousTabIndex,function(){oldPageElement!==ons._internal.nullElement&&(options._removeElement?oldPageElement._destroy():(oldPageElement.style.display="none",oldPageElement._hide())),element.style.display="block",element._show(),options.callback instanceof Function&&options.callback()})}else options.callback instanceof Function&&options.callback()}},{key:"setActiveTab",value:function(index,options){var _this3=this;options=options||{},options.animationOptions=util.extend(options.animationOptions||{},AnimatorFactory.parseAnimationOptionsString(this.getAttribute("animation-options")));var previousTab=this._getActiveTabElement(),selectedTab=this._getTabElement(index),previousTabIndex=this.getActiveTabIndex(),selectedTabIndex=index;if(!selectedTab)return!1;if((selectedTab.hasAttribute("no-reload")||selectedTab.isPersistent())&&index===previousTabIndex)return util.triggerElementEvent(this,"reactive",{index:index,tabItem:selectedTab}),!1;var canceled=!1;if(util.triggerElementEvent(this,"prechange",{index:index,tabItem:selectedTab,cancel:function(){return canceled=!0}}),canceled)return selectedTab.setInactive(),previousTab&&previousTab.setActive(),!1;selectedTab.setActive();var needLoad=!selectedTab.isLoaded()&&!options.keepPage;if(needLoad){var removeElement=!0;previousTab&&previousTab.isPersistent()&&(removeElement=!1);var params={callback:function(){util.triggerElementEvent(_this3,"postchange",{index:index,tabItem:selectedTab}),options.callback instanceof Function&&options.callback()},previousTabIndex:previousTabIndex,selectedTabIndex:selectedTabIndex,_removeElement:removeElement};if(options.animation&&(params.animation=options.animation),selectedTab.isPersistent()){var link=function(element,callback){window.OnsTabbarElement.rewritables.link(_this3,element,callback)};selectedTab._loadPageElement(function(pageElement){_this3._loadPersistentPageDOM(pageElement,params)},link)}else this._loadPage(selectedTab.getAttribute("page"),params); }return util.arrayFrom(this._getTabbarElement().children).forEach(function(tab){tab!=selectedTab?tab.setInactive():needLoad||util.triggerElementEvent(_this3,"postchange",{index:index,tabItem:selectedTab})}),!0}},{key:"_loadPersistentPageDOM",value:function(element,options){options=options||{},util.isAttached(element)||this._contentElement.appendChild(element),this._switchPage(element,options)}},{key:"setTabbarVisibility",value:function(visible){this._contentElement.style[this._hasTopTabbar()?"top":"bottom"]=visible?"":"0px",this._getTabbarElement().style.display=visible?"":"none"}},{key:"getActiveTabIndex",value:function(){for(var tabs=this._getTabbarElement().children,i=0;i<tabs.length;i++)if("ons-tab"===tabs[i].nodeName.toLowerCase()&&tabs[i].isActive&&tabs[i].isActive())return i;return-1}},{key:"_getActiveTabElement",value:function(){return this._getTabElement(this.getActiveTabIndex())}},{key:"_getTabElement",value:function(index){return this._getTabbarElement().children[index]}},{key:"detachedCallback",value:function(){}},{key:"attachedCallback",value:function(){}},{key:"_show",value:function(){var currentPageElement=this._getCurrentPageElement();currentPageElement&&currentPageElement._show()}},{key:"_hide",value:function(){var currentPageElement=this._getCurrentPageElement();currentPageElement&&currentPageElement._hide()}},{key:"_destroy",value:function(){for(var pages=this._contentElement.children,i=pages.length-1;i>=0;i--)pages[i]._destroy();this.remove()}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),TabbarElement}(ons._BaseElement);window.OnsTabbarElement||(window.OnsTabbarElement=document.registerElement("ons-tabbar",{prototype:TabbarElement.prototype}),window.OnsTabbarElement._animatorDict={"default":TabbarNoneAnimator,fade:TabbarFadeAnimator,slide:TabbarSlideAnimator,none:TabbarNoneAnimator},window.OnsTabbarElement.registerAnimator=function(name,Animator){if(!(Animator.prototype instanceof TabbarAnimator))throw new Error('"Animator" param must inherit TabbarAnimator');this._animatorDict[name]=Animator},window.OnsTabbarElement.rewritables={ready:function(tabbarElement,callback){callback()},link:function(tabbarElement,target,callback){callback(target)}})}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var TemplateElement=function(_ons$_BaseElement){function TemplateElement(){_classCallCheck(this,TemplateElement),_get(Object.getPrototypeOf(TemplateElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(TemplateElement,_ons$_BaseElement),_createClass(TemplateElement,[{key:"createdCallback",value:function(){for(this.template=this.innerHTML;this.firstChild;)this.removeChild(this.firstChild)}},{key:"attachedCallback",value:function(){var event=new CustomEvent("_templateloaded",{bubbles:!0,cancelable:!0});event.template=this.template,event.templateId=this.getAttribute("id"),this.dispatchEvent(event)}}]),TemplateElement}(ons._BaseElement);window.OnsTemplateElement||(window.OnsTemplateElement=document.registerElement("ons-template",{prototype:TemplateElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var scheme={"":"toolbar-button--*"},ModifierUtil=ons._internal.ModifierUtil,ToolbarButtonElement=function(_ons$_BaseElement){function ToolbarButtonElement(){_classCallCheck(this,ToolbarButtonElement),_get(Object.getPrototypeOf(ToolbarButtonElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ToolbarButtonElement,_ons$_BaseElement),_createClass(ToolbarButtonElement,[{key:"createdCallback",value:function(){this.classList.add("toolbar-button"),this.classList.add("navigation-bar__line-height"),ModifierUtil.initModifier(this,scheme)}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}}]),ToolbarButtonElement}(ons._BaseElement);window.OnsToolbarButton||(window.OnsToolbarButton=document.registerElement("ons-toolbar-button",{prototype:ToolbarButtonElement.prototype}))}();var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,descriptor.key,descriptor)}}return function(Constructor,protoProps,staticProps){return protoProps&&defineProperties(Constructor.prototype,protoProps),staticProps&&defineProperties(Constructor,staticProps),Constructor}}(),_get=function(_x,_x2,_x3){for(var _again=!0;_again;){var object=_x,property=_x2,receiver=_x3;desc=parent=getter=void 0,_again=!1,null===object&&(object=Function.prototype);var desc=Object.getOwnPropertyDescriptor(object,property);if(void 0!==desc){if("value"in desc)return desc.value;var getter=desc.get;return void 0===getter?void 0:getter.call(receiver)}var parent=Object.getPrototypeOf(object);if(null===parent)return void 0;_x=parent,_x2=property,_x3=receiver,_again=!0}};!function(){"use strict";var scheme={"":"navigation-bar--*",".navigation-bar__left":"navigation-bar--*__left",".navigation-bar__center":"navigation-bar--*__center",".navigation-bar__right":"navigation-bar--*__right"},ModifierUtil=ons._internal.ModifierUtil,ToolbarElement=function(_ons$_BaseElement){function ToolbarElement(){_classCallCheck(this,ToolbarElement),_get(Object.getPrototypeOf(ToolbarElement.prototype),"constructor",this).apply(this,arguments)}return _inherits(ToolbarElement,_ons$_BaseElement),_createClass(ToolbarElement,[{key:"createdCallback",value:function(){var _this=this;this._compile(),ModifierUtil.initModifier(this,scheme),this._tryToEnsureNodePosition(),setImmediate(function(){return _this._tryToEnsureNodePosition()})}},{key:"attributeChangedCallback",value:function(name,last,current){return"modifier"===name?ModifierUtil.onModifierChanged(last,current,this,scheme):void 0}},{key:"attachedCallback",value:function(){var _this2=this;this._tryToEnsureNodePosition(),setImmediate(function(){return _this2._tryToEnsureNodePosition()})}},{key:"_tryToEnsureNodePosition",value:function(){if(this.parentNode&&!this.hasAttribute("inline")&&"ons-page"!==this.parentNode.nodeName.toLowerCase()){for(var page=this;;){if(page=page.parentNode,!page)return;if("ons-page"===page.nodeName.toLowerCase())break}page._registerToolbar(this)}}},{key:"_getToolbarLeftItemsElement",value:function(){return this.querySelector(".left")||ons._internal.nullElement}},{key:"_getToolbarCenterItemsElement",value:function(){return this.querySelector(".center")||ons._internal.nullElement}},{key:"_getToolbarRightItemsElement",value:function(){return this.querySelector(".right")||ons._internal.nullElement}},{key:"_getToolbarBackButtonLabelElement",value:function(){return this.querySelector("ons-back-button .back-button__label")||ons._internal.nullElement}},{key:"_compile",value:function(){var shouldAppendAndroidModifier=ons.platform.isAndroid()&&!this.hasAttribute("fixed-style"),inline=this.hasAttribute("inline");this.classList.add("navigation-bar"),shouldAppendAndroidModifier&&this.classList.add("navigation-bar--android"),inline||(this.style.position="absolute",this.style.zIndex="10000",this.style.left="0px",this.style.right="0px",this.style.top="0px"),this._ensureToolbarItemElements()}},{key:"_ensureToolbarItemElements",value:function(){for(var center,hasCenterClassElementOnly=1===this.children.length&&this.children[0].classList.contains("center"),i=0;i<this.childNodes.length;i++)1!=this.childNodes[i].nodeType&&this.removeChild(this.childNodes[i]);if(hasCenterClassElementOnly)center=this._ensureToolbarItemContainer("center");else{center=this._ensureToolbarItemContainer("center");var left=this._ensureToolbarItemContainer("left"),right=this._ensureToolbarItemContainer("right");if(this.children[0]!==left||this.children[1]!==center||this.children[2]!==right){left.parentNode&&this.removeChild(left),center.parentNode&&this.removeChild(center),right.parentNode&&this.removeChild(right);var fragment=document.createDocumentFragment();fragment.appendChild(left),fragment.appendChild(center),fragment.appendChild(right),this.appendChild(fragment)}}center.classList.add("navigation-bar__title")}},{key:"_ensureToolbarItemContainer",value:function(name){var container=ons._util.findChild(this,"."+name);return container||(container=document.createElement("div"),container.classList.add(name)),""===container.innerHTML.trim()&&(container.innerHTML="&nbsp;"),container.classList.add("navigation-bar__"+name),container}}]),ToolbarElement}(ons._BaseElement);window.OnsToolbarElement||(window.OnsToolbarElement=document.registerElement("ons-toolbar",{prototype:ToolbarElement.prototype}))}();
ajax/libs/primereact/6.5.0/accordion/accordion.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { UniqueComponentId, classNames, ObjectUtils, CSSTransition } from 'primereact/core'; function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var AccordionTab = /*#__PURE__*/function (_Component) { _inherits(AccordionTab, _Component); var _super = _createSuper(AccordionTab); function AccordionTab() { _classCallCheck(this, AccordionTab); return _super.apply(this, arguments); } return AccordionTab; }(Component); _defineProperty(AccordionTab, "defaultProps", { header: null, disabled: false, headerStyle: null, headerClassName: null, headerTemplate: null, contentStyle: null, contentClassName: null }); var Accordion = /*#__PURE__*/function (_Component2) { _inherits(Accordion, _Component2); var _super2 = _createSuper(Accordion); function Accordion(props) { var _this; _classCallCheck(this, Accordion); _this = _super2.call(this, props); var state = { id: _this.props.id }; if (!_this.props.onTabChange) { state = _objectSpread(_objectSpread({}, state), {}, { activeIndex: props.activeIndex }); } _this.state = state; _this.contentWrappers = []; return _this; } _createClass(Accordion, [{ key: "onTabHeaderClick", value: function onTabHeaderClick(event, tab, index) { if (!tab.props.disabled) { var selected = this.isSelected(index); var newActiveIndex = null; if (this.props.multiple) { var indexes = (this.props.onTabChange ? this.props.activeIndex : this.state.activeIndex) || []; if (selected) indexes = indexes.filter(function (i) { return i !== index; });else indexes = [].concat(_toConsumableArray(indexes), [index]); newActiveIndex = indexes; } else { newActiveIndex = selected ? null : index; } var callback = selected ? this.props.onTabClose : this.props.onTabOpen; if (callback) { callback({ originalEvent: event, index: index }); } if (this.props.onTabChange) { this.props.onTabChange({ originalEvent: event, index: newActiveIndex }); } else { this.setState({ activeIndex: newActiveIndex }); } } event.preventDefault(); } }, { key: "isSelected", value: function isSelected(index) { var activeIndex = this.props.onTabChange ? this.props.activeIndex : this.state.activeIndex; return this.props.multiple ? activeIndex && activeIndex.indexOf(index) >= 0 : activeIndex === index; } }, { key: "componentDidMount", value: function componentDidMount() { if (!this.state.id) { this.setState({ id: UniqueComponentId() }); } } }, { key: "renderTabHeader", value: function renderTabHeader(tab, selected, index) { var _classNames, _this2 = this; var tabHeaderClass = classNames('p-accordion-header', { 'p-highlight': selected, 'p-disabled': tab.props.disabled }, tab.props.headerClassName); var iconClassName = classNames('p-accordion-toggle-icon', (_classNames = {}, _defineProperty(_classNames, "".concat(this.props.expandIcon), !selected), _defineProperty(_classNames, "".concat(this.props.collapseIcon), selected), _classNames)); var id = this.state.id + '_header_' + index; var ariaControls = this.state.id + '_content_' + index; var tabIndex = tab.props.disabled ? -1 : null; var header = tab.props.headerTemplate ? ObjectUtils.getJSXElement(tab.props.headerTemplate, tab.props) : /*#__PURE__*/React.createElement("span", { className: "p-accordion-header-text" }, tab.props.header); return /*#__PURE__*/React.createElement("div", { className: tabHeaderClass, style: tab.props.headerStyle }, /*#__PURE__*/React.createElement("a", { href: '#' + ariaControls, id: id, className: "p-accordion-header-link", "aria-controls": ariaControls, role: "tab", "aria-expanded": selected, onClick: function onClick(event) { return _this2.onTabHeaderClick(event, tab, index); }, tabIndex: tabIndex }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), header)); } }, { key: "renderTabContent", value: function renderTabContent(tab, selected, index) { var className = classNames('p-toggleable-content', tab.props.contentClassName); var id = this.state.id + '_content_' + index; var toggleableContentRef = /*#__PURE__*/React.createRef(); return /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: toggleableContentRef, classNames: "p-toggleable-content", timeout: { enter: 1000, exit: 450 }, in: selected, unmountOnExit: true, options: this.props.transitionOptions }, /*#__PURE__*/React.createElement("div", { ref: toggleableContentRef, id: id, className: className, style: tab.props.contentStyle, role: "region", "aria-labelledby": this.state.id + '_header_' + index }, /*#__PURE__*/React.createElement("div", { className: "p-accordion-content" }, tab.props.children))); } }, { key: "renderTab", value: function renderTab(tab, index) { var selected = this.isSelected(index); var tabHeader = this.renderTabHeader(tab, selected, index); var tabContent = this.renderTabContent(tab, selected, index); var tabClassName = classNames('p-accordion-tab', { 'p-accordion-tab-active': selected }); return /*#__PURE__*/React.createElement("div", { key: tab.props.header, className: tabClassName }, tabHeader, tabContent); } }, { key: "renderTabs", value: function renderTabs() { var _this3 = this; return React.Children.map(this.props.children, function (tab, index) { if (tab && tab.type === AccordionTab) { return _this3.renderTab(tab, index); } }); } }, { key: "render", value: function render() { var _this4 = this; var className = classNames('p-accordion p-component', this.props.className); var tabs = this.renderTabs(); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this4.container = el; }, id: this.state.id, className: className, style: this.props.style }, tabs); } }]); return Accordion; }(Component); _defineProperty(Accordion, "defaultProps", { id: null, activeIndex: null, className: null, style: null, multiple: false, expandIcon: 'pi pi-chevron-right', collapseIcon: 'pi pi-chevron-down', transitionOptions: null, onTabOpen: null, onTabClose: null, onTabChange: null }); export { Accordion, AccordionTab };
src/元素/搜揣結果/index.spec.js
sih4sing5hong5/su5lui3-hun1kip4
import React from 'react' import { shallow } from 'enzyme' import 搜揣結果, { calItemSize } from './' import AutoSizer from 'react-virtualized-auto-sizer' it('算一逝的懸低', ()=>{ const tailoNum = 60 const baseHeight = 80 expect(calItemSize(tailoNum, baseHeight)).toEqual(baseHeight) }) it('算兩逝的懸低', ()=>{ const tailoNum = 71 const baseHeight = 80 expect(calItemSize(tailoNum, baseHeight)).toBeGreaterThan(baseHeight) }) it('無超過抽樣數 莫顯示結果', ()=>{ const wrapper = shallow( <搜揣結果 結果={[]} 抽樣數={10} />) expect(wrapper.find(AutoSizer)).toHaveLength(0) }) it('超過抽樣數 顯示結果', ()=>{ const wrapper = shallow( <搜揣結果 結果={[ {"篇號": 1, "逝號": 10, "句資料": {}}, {"篇號": 1, "逝號": 10, "句資料": {}}, ]} 抽樣數={1} />) expect(wrapper.find(AutoSizer)).toHaveLength(1) })
src/components/Player.js
xavi160/react-video
import React from 'react'; import stateReducer, { PLAY, PAUSE, SEEKING, SEEKED, VOLUME_CHANGED } from '../state'; import ControlledPlayer from './ControlledPlayer'; export default class Player extends React.Component { constructor(props) { super(props); this.state = stateReducer({ paused: true, currentTime: props.starttime || 0 }); this.onChange = this.onChange.bind(this); this.onPlay = this.onEvent.bind(this, PLAY); this.onPause = this.onEvent.bind(this, PAUSE); this.onSeeking = this.onEvent.bind(this, SEEKING); this.onSeeked = this.onEvent.bind(this, SEEKED); this.onVolumeChange = this.onVolumeChange.bind(this); } getChildContext() { return { playerState: this.state }; } onChange(action) { console.log(this, action); } onEvent(type, event) { event.persist(); this.setState((state) => stateReducer(state, { type, currentTime: event.target.currentTime })); } onVolumeChange(event) { event.persist(); this.setState((state) => stateReducer(state, { type: VOLUME_CHANGED, volume: event.target.volume, muted: event.target.muted })); } render() { return ( <ControlledPlayer {...this.props} playerState={this.state} onChange={this.onChange} onPlay={this.onPlay} onPause={this.onPause} onSeeking={this.onSeeking} onSeeked={this.onSeeked} onEnded={this.onPause} onVolumeChange={this.onVolumeChange} /> ); } } Player.propTypes = { children: React.PropTypes.node, starttime: React.PropTypes.number, nativeControls: React.PropTypes.bool }; Player.childContextTypes = { playerState: React.PropTypes.object.isRequired };
lib/components/Button.js
devinmarieb/budget-app
import React, { Component } from 'react' export default class Input extends Component { render() { const { text, handleClick, className, disabled } = this.props; return ( <button className={className} onClick={ handleClick } disabled={ disabled }> { text } </button> ); } }
ajax/libs/forerunnerdb/1.3.606/fdb-core.js
sufuf3/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":4,"../lib/Shim.IE8":29}],2:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.value === 1) { result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', result); } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (this.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', data); } // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, data); } // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param data * @param options * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visited === undefined) { resultArr._visited = 0; } resultArr._visited++; result = this.sortAsc(thisDataPathVal, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":25,"./Shared":28}],3:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Crc, Overload, ReactorIO, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); sharedPathSolver = new Path(); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', keyName, {oldData: oldKey}); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = new Date(); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = this.jStringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.emit('immediateChange', {type: 'truncate'}); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: updated }, options); op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); this.emit('immediateChange', {type: 'update', data: updated}); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.emit('immediateChange', {type: 'remove', data: returnArr}); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback(false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback(resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.emit('immediateChange', {type: 'insert', data: inserted}); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); self.chainSend('insert', doc, {index: index}); //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = this.jStringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = this.jStringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearchQuery, joinSearchOptions, joinMulti, joinRequire, joinFindResults, joinFindResult, joinItem, joinPrefix, joinMatchData, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, l, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinCollectionName]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB if (joinCollection[joinCollectionName]) { joinCollectionInstance = joinCollection[joinCollectionName]; } else { joinCollectionInstance = this._db.collection(joinCollectionName); } // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self._resolveDynamicQuery(joinMatchData.$query, resultArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatchData, resultArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultCollectionName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = resultArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; Collection.prototype._resolveDynamicQuery = function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = new Path(query.substr(3, query.length - 3)).value(item); } else { pathResult = new Path(query).value(item); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self._resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; case '2d': index = new Index2d(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); } else { self.insert(packet.data); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":5,"./Index2d":8,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":25,"./ReactorIO":26,"./Shared":28}],4:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":6,"./Metrics.js":12,"./Overload":24,"./Shared":28}],5:[function(_dereq_,module,exports){ "use strict"; /** * @mixin */ var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],6:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":3,"./Crc.js":5,"./Metrics.js":12,"./Overload":24,"./Shared":28}],7:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - rob@irrelon.com "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders; bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to longitude/latitude. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { latitude: lat, longitude: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; module.exports = GeoHash; },{}],8:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.lookup = function (query, options) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options) { var self = this, geoHash, neighbours, visited, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } // Get the lngLat geohash from the query geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision); // Calculate 9 box geohashes neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'}); // Lookup all matching co-ordinates from the btree results = []; visited = 0; for (i = 0; i < 9; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visited += search._visited; results = results.concat(search); } // Work with original data results = this._collection._primaryIndex.lookup(results); if (results.length) { distance = {}; // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { // Add item inside radius distance finalResults.push(results[i]); } } // Sort by distance from center finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":2,"./GeoHash":7,"./Path":25,"./Shared":28}],9:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query, options) { return this._btree.lookup(query, options); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":2,"./Path":25,"./Shared":28}],10:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":25,"./Shared":28}],11:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk]) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":28}],12:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":23,"./Shared":28}],13:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],14:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, data, options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],15:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return serialiser.parse(data); //return JSON.parse(data); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { return serialiser.stringify(data); //return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":24,"./Serialiser":27}],16:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],17:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":24}],18:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; } }; module.exports = Matching; },{}],19:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],20:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],21:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":24}],22:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":25,"./Shared":28}],24:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, name; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } name = typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload: ', def); throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],25:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":28}],26:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); delete this._listeners; } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":28}],27:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { this._encoder = []; this._decoder = {}; // Handler for Date() objects this.registerEncoder('$date', function (data) { if (data instanceof Date) { return data.toISOString(); } }); this.registerDecoder('$date', function (data) { return new Date(data); }); // Handler for RegExp() objects this.registerEncoder('$regexp', function (data) { if (data instanceof RegExp) { return { source: data.source, params: '' + (data.global ? 'g' : '') + (data.ignoreCase ? 'i' : '') }; } }); this.registerDecoder('$regexp', function (data) { var type = typeof data; if (type === 'object') { return new RegExp(data.source, data.params); } else if (type === 'string') { return new RegExp(data); } }); }; /** * Register an encoder that can handle encoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. * @param {Function} method The encoder method. */ Serialiser.prototype.registerEncoder = function (handles, method) { this._encoder.push(function (data) { var methodVal = method(data), returnObj; if (methodVal !== undefined) { returnObj = {}; returnObj[handles] = methodVal; } return returnObj; }); }; /** * Register a decoder that can handle decoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. When an object * has a field matching this handler name then this decode will be invoked * to provide a decoded version of the data that was previously encoded by * it's counterpart encoder method. * @param {Function} method The decoder method. */ Serialiser.prototype.registerDecoder = function (handles, method) { this._decoder[handles] = method; }; /** * Loops the encoders and asks each one if it wants to handle encoding for * the passed data object. If no value is returned (undefined) then the data * will be passed to the next encoder and so on. If a value is returned the * loop will break and the encoded data will be used. * @param {Object} data The data object to handle. * @returns {*} The encoded data. * @private */ Serialiser.prototype._encode = function (data) { // Loop the encoders and if a return value is given by an encoder // the loop will exit and return that value. var count = this._encoder.length, retVal; while (count-- && !retVal) { retVal = this._encoder[count](data); } return retVal; }; /** * Converts a previously encoded string back into an object. * @param {String} data The string to convert to an object. * @returns {Object} The reconstituted object. */ Serialiser.prototype.parse = function (data) { return this._parse(JSON.parse(data)); }; /** * Handles restoring an object with special data markers back into * it's original format. * @param {Object} data The object to recurse. * @param {Object=} target The target object to restore data to. * @returns {Object} The final restored object. * @private */ Serialiser.prototype._parse = function (data, target) { var i; if (typeof data === 'object' && data !== null) { if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and handle // special object types and restore them for (i in data) { if (data.hasOwnProperty(i)) { if (i.substr(0, 1) === '$' && this._decoder[i]) { // This is a special object type and a handler // exists, restore it return this._decoder[i](data[i]); } // Not a special object or no handler, recurse as normal target[i] = this._parse(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; /** * Converts an object to a encoded string representation. * @param {Object} data The object to encode. */ Serialiser.prototype.stringify = function (data) { return JSON.stringify(this._stringify(data)); }; /** * Recurse down an object and encode special objects so they can be * stringified and later restored. * @param {Object} data The object to parse. * @param {Object=} target The target object to store converted data to. * @returns {Object} The converted object. * @private */ Serialiser.prototype._stringify = function (data, target) { var handledData, i; if (typeof data === 'object' && data !== null) { // Handle special object types so they can be encoded with // a special marker and later restored by a decoder counterpart handledData = this._encode(data); if (handledData) { // An encoder handled this object type so return it now return handledData; } if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and serialise for (i in data) { if (data.hasOwnProperty(i)) { target[i] = this._stringify(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; module.exports = Serialiser; },{}],28:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.606', modules: {}, plugins: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Tags":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],29:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}]},{},[1]);
ajax/libs/rxjs/2.3.17/rx.lite.js
wenliang-developer/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; })(); var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); } var s = state; var id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new Error('No concurrency detected!'); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('', '*'); root.onmessage = oldHandler; return isAsync; } // Use in order, 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); })(); /** * 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)); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(arguments.length === 2 ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, arguments.length === 2 ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, arguments.length === 2 ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (err) { var self = this; this.queue.push(function () { self.observer.onError(err); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** * Creates 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(); } }); }); }; /** * 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); }); }); }; 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); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { return new AnonymousObservable(this.subscribe.bind(this)); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.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(); }); }); }; 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 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]; }); }; 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)); }); }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function createListener (element, name, handler) { if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } throw new Error('No listener found'); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (Object.prototype.toString.call(el) === '[object NodeList]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; // Check for Angular/jQuery/Zepto support var jq = !!root.angular && !!angular.element ? angular.element : (!!root.jQuery ? root.jQuery : ( !!root.Zepto ? root.Zepto : null)); // Check for ember var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; // Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs // for proper loading order! var marionette = !!root.Backbone && !!root.Backbone.Marionette; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { if (marionette) { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } if (ember) { return fromEventPattern( function (h) { Ember.addListener(element, eventName, h); }, function (h) { Ember.removeListener(element, eventName, h); }, selector); } if (jq) { var $elem = jq(element); return fromEventPattern( function (h) { $elem.on(eventName, h); }, function (h) { $elem.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { if (!subject.isDisposed) { subject.onNext(value); subject.onCompleted(); } }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.share(); * * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareValue(42); * * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, window, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, subject.subscribe.bind(subject)); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var count = 0, d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count++); self(d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The debounced sequence. */ observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; var subscription = source.subscribe( function (x) { hasvalue = true; value = x; id++; var currentId = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { hasvalue && id === currentId && observer.onNext(value); hasvalue = false; })); }, function (e) { cancelable.dispose(); observer.onError(e); hasvalue = false; id++; }, function () { cancelable.dispose(); hasvalue && observer.onNext(value); observer.onCompleted(); hasvalue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * @deprecated use #debounce or #throttleWithTimeout instead. */ observableProto.throttle = function(dueTime, scheduler) { deprecate('throttle', 'debounce or throttleWithTimeout'); return this.debounce(dueTime, scheduler); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { (other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout'))); isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); function createTimer() { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. * @returns {Observable} An Observable that performs the throttle operation. */ observableProto.throttleFirst = function (windowDuration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var duration = +windowDuration || 0; if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } var source = this; return new AnonymousObservable(function (observer) { var lastOnNext = 0; return source.subscribe( function (x) { var now = scheduler.now(); if (lastOnNext === 0 || now - lastOnNext >= duration) { lastOnNext = now; observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer) ); }); }; var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } _super.call(this, subscribe); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (observer) { var hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(2), err; function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { if (err) { observer.onError(err); return; } try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } if (isDone && values[1]) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, function (e) { if (values[1]) { observer.onError(e); } else { err = e; } }, function () { isDone = true; values[1] && observer.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, observer.onError.bind(observer), function () { isDone = true; next(true, 1); }) ); }); } var PausableBufferedObservable = (function (__super__) { inherits(PausableBufferedObservable, __super__); function subscribe(observer) { var q = [], previousShouldFire; var subscription = combineLatestSource( this.source, this.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { while (q.length > 0) { observer.onNext(q.shift()); } } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { observer.onNext(results.data); } else { q.push(results.data); } } }, function (err) { // Empty buffer before sending error while (q.length > 0) { observer.onNext(q.shift()); } observer.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var ControlledObservable = (function (_super) { inherits(ControlledObservable, _super); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { _super.call(this, subscribe); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = Rx.ControlledSubject = (function (_super) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, _super); function ControlledSubject(enableQueue) { if (enableQueue == null) { enableQueue = true; } _super.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { checkDisposed.call(this); this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } }, onError: function (error) { checkDisposed.call(this); this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } }, onNext: function (value) { checkDisposed.call(this); var hasRequested = false; if (this.requestedCount === 0) { if (this.enableQueue) { this.queue.push(value); } } else { if (this.requestedCount !== -1) { if (this.requestedCount-- === 0) { this.disposeCurrentRequest(); } } hasRequested = true; } if (hasRequested) { this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { //console.log('queue length', this.queue.length); while (this.queue.length >= numberOfItems && numberOfItems > 0) { //console.log('number of items', numberOfItems); this.subject.onNext(this.queue.shift()); numberOfItems--; } if (this.queue.length !== 0) { return { numberOfItems: numberOfItems, returnValue: true }; } else { return { numberOfItems: numberOfItems, returnValue: false }; } } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { checkDisposed.call(this); this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; }, dispose: function () { this.isDisposed = true; this.error = null; this.subject.dispose(); this.requestedDisposable.dispose(); } }); return ControlledSubject; }(Observable)); /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(observer) { return { init: function() { return observer; }, step: function(obs, input) { return obs.onNext(input); }, result: function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(observer) { var xform = transducer(transformForObserver(observer)); return source.subscribe( function(v) { try { xform.step(observer, v); } catch (e) { observer.onError(e); } }, observer.onError.bind(observer), function() { xform.result(observer); } ); }); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; this.exception = error; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); var n = this.q.length; for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { n++; so.onError(this.error); } else if (this.isStopped) { n++; so.onCompleted(); } so.ensureActive(n); return subscription; } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
app/javascript/mastodon/features/favourited_statuses/index.js
imomix/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import LoadingIndicator from '../../components/loading_indicator'; import { fetchFavouritedStatuses, expandFavouritedStatuses } from '../../actions/favourites'; import Column from '../ui/components/column'; import StatusList from '../../components/status_list'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ heading: { id: 'column.favourites', defaultMessage: 'Favourites' }, }); const mapStateToProps = state => ({ loaded: state.getIn(['status_lists', 'favourites', 'loaded']), }); class Favourites extends ImmutablePureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, loaded: PropTypes.bool, intl: PropTypes.object.isRequired, }; componentWillMount () { this.props.dispatch(fetchFavouritedStatuses()); } handleScrollToBottom = () => { this.props.dispatch(expandFavouritedStatuses()); } render () { const { loaded, intl } = this.props; if (!loaded) { return ( <Column> <LoadingIndicator /> </Column> ); } return ( <Column icon='star' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <StatusList {...this.props} scrollKey='favourited_statuses' onScrollToBottom={this.handleScrollToBottom} /> </Column> ); } } export default connect(mapStateToProps)(injectIntl(Favourites));
packages/benchmarks/src/implementations/inline-styles/Dot.js
necolas/react-native-web
import React from 'react'; const Dot = ({ size, x, y, children, color }) => ( <div style={{ ...styles.root, ...{ borderBottomColor: color, borderRightWidth: `${size / 2}px`, borderBottomWidth: `${size / 2}px`, borderLeftWidth: `${size / 2}px`, marginLeft: `${x}px`, marginTop: `${y}px` } }} > {children} </div> ); const styles = { root: { position: 'absolute', cursor: 'pointer', width: 0, height: 0, borderColor: 'transparent', borderStyle: 'solid', borderTopWidth: 0, transform: 'translate(50%, 50%)' } }; export default Dot;
mla_game/front-end/javascript/components/routes/preferences.js
WGBH/FixIt
import React from 'react' import UserForm from '../partials/user_form' import PreferencesForm from '../partials/preferences_form' import UserMessage from '../partials/user_message' class Preferences extends React.Component{ componentWillUnmount(){ this.props.fetchData() } render(){ return ( <div className="preferences"> <div className="user-form"> <div className="grid user-form-message"> <p>Below, you can customize the username that other players see in FIX IT.</p> </div> <div className="grid"> <span className="user">{this.props.initialData.username}</span> <UserForm data={this.props.initialData} setUsername={this.props.setUsername} /> </div> </div> <div className="message"> <div className="grid"> <UserMessage message={this.props.initialData.message} toggleMessage={this.props.setPreferencesMessage} isVisible={this.props.userMessages.messagePreferences} /> </div> </div> <PreferencesForm user={this.props.initialData.user[0].pk} topics={this.props.preferencesOptions.topics} source={this.props.preferencesOptions.source} preferred_topics={this.props.initialData.user[0].preferred_topics} preferred_stations={this.props.initialData.user[0].preferred_stations} /> </div> ) } }; export default Preferences;
dist/inspector/babylon.inspector.bundle.js
Kesshi/Babylon.js
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("babylonjs"),require("babylonjs-gui"),require("babylonjs-loaders"),require("babylonjs-materials"),require("babylonjs-serializers")):"function"==typeof define&&define.amd?define("babylonjs-inspector",["babylonjs","babylonjs-gui","babylonjs-loaders","babylonjs-materials","babylonjs-serializers"],t):"object"==typeof exports?exports["babylonjs-inspector"]=t(require("babylonjs"),require("babylonjs-gui"),require("babylonjs-loaders"),require("babylonjs-materials"),require("babylonjs-serializers")):e.INSPECTOR=t(e.BABYLON,e.BABYLON.GUI,e.BABYLON,e.BABYLON,e.BABYLON)}("undefined"!=typeof self?self:"undefined"!=typeof global?global:this,(function(e,t,r,n,a){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var a=t[n]={i:n,l:!1,exports:{}};return e[n].call(a.exports,a,a.exports,r),a.l=!0,a.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)r.d(n,a,function(t){return e[t]}.bind(null,a));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=17)}([function(e,t,r){"use strict";e.exports=r(18)},function(t,r){t.exports=e},function(e,t,r){e.exports=r(25)()},function(e,r){e.exports=t},function(e,t,r){"use strict"; /* object-assign (c) Sindre Sorhus @license MIT */var n=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;function i(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=function(){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={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(t).map((function(e){return t[e]})).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach((function(e){n[e]=e})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var r,l,s=i(e),p=1;p<arguments.length;p++){for(var c in r=Object(arguments[p]))a.call(r,c)&&(s[c]=r[c]);if(n){l=n(r);for(var u=0;u<l.length;u++)o.call(r,l[u])&&(s[l[u]]=r[l[u]])}}return s}},function(e,t,r){"use strict";!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE){0;try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}}}(),e.exports=r(19)},function(e,t,r){var n; /*! Copyright (c) 2017 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */!function(){"use strict";var r={}.hasOwnProperty;function a(){for(var e=[],t=0;t<arguments.length;t++){var n=arguments[t];if(n){var o=typeof n;if("string"===o||"number"===o)e.push(n);else if(Array.isArray(n)&&n.length){var i=a.apply(null,n);i&&e.push(i)}else if("object"===o)for(var l in n)r.call(n,l)&&n[l]&&e.push(l)}}return e.join(" ")}e.exports?(a.default=a,e.exports=a):void 0===(n=function(){return a}.apply(t,[]))||(e.exports=n)}()},function(e,t){e.exports=r},function(e,t,r){"use strict";var n=r(0),a=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i={base:{position:"absolute",userSelect:"none",MsUserSelect:"none"},top:{width:"100%",height:"10px",top:"-5px",left:"0px",cursor:"row-resize"},right:{width:"10px",height:"100%",top:"0px",right:"-5px",cursor:"col-resize"},bottom:{width:"100%",height:"10px",bottom:"-5px",left:"0px",cursor:"row-resize"},left:{width:"10px",height:"100%",top:"0px",left:"-5px",cursor:"col-resize"},topRight:{width:"20px",height:"20px",position:"absolute",right:"-10px",top:"-10px",cursor:"ne-resize"},bottomRight:{width:"20px",height:"20px",position:"absolute",right:"-10px",bottom:"-10px",cursor:"se-resize"},bottomLeft:{width:"20px",height:"20px",position:"absolute",left:"-10px",bottom:"-10px",cursor:"sw-resize"},topLeft:{width:"20px",height:"20px",position:"absolute",left:"-10px",top:"-10px",cursor:"nw-resize"}},l=function(e){return n.createElement("div",{className:e.className,style:o({},i.base,i[e.direction],e.replaceStyles||{}),onMouseDown:function(t){e.onResizeStart(t,e.direction)},onTouchStart:function(t){e.onResizeStart(t,e.direction)}},e.children)},s={userSelect:"none",MozUserSelect:"none",WebkitUserSelect:"none",MsUserSelect:"none"},p={userSelect:"auto",MozUserSelect:"auto",WebkitUserSelect:"auto",MsUserSelect:"auto"},c=function(e,t,r){return Math.max(Math.min(e,r),t)},u=function(e,t){return Math.round(e/t)*t},d=function(e,t){return t.reduce((function(t,r){return Math.abs(r-e)<Math.abs(t-e)?r:t}))},h=function(e,t){return e.substr(e.length-t.length,t.length)===t},b=function(e){return"auto"===e.toString()||h(e.toString(),"px")||h(e.toString(),"%")||h(e.toString(),"vh")||h(e.toString(),"vw")||h(e.toString(),"vmax")||h(e.toString(),"vmin")?e.toString():e+"px"},m=["style","className","grid","snap","bounds","size","defaultSize","minWidth","minHeight","maxWidth","maxHeight","lockAspectRatio","lockAspectRatioExtraWidth","lockAspectRatioExtraHeight","enable","handleStyles","handleClasses","handleWrapperStyle","handleWrapperClass","children","onResizeStart","onResize","onResizeStop","handleComponent"],g=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.state={isResizing:!1,resizeCursor:"auto",width:void 0===(r.propsSize&&r.propsSize.width)?"auto":r.propsSize&&r.propsSize.width,height:void 0===(r.propsSize&&r.propsSize.height)?"auto":r.propsSize&&r.propsSize.height,direction:"right",original:{x:0,y:0,width:0,height:0}},r.updateExtendsProps(e),r.onResizeStart=r.onResizeStart.bind(r),r.onMouseMove=r.onMouseMove.bind(r),r.onMouseUp=r.onMouseUp.bind(r),"undefined"!=typeof window&&(window.addEventListener("mouseup",r.onMouseUp),window.addEventListener("mousemove",r.onMouseMove),window.addEventListener("mouseleave",r.onMouseUp),window.addEventListener("touchmove",r.onMouseMove),window.addEventListener("touchend",r.onMouseUp)),r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),a(t,[{key:"updateExtendsProps",value:function(e){this.extendsProps=Object.keys(e).reduce((function(t,r){return-1!==m.indexOf(r)||(t[r]=e[r]),t}),{})}},{key:"getParentSize",value:function(){var e=this.base;if(!e)return{width:window.innerWidth,height:window.innerHeight};var t=!1,r=this.parentNode.style.flexWrap,n=e.style.minWidth;"wrap"!==r&&(t=!0,this.parentNode.style.flexWrap="wrap"),e.style.position="relative",e.style.minWidth="100%";var a={width:e.offsetWidth,height:e.offsetHeight};return e.style.position="absolute",t&&(this.parentNode.style.flexWrap=r),e.style.minWidth=n,a}},{key:"componentDidMount",value:function(){var e=this.size;this.setState({width:this.state.width||e.width,height:this.state.height||e.height});var t=this.parentNode;if(t instanceof HTMLElement&&!this.base){var r=document.createElement("div");r.style.width="100%",r.style.height="100%",r.style.position="absolute",r.style.transform="scale(0, 0)",r.style.left="0",r.style.flex="0",r.classList?r.classList.add("__resizable_base__"):r.className+="__resizable_base__",t.appendChild(r)}}},{key:"componentWillReceiveProps",value:function(e){this.updateExtendsProps(e)}},{key:"componentWillUnmount",value:function(){if("undefined"!=typeof window){window.removeEventListener("mouseup",this.onMouseUp),window.removeEventListener("mousemove",this.onMouseMove),window.removeEventListener("mouseleave",this.onMouseUp),window.removeEventListener("touchmove",this.onMouseMove),window.removeEventListener("touchend",this.onMouseUp);var e=this.parentNode,t=this.base;if(!t||!e)return;if(!(e instanceof HTMLElement&&t instanceof Node))return;e.removeChild(t)}}},{key:"calculateNewSize",value:function(e,t){var r=this.propsSize&&this.propsSize[t];return"auto"!==this.state[t]||this.state.original[t]!==e||void 0!==r&&"auto"!==r?e:"auto"}},{key:"onResizeStart",value:function(e,t){var r=0,n=0;if(e.nativeEvent instanceof MouseEvent){if(r=e.nativeEvent.clientX,n=e.nativeEvent.clientY,3===e.nativeEvent.which)return}else e.nativeEvent instanceof TouchEvent&&(r=e.nativeEvent.touches[0].clientX,n=e.nativeEvent.touches[0].clientY);this.props.onResizeStart&&this.props.onResizeStart(e,t,this.resizable),this.props.size&&(void 0!==this.props.size.height&&this.props.size.height!==this.state.height&&this.setState({height:this.props.size.height}),void 0!==this.props.size.width&&this.props.size.width!==this.state.width&&this.setState({width:this.props.size.width})),this.setState({original:{x:r,y:n,width:this.size.width,height:this.size.height},isResizing:!0,resizeCursor:window.getComputedStyle(e.target).cursor,direction:t})}},{key:"onMouseMove",value:function(e){if(this.state.isResizing){var t=e instanceof MouseEvent?e.clientX:e.touches[0].clientX,r=e instanceof MouseEvent?e.clientY:e.touches[0].clientY,n=this.state,a=n.direction,o=n.original,i=n.width,l=n.height,s=this.props,p=s.lockAspectRatio,b=s.lockAspectRatioExtraHeight,m=s.lockAspectRatioExtraWidth,g=this.props,f=g.maxWidth,v=g.maxHeight,y=g.minWidth,C=g.minHeight,E=this.getParentSize();if(f&&"string"==typeof f&&h(f,"%")){var O=Number(f.replace("%",""))/100;f=E.width*O}if(v&&"string"==typeof v&&h(v,"%")){var S=Number(v.replace("%",""))/100;v=E.height*S}if(y&&"string"==typeof y&&h(y,"%")){var x=Number(y.replace("%",""))/100;y=E.width*x}if(C&&"string"==typeof C&&h(C,"%")){var P=Number(C.replace("%",""))/100;C=E.height*P}f=void 0===f?void 0:Number(f),v=void 0===v?void 0:Number(v),y=void 0===y?void 0:Number(y),C=void 0===C?void 0:Number(C);var w="number"==typeof p?p:o.width/o.height,k=o.width,N=o.height;if(/right/i.test(a)&&(k=o.width+(t-o.x),p&&(N=(k-m)/w+b)),/left/i.test(a)&&(k=o.width-(t-o.x),p&&(N=(k-m)/w+b)),/bottom/i.test(a)&&(N=o.height+(r-o.y),p&&(k=(N-b)*w+m)),/top/i.test(a)&&(N=o.height-(r-o.y),p&&(k=(N-b)*w+m)),"parent"===this.props.bounds){var T=this.parentNode;if(T instanceof HTMLElement){var _=T.getBoundingClientRect(),M=_.left,L=_.top,D=this.resizable.getBoundingClientRect(),R=D.left,A=D.top,I=T.offsetWidth+(M-R),j=T.offsetHeight+(L-A);f=f&&f<I?f:I,v=v&&v<j?v:j}}else if("window"===this.props.bounds){if("undefined"!=typeof window){var z=this.resizable.getBoundingClientRect(),F=z.left,G=z.top,V=window.innerWidth-F,U=window.innerHeight-G;f=f&&f<V?f:V,v=v&&v<U?v:U}}else if(this.props.bounds instanceof HTMLElement){var H=this.props.bounds.getBoundingClientRect(),B=H.left,W=H.top,Y=this.resizable.getBoundingClientRect(),Z=Y.left,K=Y.top;if(!(this.props.bounds instanceof HTMLElement))return;var X=this.props.bounds.offsetWidth+(B-Z),Q=this.props.bounds.offsetHeight+(W-K);f=f&&f<X?f:X,v=v&&v<Q?v:Q}var q=void 0===y?10:y,$=void 0===f||f<0?k:f,J=void 0===C?10:C,ee=void 0===v||v<0?N:v;if(p){var te=(J-b)*w+m,re=(ee-b)*w+m,ne=(q-m)/w+b,ae=($-m)/w+b,oe=Math.max(q,te),ie=Math.min($,re),le=Math.max(J,ne),se=Math.min(ee,ae);k=c(k,oe,ie),N=c(N,le,se)}else k=c(k,q,$),N=c(N,J,ee);this.props.grid&&(k=u(k,this.props.grid[0])),this.props.grid&&(N=u(N,this.props.grid[1])),this.props.snap&&this.props.snap.x&&(k=d(k,this.props.snap.x)),this.props.snap&&this.props.snap.y&&(N=d(N,this.props.snap.y));var pe={width:k-o.width,height:N-o.height};if(i&&"string"==typeof i&&h(i,"%"))k=k/E.width*100+"%";if(l&&"string"==typeof l&&h(l,"%"))N=N/E.height*100+"%";this.setState({width:this.calculateNewSize(k,"width"),height:this.calculateNewSize(N,"height")}),this.props.onResize&&this.props.onResize(e,a,this.resizable,pe)}}},{key:"onMouseUp",value:function(e){var t=this.state,r=t.isResizing,n=t.direction,a=t.original;if(r){var o={width:this.size.width-a.width,height:this.size.height-a.height};this.props.onResizeStop&&this.props.onResizeStop(e,n,this.resizable,o),this.props.size&&this.setState(this.props.size),this.setState({isResizing:!1,resizeCursor:"auto"})}}},{key:"updateSize",value:function(e){this.setState({width:e.width,height:e.height})}},{key:"renderResizer",value:function(){var e=this,t=this.props,r=t.enable,a=t.handleStyles,o=t.handleClasses,i=t.handleWrapperStyle,s=t.handleWrapperClass,p=t.handleComponent;if(!r)return null;var c=Object.keys(r).map((function(t){return!1!==r[t]?n.createElement(l,{key:t,direction:t,onResizeStart:e.onResizeStart,replaceStyles:a&&a[t],className:o&&o[t]},p&&p[t]?n.createElement(p[t]):null):null}));return n.createElement("span",{className:s,style:i},c)}},{key:"render",value:function(){var e=this,t=this.state.isResizing?s:p;return n.createElement("div",o({ref:function(t){t&&(e.resizable=t)},style:o({position:"relative"},t,this.props.style,this.sizeStyle,{maxWidth:this.props.maxWidth,maxHeight:this.props.maxHeight,minWidth:this.props.minWidth,minHeight:this.props.minHeight,boxSizing:"border-box"}),className:this.props.className},this.extendsProps),this.state.isResizing&&n.createElement("div",{style:{height:"100%",width:"100%",backgroundColor:"rgba(0,0,0,0)",cursor:""+(this.state.resizeCursor||"auto"),opacity:"0",position:"fixed",zIndex:"9999",top:"0",left:"0",bottom:"0",right:"0"}}),this.props.children,this.renderResizer())}},{key:"parentNode",get:function(){return this.resizable.parentNode}},{key:"propsSize",get:function(){return this.props.size||this.props.defaultSize}},{key:"base",get:function(){var e=this.parentNode;if(e)for(var t=[].slice.call(e.children),r=0;r<t.length;r+=1){var n=t[r];if(n instanceof HTMLElement&&n.classList.contains("__resizable_base__"))return n}}},{key:"size",get:function(){var e=0,t=0;if("undefined"!=typeof window){var r=this.resizable.offsetWidth,n=this.resizable.offsetHeight,a=this.resizable.style.position;"relative"!==a&&(this.resizable.style.position="relative"),e="auto"!==this.resizable.style.width?this.resizable.offsetWidth:r,t="auto"!==this.resizable.style.height?this.resizable.offsetHeight:n,this.resizable.style.position=a}return{width:e,height:t}}},{key:"sizeStyle",get:function(){var e=this,t=this.props.size,r=function(t){if(void 0===e.state[t]||"auto"===e.state[t])return"auto";if(e.propsSize&&e.propsSize[t]&&h(e.propsSize[t].toString(),"%")){if(h(e.state[t].toString(),"%"))return e.state[t].toString();var r=e.getParentSize();return Number(e.state[t].toString().replace("px",""))/r[t]*100+"%"}return b(e.state[t])};return{width:t&&void 0!==t.width&&!this.state.isResizing?b(t.width):r("width"),height:t&&void 0!==t.height&&!this.state.isResizing?b(t.height):r("height")}}}]),t}(n.Component);g.defaultProps={onResizeStart:function(){},onResize:function(){},onResizeStop:function(){},enable:{top:!0,right:!0,bottom:!0,left:!0,topRight:!0,bottomRight:!0,bottomLeft:!0,topLeft:!0},style:{},grid:[1,1],lockAspectRatio:!1,lockAspectRatioExtraWidth:0,lockAspectRatioExtraHeight:0},e.exports=g},function(e,t,r){"use strict";var n,a=function(){return void 0===n&&(n=Boolean(window&&document&&document.all&&!window.atob)),n},o=function(){var e={};return function(t){if(void 0===e[t]){var r=document.querySelector(t);if(window.HTMLIFrameElement&&r instanceof window.HTMLIFrameElement)try{r=r.contentDocument.head}catch(e){r=null}e[t]=r}return e[t]}}(),i=[];function l(e){for(var t=-1,r=0;r<i.length;r++)if(i[r].identifier===e){t=r;break}return t}function s(e,t){for(var r={},n=[],a=0;a<e.length;a++){var o=e[a],s=t.base?o[0]+t.base:o[0],p=r[s]||0,c="".concat(s," ").concat(p);r[s]=p+1;var u=l(c),d={css:o[1],media:o[2],sourceMap:o[3]};-1!==u?(i[u].references++,i[u].updater(d)):i.push({identifier:c,updater:g(d,t),references:1}),n.push(c)}return n}function p(e){var t=document.createElement("style"),n=e.attributes||{};if(void 0===n.nonce){var a=r.nc;a&&(n.nonce=a)}if(Object.keys(n).forEach((function(e){t.setAttribute(e,n[e])})),"function"==typeof e.insert)e.insert(t);else{var i=o(e.insert||"head");if(!i)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");i.appendChild(t)}return t}var c,u=(c=[],function(e,t){return c[e]=t,c.filter(Boolean).join("\n")});function d(e,t,r,n){var a=r?"":n.media?"@media ".concat(n.media," {").concat(n.css,"}"):n.css;if(e.styleSheet)e.styleSheet.cssText=u(t,a);else{var o=document.createTextNode(a),i=e.childNodes;i[t]&&e.removeChild(i[t]),i.length?e.insertBefore(o,i[t]):e.appendChild(o)}}function h(e,t,r){var n=r.css,a=r.media,o=r.sourceMap;if(a?e.setAttribute("media",a):e.removeAttribute("media"),o&&btoa&&(n+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(o))))," */")),e.styleSheet)e.styleSheet.cssText=n;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(n))}}var b=null,m=0;function g(e,t){var r,n,a;if(t.singleton){var o=m++;r=b||(b=p(t)),n=d.bind(null,r,o,!1),a=d.bind(null,r,o,!0)}else r=p(t),n=h.bind(null,r,t),a=function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(r)};return n(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;n(e=t)}else a()}}e.exports=function(e,t){(t=t||{}).singleton||"boolean"==typeof t.singleton||(t.singleton=a());var r=s(e=e||[],t);return function(e){if(e=e||[],"[object Array]"===Object.prototype.toString.call(e)){for(var n=0;n<r.length;n++){var a=l(r[n]);i[a].references--}for(var o=s(e,t),p=0;p<r.length;p++){var c=l(r[p]);0===i[c].references&&(i[c].updater(),i.splice(c,1))}r=o}}}},function(e,t,r){"use strict";e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var r=function(e,t){var r=e[1]||"",n=e[3];if(!n)return r;if(t&&"function"==typeof btoa){var a=(i=n,l=btoa(unescape(encodeURIComponent(JSON.stringify(i)))),s="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(l),"/*# ".concat(s," */")),o=n.sources.map((function(e){return"/*# sourceURL=".concat(n.sourceRoot||"").concat(e," */")}));return[r].concat(o).concat([a]).join("\n")}var i,l,s;return[r].join("\n")}(t,e);return t[2]?"@media ".concat(t[2]," {").concat(r,"}"):r})).join("")},t.i=function(e,r,n){"string"==typeof e&&(e=[[null,e,""]]);var a={};if(n)for(var o=0;o<this.length;o++){var i=this[o][0];null!=i&&(a[i]=!0)}for(var l=0;l<e.length;l++){var s=[].concat(e[l]);n&&a[s[0]]||(r&&(s[2]?s[2]="".concat(r," and ").concat(s[2]):s[2]=r),t.push(s))}},t}},function(e,t){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t,r){"use strict";r.d(t,"a",(function(){return La})); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])})(e,t)};function a(e,t){function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var o=function(){return(o=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var a in t=arguments[r])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e}).apply(this,arguments)};function i(e,t,r,n){return new(r||(r=Promise))((function(a,o){function i(e){try{s(n.next(e))}catch(e){o(e)}}function l(e){try{s(n.throw(e))}catch(e){o(e)}}function s(e){var t;e.done?a(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,l)}s((n=n.apply(e,t||[])).next())}))}function l(e,t){var r,n,a,o,i={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function l(o){return function(l){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;i;)try{if(r=1,n&&(a=2&o[0]?n.return:o[0]?n.throw||((a=n.return)&&a.call(n),0):n.next)&&!(a=a.call(n,o[1])).done)return a;switch(n=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return i.label++,{value:o[1],done:!1};case 5:i.label++,n=o[1],o=[0];continue;case 7:o=i.ops.pop(),i.trys.pop();continue;default:if(!(a=i.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){i=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){i.label=o[1];break}if(6===o[0]&&i.label<a[1]){i.label=a[1],a=o;break}if(a&&i.label<a[2]){i.label=a[2],i.ops.push(o);break}a[2]&&i.ops.pop(),i.trys.pop();continue}o=t.call(e,i)}catch(e){o=[6,e],n=0}finally{r=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}Object.create;Object.create;var s=r(0),p=r.n(s),c=r(5),u=r(1),d=r(13),h=r(2),b=r.n(h);function m(e){return(m="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})(e)}function g(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function f(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function v(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?f(Object(r),!0).forEach((function(t){g(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):f(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function y(e,t){if(null==e)return{};var r,n,a=function(e,t){if(null==e)return{};var r,n,a={},o=Object.keys(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||(a[r]=e[r]);return a}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function C(e){return function(e){if(Array.isArray(e)){for(var t=0,r=new Array(e.length);t<e.length;t++)r[t]=e[t];return r}}(e)||function(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}function E(e){return t=e,(t-=0)==t?e:(e=e.replace(/[\-_\s]+(.)?/g,(function(e,t){return t?t.toUpperCase():""}))).substr(0,1).toLowerCase()+e.substr(1);var t}function O(e){return e.split(";").map((function(e){return e.trim()})).filter((function(e){return e})).reduce((function(e,t){var r,n=t.indexOf(":"),a=E(t.slice(0,n)),o=t.slice(n+1).trim();return a.startsWith("webkit")?e[(r=a,r.charAt(0).toUpperCase()+r.slice(1))]=o:e[a]=o,e}),{})}var S=!1;try{S=!0}catch(e){}function x(e){return null===e?null:"object"===m(e)&&e.prefix&&e.iconName?e:Array.isArray(e)&&2===e.length?{prefix:e[0],iconName:e[1]}:"string"==typeof e?{prefix:"fas",iconName:e}:void 0}function P(e,t){return Array.isArray(t)&&t.length>0||!Array.isArray(t)&&t?g({},e,t):{}}function w(e){var t=e.forwardedRef,r=y(e,["forwardedRef"]),n=r.icon,a=r.mask,o=r.symbol,i=r.className,l=r.title,s=x(n),p=P("classes",[].concat(C(function(e){var t,r=e.spin,n=e.pulse,a=e.fixedWidth,o=e.inverse,i=e.border,l=e.listItem,s=e.flip,p=e.size,c=e.rotation,u=e.pull,d=(g(t={"fa-spin":r,"fa-pulse":n,"fa-fw":a,"fa-inverse":o,"fa-border":i,"fa-li":l,"fa-flip-horizontal":"horizontal"===s||"both"===s,"fa-flip-vertical":"vertical"===s||"both"===s},"fa-".concat(p),null!=p),g(t,"fa-rotate-".concat(c),null!=c&&0!==c),g(t,"fa-pull-".concat(u),null!=u),g(t,"fa-swap-opacity",e.swapOpacity),t);return Object.keys(d).map((function(e){return d[e]?e:null})).filter((function(e){return e}))}(r)),C(i.split(" ")))),c=P("transform","string"==typeof r.transform?d.b.transform(r.transform):r.transform),u=P("mask",x(a)),h=Object(d.a)(s,v({},p,{},c,{},u,{symbol:o,title:l}));if(!h)return function(){var e;!S&&console&&"function"==typeof console.error&&(e=console).error.apply(e,arguments)}("Could not find icon",s),null;var b=h.abstract,m={ref:t};return Object.keys(r).forEach((function(e){w.defaultProps.hasOwnProperty(e)||(m[e]=r[e])})),k(b[0],m)}w.displayName="FontAwesomeIcon",w.propTypes={border:b.a.bool,className:b.a.string,mask:b.a.oneOfType([b.a.object,b.a.array,b.a.string]),fixedWidth:b.a.bool,inverse:b.a.bool,flip:b.a.oneOf(["horizontal","vertical","both"]),icon:b.a.oneOfType([b.a.object,b.a.array,b.a.string]),listItem:b.a.bool,pull:b.a.oneOf(["right","left"]),pulse:b.a.bool,rotation:b.a.oneOf([0,90,180,270]),size:b.a.oneOf(["lg","xs","sm","1x","2x","3x","4x","5x","6x","7x","8x","9x","10x"]),spin:b.a.bool,symbol:b.a.oneOfType([b.a.bool,b.a.string]),title:b.a.string,transform:b.a.oneOfType([b.a.string,b.a.object]),swapOpacity:b.a.bool},w.defaultProps={border:!1,className:"",mask:null,fixedWidth:!1,inverse:!1,flip:null,icon:null,listItem:!1,pull:null,pulse:!1,rotation:null,size:null,spin:!1,symbol:!1,title:"",transform:null,swapOpacity:!1};var k=function e(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if("string"==typeof r)return r;var a=(r.children||[]).map((function(r){return e(t,r)})),o=Object.keys(r.attributes||{}).reduce((function(e,t){var n=r.attributes[t];switch(t){case"class":e.attrs.className=n,delete r.attributes.class;break;case"style":e.attrs.style=O(n);break;default:0===t.indexOf("aria-")||0===t.indexOf("data-")?e.attrs[t.toLowerCase()]=n:e.attrs[E(t)]=n}return e}),{attrs:{}}),i=n.style,l=void 0===i?{}:i,s=y(n,["style"]);return o.attrs.style=v({},o.attrs.style,{},l),t.apply(void 0,[r.tag,v({},o.attrs,{},s)].concat(C(a)))}.bind(null,p.a.createElement),N=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.onSelect=function(e){this.props.onSelectedIndexChange(e)},t.prototype.renderLabel=function(e,t){var r=this,n=this.props.selectedIndex===t?"label active":"label";return s.createElement("div",{className:n,key:t,onClick:function(){return r.onSelect(t)},title:e.props.title},s.createElement("div",null,s.createElement(w,{icon:e.props.icon})))},t.prototype.render=function(){var e=this;return s.createElement("div",{className:"tabs",onContextMenu:function(e){return e.preventDefault()}},s.createElement("div",{className:"labels"},this.props.children.map((function(t,r){return e.renderLabel(t,r)}))),s.createElement("div",{className:"panes"},this.props.children[this.props.selectedIndex]))},t}(s.Component),T={prefix:"fas",iconName:"address-book",icon:[448,512,[],"f2b9","M436 160c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12h-20V48c0-26.5-21.5-48-48-48H48C21.5 0 0 21.5 0 48v416c0 26.5 21.5 48 48 48h320c26.5 0 48-21.5 48-48v-48h20c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12h-20v-64h20c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12h-20v-64h20zm-228-32c35.3 0 64 28.7 64 64s-28.7 64-64 64-64-28.7-64-64 28.7-64 64-64zm112 236.8c0 10.6-10 19.2-22.4 19.2H118.4C106 384 96 375.4 96 364.8v-19.2c0-31.8 30.1-57.6 67.2-57.6h5c12.3 5.1 25.7 8 39.8 8s27.6-2.9 39.8-8h5c37.1 0 67.2 25.8 67.2 57.6v19.2z"]},_={prefix:"fas",iconName:"arrow-left",icon:[448,512,[],"f060","M257.5 445.1l-22.2 22.2c-9.4 9.4-24.6 9.4-33.9 0L7 273c-9.4-9.4-9.4-24.6 0-33.9L201.4 44.7c9.4-9.4 24.6-9.4 33.9 0l22.2 22.2c9.5 9.5 9.3 25-.4 34.3L136.6 216H424c13.3 0 24 10.7 24 24v32c0 13.3-10.7 24-24 24H136.6l120.5 114.8c9.8 9.3 10 24.8.4 34.3z"]},M={prefix:"fas",iconName:"arrows-alt",icon:[512,512,[],"f0b2","M352.201 425.775l-79.196 79.196c-9.373 9.373-24.568 9.373-33.941 0l-79.196-79.196c-15.119-15.119-4.411-40.971 16.971-40.97h51.162L228 284H127.196v51.162c0 21.382-25.851 32.09-40.971 16.971L7.029 272.937c-9.373-9.373-9.373-24.569 0-33.941L86.225 159.8c15.119-15.119 40.971-4.411 40.971 16.971V228H228V127.196h-51.23c-21.382 0-32.09-25.851-16.971-40.971l79.196-79.196c9.373-9.373 24.568-9.373 33.941 0l79.196 79.196c15.119 15.119 4.411 40.971-16.971 40.971h-51.162V228h100.804v-51.162c0-21.382 25.851-32.09 40.97-16.971l79.196 79.196c9.373 9.373 9.373 24.569 0 33.941L425.773 352.2c-15.119 15.119-40.971 4.411-40.97-16.971V284H284v100.804h51.23c21.382 0 32.09 25.851 16.971 40.971z"]},L={prefix:"fas",iconName:"ban",icon:[512,512,[],"f05e","M256 8C119.034 8 8 119.033 8 256s111.034 248 248 248 248-111.034 248-248S392.967 8 256 8zm130.108 117.892c65.448 65.448 70 165.481 20.677 235.637L150.47 105.216c70.204-49.356 170.226-44.735 235.638 20.676zM125.892 386.108c-65.448-65.448-70-165.481-20.677-235.637L361.53 406.784c-70.203 49.356-170.226 44.736-235.638-20.676z"]},D={prefix:"fas",iconName:"bone",icon:[640,512,[],"f5d7","M598.88 244.56c25.2-12.6 41.12-38.36 41.12-66.53v-7.64C640 129.3 606.7 96 565.61 96c-32.02 0-60.44 20.49-70.57 50.86-7.68 23.03-11.6 45.14-38.11 45.14H183.06c-27.38 0-31.58-25.54-38.11-45.14C134.83 116.49 106.4 96 74.39 96 33.3 96 0 129.3 0 170.39v7.64c0 28.17 15.92 53.93 41.12 66.53 9.43 4.71 9.43 18.17 0 22.88C15.92 280.04 0 305.8 0 333.97v7.64C0 382.7 33.3 416 74.38 416c32.02 0 60.44-20.49 70.57-50.86 7.68-23.03 11.6-45.14 38.11-45.14h273.87c27.38 0 31.58 25.54 38.11 45.14C505.17 395.51 533.6 416 565.61 416c41.08 0 74.38-33.3 74.38-74.39v-7.64c0-28.18-15.92-53.93-41.12-66.53-9.42-4.71-9.42-18.17.01-22.88z"]},R={prefix:"fas",iconName:"braille",icon:[640,512,[],"f2a1","M128 256c0 35.346-28.654 64-64 64S0 291.346 0 256s28.654-64 64-64 64 28.654 64 64zM64 384c-17.673 0-32 14.327-32 32s14.327 32 32 32 32-14.327 32-32-14.327-32-32-32zm0-352C28.654 32 0 60.654 0 96s28.654 64 64 64 64-28.654 64-64-28.654-64-64-64zm160 192c-17.673 0-32 14.327-32 32s14.327 32 32 32 32-14.327 32-32-14.327-32-32-32zm0 160c-17.673 0-32 14.327-32 32s14.327 32 32 32 32-14.327 32-32-14.327-32-32-32zm0-352c-35.346 0-64 28.654-64 64s28.654 64 64 64 64-28.654 64-64-28.654-64-64-64zm224 192c-17.673 0-32 14.327-32 32s14.327 32 32 32 32-14.327 32-32-14.327-32-32-32zm0 160c-17.673 0-32 14.327-32 32s14.327 32 32 32 32-14.327 32-32-14.327-32-32-32zm0-352c-35.346 0-64 28.654-64 64s28.654 64 64 64 64-28.654 64-64-28.654-64-64-64zm160 192c-17.673 0-32 14.327-32 32s14.327 32 32 32 32-14.327 32-32-14.327-32-32-32zm0 160c-17.673 0-32 14.327-32 32s14.327 32 32 32 32-14.327 32-32-14.327-32-32-32zm0-320c-17.673 0-32 14.327-32 32s14.327 32 32 32 32-14.327 32-32-14.327-32-32-32z"]},A={prefix:"fas",iconName:"brush",icon:[384,512,[],"f55d","M352 0H32C14.33 0 0 14.33 0 32v224h384V32c0-17.67-14.33-32-32-32zM0 320c0 35.35 28.66 64 64 64h64v64c0 35.35 28.66 64 64 64s64-28.65 64-64v-64h64c35.34 0 64-28.65 64-64v-32H0v32zm192 104c13.25 0 24 10.74 24 24 0 13.25-10.75 24-24 24s-24-10.75-24-24c0-13.26 10.75-24 24-24z"]},I={prefix:"fas",iconName:"bug",icon:[512,512,[],"f188","M511.988 288.9c-.478 17.43-15.217 31.1-32.653 31.1H424v16c0 21.864-4.882 42.584-13.6 61.145l60.228 60.228c12.496 12.497 12.496 32.758 0 45.255-12.498 12.497-32.759 12.496-45.256 0l-54.736-54.736C345.886 467.965 314.351 480 280 480V236c0-6.627-5.373-12-12-12h-24c-6.627 0-12 5.373-12 12v244c-34.351 0-65.886-12.035-90.636-32.108l-54.736 54.736c-12.498 12.497-32.759 12.496-45.256 0-12.496-12.497-12.496-32.758 0-45.255l60.228-60.228C92.882 378.584 88 357.864 88 336v-16H32.666C15.23 320 .491 306.33.013 288.9-.484 270.816 14.028 256 32 256h56v-58.745l-46.628-46.628c-12.496-12.497-12.496-32.758 0-45.255 12.498-12.497 32.758-12.497 45.256 0L141.255 160h229.489l54.627-54.627c12.498-12.497 32.758-12.497 45.256 0 12.496 12.497 12.496 32.758 0 45.255L424 197.255V256h56c17.972 0 32.484 14.816 31.988 32.9zM257 0c-61.856 0-112 50.144-112 112h224C369 50.144 318.856 0 257 0z"]},j={prefix:"fas",iconName:"camera",icon:[512,512,[],"f030","M512 144v288c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V144c0-26.5 21.5-48 48-48h88l12.3-32.9c7-18.7 24.9-31.1 44.9-31.1h125.5c20 0 37.9 12.4 44.9 31.1L376 96h88c26.5 0 48 21.5 48 48zM376 288c0-66.2-53.8-120-120-120s-120 53.8-120 120 53.8 120 120 120 120-53.8 120-120zm-32 0c0 48.5-39.5 88-88 88s-88-39.5-88-88 39.5-88 88-88 88 39.5 88 88z"]},z={prefix:"fas",iconName:"chart-bar",icon:[512,512,[],"f080","M332.8 320h38.4c6.4 0 12.8-6.4 12.8-12.8V172.8c0-6.4-6.4-12.8-12.8-12.8h-38.4c-6.4 0-12.8 6.4-12.8 12.8v134.4c0 6.4 6.4 12.8 12.8 12.8zm96 0h38.4c6.4 0 12.8-6.4 12.8-12.8V76.8c0-6.4-6.4-12.8-12.8-12.8h-38.4c-6.4 0-12.8 6.4-12.8 12.8v230.4c0 6.4 6.4 12.8 12.8 12.8zm-288 0h38.4c6.4 0 12.8-6.4 12.8-12.8v-70.4c0-6.4-6.4-12.8-12.8-12.8h-38.4c-6.4 0-12.8 6.4-12.8 12.8v70.4c0 6.4 6.4 12.8 12.8 12.8zm96 0h38.4c6.4 0 12.8-6.4 12.8-12.8V108.8c0-6.4-6.4-12.8-12.8-12.8h-38.4c-6.4 0-12.8 6.4-12.8 12.8v198.4c0 6.4 6.4 12.8 12.8 12.8zM496 384H64V80c0-8.84-7.16-16-16-16H16C7.16 64 0 71.16 0 80v336c0 17.67 14.33 32 32 32h464c8.84 0 16-7.16 16-16v-32c0-8.84-7.16-16-16-16z"]},F={prefix:"fas",iconName:"check",icon:[512,512,[],"f00c","M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z"]},G={prefix:"fas",iconName:"chevron-down",icon:[448,512,[],"f078","M207.029 381.476L12.686 187.132c-9.373-9.373-9.373-24.569 0-33.941l22.667-22.667c9.357-9.357 24.522-9.375 33.901-.04L224 284.505l154.745-154.021c9.379-9.335 24.544-9.317 33.901.04l22.667 22.667c9.373 9.373 9.373 24.569 0 33.941L240.971 381.476c-9.373 9.372-24.569 9.372-33.942 0z"]},V={prefix:"fas",iconName:"code-branch",icon:[384,512,[],"f126","M384 144c0-44.2-35.8-80-80-80s-80 35.8-80 80c0 36.4 24.3 67.1 57.5 76.8-.6 16.1-4.2 28.5-11 36.9-15.4 19.2-49.3 22.4-85.2 25.7-28.2 2.6-57.4 5.4-81.3 16.9v-144c32.5-10.2 56-40.5 56-76.3 0-44.2-35.8-80-80-80S0 35.8 0 80c0 35.8 23.5 66.1 56 76.3v199.3C23.5 365.9 0 396.2 0 432c0 44.2 35.8 80 80 80s80-35.8 80-80c0-34-21.2-63.1-51.2-74.6 3.1-5.2 7.8-9.8 14.9-13.4 16.2-8.2 40.4-10.4 66.1-12.8 42.2-3.9 90-8.4 118.2-43.4 14-17.4 21.1-39.8 21.6-67.9 31.6-10.8 54.4-40.7 54.4-75.9zM80 64c8.8 0 16 7.2 16 16s-7.2 16-16 16-16-7.2-16-16 7.2-16 16-16zm0 384c-8.8 0-16-7.2-16-16s7.2-16 16-16 16 7.2 16 16-7.2 16-16 16zm224-320c8.8 0 16 7.2 16 16s-7.2 16-16 16-16-7.2-16-16 7.2-16 16-16z"]},U={prefix:"fas",iconName:"cog",icon:[512,512,[],"f013","M487.4 315.7l-42.6-24.6c4.3-23.2 4.3-47 0-70.2l42.6-24.6c4.9-2.8 7.1-8.6 5.5-14-11.1-35.6-30-67.8-54.7-94.6-3.8-4.1-10-5.1-14.8-2.3L380.8 110c-17.9-15.4-38.5-27.3-60.8-35.1V25.8c0-5.6-3.9-10.5-9.4-11.7-36.7-8.2-74.3-7.8-109.2 0-5.5 1.2-9.4 6.1-9.4 11.7V75c-22.2 7.9-42.8 19.8-60.8 35.1L88.7 85.5c-4.9-2.8-11-1.9-14.8 2.3-24.7 26.7-43.6 58.9-54.7 94.6-1.7 5.4.6 11.2 5.5 14L67.3 221c-4.3 23.2-4.3 47 0 70.2l-42.6 24.6c-4.9 2.8-7.1 8.6-5.5 14 11.1 35.6 30 67.8 54.7 94.6 3.8 4.1 10 5.1 14.8 2.3l42.6-24.6c17.9 15.4 38.5 27.3 60.8 35.1v49.2c0 5.6 3.9 10.5 9.4 11.7 36.7 8.2 74.3 7.8 109.2 0 5.5-1.2 9.4-6.1 9.4-11.7v-49.2c22.2-7.9 42.8-19.8 60.8-35.1l42.6 24.6c4.9 2.8 11 1.9 14.8-2.3 24.7-26.7 43.6-58.9 54.7-94.6 1.5-5.5-.7-11.3-5.6-14.1zM256 336c-44.1 0-80-35.9-80-80s35.9-80 80-80 80 35.9 80 80-35.9 80-80 80z"]},H={prefix:"fas",iconName:"compress",icon:[448,512,[],"f066","M436 192H312c-13.3 0-24-10.7-24-24V44c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v84h84c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm-276-24V44c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v84H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h124c13.3 0 24-10.7 24-24zm0 300V344c0-13.3-10.7-24-24-24H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h84v84c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-84h84c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12H312c-13.3 0-24 10.7-24 24v124c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12z"]},B={prefix:"fas",iconName:"crosshairs",icon:[512,512,[],"f05b","M500 224h-30.364C455.724 130.325 381.675 56.276 288 42.364V12c0-6.627-5.373-12-12-12h-40c-6.627 0-12 5.373-12 12v30.364C130.325 56.276 56.276 130.325 42.364 224H12c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h30.364C56.276 381.675 130.325 455.724 224 469.636V500c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12v-30.364C381.675 455.724 455.724 381.675 469.636 288H500c6.627 0 12-5.373 12-12v-40c0-6.627-5.373-12-12-12zM288 404.634V364c0-6.627-5.373-12-12-12h-40c-6.627 0-12 5.373-12 12v40.634C165.826 392.232 119.783 346.243 107.366 288H148c6.627 0 12-5.373 12-12v-40c0-6.627-5.373-12-12-12h-40.634C119.768 165.826 165.757 119.783 224 107.366V148c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12v-40.634C346.174 119.768 392.217 165.757 404.634 224H364c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h40.634C392.232 346.174 346.243 392.217 288 404.634zM288 256c0 17.673-14.327 32-32 32s-32-14.327-32-32c0-17.673 14.327-32 32-32s32 14.327 32 32z"]},W={prefix:"fas",iconName:"cube",icon:[512,512,[],"f1b2","M239.1 6.3l-208 78c-18.7 7-31.1 25-31.1 45v225.1c0 18.2 10.3 34.8 26.5 42.9l208 104c13.5 6.8 29.4 6.8 42.9 0l208-104c16.3-8.1 26.5-24.8 26.5-42.9V129.3c0-20-12.4-37.9-31.1-44.9l-208-78C262 2.2 250 2.2 239.1 6.3zM256 68.4l192 72v1.1l-192 78-192-78v-1.1l192-72zm32 356V275.5l160-65v133.9l-160 80z"]},Y={prefix:"fas",iconName:"ellipsis-h",icon:[512,512,[],"f141","M328 256c0 39.8-32.2 72-72 72s-72-32.2-72-72 32.2-72 72-72 72 32.2 72 72zm104-72c-39.8 0-72 32.2-72 72s32.2 72 72 72 72-32.2 72-72-32.2-72-72-72zm-352 0c-39.8 0-72 32.2-72 72s32.2 72 72 72 72-32.2 72-72-32.2-72-72-72z"]},Z={prefix:"fas",iconName:"expand-arrows-alt",icon:[448,512,[],"f31e","M448 344v112a23.94 23.94 0 0 1-24 24H312c-21.39 0-32.09-25.9-17-41l36.2-36.2L224 295.6 116.77 402.9 153 439c15.09 15.1 4.39 41-17 41H24a23.94 23.94 0 0 1-24-24V344c0-21.4 25.89-32.1 41-17l36.19 36.2L184.46 256 77.18 148.7 41 185c-15.1 15.1-41 4.4-41-17V56a23.94 23.94 0 0 1 24-24h112c21.39 0 32.09 25.9 17 41l-36.2 36.2L224 216.4l107.23-107.3L295 73c-15.09-15.1-4.39-41 17-41h112a23.94 23.94 0 0 1 24 24v112c0 21.4-25.89 32.1-41 17l-36.19-36.2L263.54 256l107.28 107.3L407 327.1c15.1-15.2 41-4.5 41 16.9z"]},K={prefix:"fas",iconName:"eye",icon:[576,512,[],"f06e","M572.52 241.4C518.29 135.59 410.93 64 288 64S57.68 135.64 3.48 241.41a32.35 32.35 0 0 0 0 29.19C57.71 376.41 165.07 448 288 448s230.32-71.64 284.52-177.41a32.35 32.35 0 0 0 0-29.19zM288 400a144 144 0 1 1 144-144 143.93 143.93 0 0 1-144 144zm0-240a95.31 95.31 0 0 0-25.31 3.79 47.85 47.85 0 0 1-66.9 66.9A95.78 95.78 0 1 0 288 160z"]},X={prefix:"fas",iconName:"eye-slash",icon:[640,512,[],"f070","M320 400c-75.85 0-137.25-58.71-142.9-133.11L72.2 185.82c-13.79 17.3-26.48 35.59-36.72 55.59a32.35 32.35 0 0 0 0 29.19C89.71 376.41 197.07 448 320 448c26.91 0 52.87-4 77.89-10.46L346 397.39a144.13 144.13 0 0 1-26 2.61zm313.82 58.1l-110.55-85.44a331.25 331.25 0 0 0 81.25-102.07 32.35 32.35 0 0 0 0-29.19C550.29 135.59 442.93 64 320 64a308.15 308.15 0 0 0-147.32 37.7L45.46 3.37A16 16 0 0 0 23 6.18L3.37 31.45A16 16 0 0 0 6.18 53.9l588.36 454.73a16 16 0 0 0 22.46-2.81l19.64-25.27a16 16 0 0 0-2.82-22.45zm-183.72-142l-39.3-30.38A94.75 94.75 0 0 0 416 256a94.76 94.76 0 0 0-121.31-92.21A47.65 47.65 0 0 1 304 192a46.64 46.64 0 0 1-1.54 10l-73.61-56.89A142.31 142.31 0 0 1 320 112a143.92 143.92 0 0 1 144 144c0 21.63-5.29 41.79-13.9 60.11z"]},Q={prefix:"fas",iconName:"file-alt",icon:[384,512,[],"f15c","M224 136V0H24C10.7 0 0 10.7 0 24v464c0 13.3 10.7 24 24 24h336c13.3 0 24-10.7 24-24V160H248c-13.2 0-24-10.8-24-24zm64 236c0 6.6-5.4 12-12 12H108c-6.6 0-12-5.4-12-12v-8c0-6.6 5.4-12 12-12h168c6.6 0 12 5.4 12 12v8zm0-64c0 6.6-5.4 12-12 12H108c-6.6 0-12-5.4-12-12v-8c0-6.6 5.4-12 12-12h168c6.6 0 12 5.4 12 12v8zm0-72v8c0 6.6-5.4 12-12 12H108c-6.6 0-12-5.4-12-12v-8c0-6.6 5.4-12 12-12h168c6.6 0 12 5.4 12 12zm96-114.1v6.1H256V0h6.1c6.4 0 12.5 2.5 17 7l97.9 98c4.5 4.5 7 10.6 7 16.9z"]},q={prefix:"fas",iconName:"film",icon:[512,512,[],"f008","M488 64h-8v20c0 6.6-5.4 12-12 12h-40c-6.6 0-12-5.4-12-12V64H96v20c0 6.6-5.4 12-12 12H44c-6.6 0-12-5.4-12-12V64h-8C10.7 64 0 74.7 0 88v336c0 13.3 10.7 24 24 24h8v-20c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v20h320v-20c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v20h8c13.3 0 24-10.7 24-24V88c0-13.3-10.7-24-24-24zM96 372c0 6.6-5.4 12-12 12H44c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40zm0-96c0 6.6-5.4 12-12 12H44c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40zm0-96c0 6.6-5.4 12-12 12H44c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40zm272 208c0 6.6-5.4 12-12 12H156c-6.6 0-12-5.4-12-12v-96c0-6.6 5.4-12 12-12h200c6.6 0 12 5.4 12 12v96zm0-168c0 6.6-5.4 12-12 12H156c-6.6 0-12-5.4-12-12v-96c0-6.6 5.4-12 12-12h200c6.6 0 12 5.4 12 12v96zm112 152c0 6.6-5.4 12-12 12h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40zm0-96c0 6.6-5.4 12-12 12h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40zm0-96c0 6.6-5.4 12-12 12h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40z"]},$={prefix:"fas",iconName:"ghost",icon:[384,512,[],"f6e2","M186.1.09C81.01 3.24 0 94.92 0 200.05v263.92c0 14.26 17.23 21.39 27.31 11.31l24.92-18.53c6.66-4.95 16-3.99 21.51 2.21l42.95 48.35c6.25 6.25 16.38 6.25 22.63 0l40.72-45.85c6.37-7.17 17.56-7.17 23.92 0l40.72 45.85c6.25 6.25 16.38 6.25 22.63 0l42.95-48.35c5.51-6.2 14.85-7.17 21.51-2.21l24.92 18.53c10.08 10.08 27.31 2.94 27.31-11.31V192C384 84 294.83-3.17 186.1.09zM128 224c-17.67 0-32-14.33-32-32s14.33-32 32-32 32 14.33 32 32-14.33 32-32 32zm128 0c-17.67 0-32-14.33-32-32s14.33-32 32-32 32 14.33 32 32-14.33 32-32 32z"]},J={prefix:"fas",iconName:"highlighter",icon:[544,512,[],"f591","M0 479.98L99.92 512l35.45-35.45-67.04-67.04L0 479.98zm124.61-240.01a36.592 36.592 0 0 0-10.79 38.1l13.05 42.83-50.93 50.94 96.23 96.23 50.86-50.86 42.74 13.08c13.73 4.2 28.65-.01 38.15-10.78l35.55-41.64-173.34-173.34-41.52 35.44zm403.31-160.7l-63.2-63.2c-20.49-20.49-53.38-21.52-75.12-2.35L190.55 183.68l169.77 169.78L530.27 154.4c19.18-21.74 18.15-54.63-2.35-75.13z"]},ee={prefix:"fas",iconName:"image",icon:[512,512,[],"f03e","M464 448H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h416c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48zM112 120c-30.928 0-56 25.072-56 56s25.072 56 56 56 56-25.072 56-56-25.072-56-56-56zM64 384h384V272l-87.515-87.515c-4.686-4.686-12.284-4.686-16.971 0L208 320l-55.515-55.515c-4.686-4.686-12.284-4.686-16.971 0L64 336v48z"]},te={prefix:"fas",iconName:"layer-group",icon:[512,512,[],"f5fd","M12.41 148.02l232.94 105.67c6.8 3.09 14.49 3.09 21.29 0l232.94-105.67c16.55-7.51 16.55-32.52 0-40.03L266.65 2.31a25.607 25.607 0 0 0-21.29 0L12.41 107.98c-16.55 7.51-16.55 32.53 0 40.04zm487.18 88.28l-58.09-26.33-161.64 73.27c-7.56 3.43-15.59 5.17-23.86 5.17s-16.29-1.74-23.86-5.17L70.51 209.97l-58.1 26.33c-16.55 7.5-16.55 32.5 0 40l232.94 105.59c6.8 3.08 14.49 3.08 21.29 0L499.59 276.3c16.55-7.5 16.55-32.5 0-40zm0 127.8l-57.87-26.23-161.86 73.37c-7.56 3.43-15.59 5.17-23.86 5.17s-16.29-1.74-23.86-5.17L70.29 337.87 12.41 364.1c-16.55 7.5-16.55 32.5 0 40l232.94 105.59c6.8 3.08 14.49 3.08 21.29 0L499.59 404.1c16.55-7.5 16.55-32.5 0-40z"]},re={prefix:"fas",iconName:"lightbulb",icon:[352,512,[],"f0eb","M96.06 454.35c.01 6.29 1.87 12.45 5.36 17.69l17.09 25.69a31.99 31.99 0 0 0 26.64 14.28h61.71a31.99 31.99 0 0 0 26.64-14.28l17.09-25.69a31.989 31.989 0 0 0 5.36-17.69l.04-38.35H96.01l.05 38.35zM0 176c0 44.37 16.45 84.85 43.56 115.78 16.52 18.85 42.36 58.23 52.21 91.45.04.26.07.52.11.78h160.24c.04-.26.07-.51.11-.78 9.85-33.22 35.69-72.6 52.21-91.45C335.55 260.85 352 220.37 352 176 352 78.61 272.91-.3 175.45 0 73.44.31 0 82.97 0 176zm176-80c-44.11 0-80 35.89-80 80 0 8.84-7.16 16-16 16s-16-7.16-16-16c0-61.76 50.24-112 112-112 8.84 0 16 7.16 16 16s-7.16 16-16 16z"]},ne={prefix:"fas",iconName:"magic",icon:[512,512,[],"f0d0","M224 96l16-32 32-16-32-16-16-32-16 32-32 16 32 16 16 32zM80 160l26.66-53.33L160 80l-53.34-26.67L80 0 53.34 53.33 0 80l53.34 26.67L80 160zm352 128l-26.66 53.33L352 368l53.34 26.67L432 448l26.66-53.33L512 368l-53.34-26.67L432 288zm70.62-193.77L417.77 9.38C411.53 3.12 403.34 0 395.15 0c-8.19 0-16.38 3.12-22.63 9.38L9.38 372.52c-12.5 12.5-12.5 32.76 0 45.25l84.85 84.85c6.25 6.25 14.44 9.37 22.62 9.37 8.19 0 16.38-3.12 22.63-9.37l363.14-363.15c12.5-12.48 12.5-32.75 0-45.24zM359.45 203.46l-50.91-50.91 86.6-86.6 50.91 50.91-86.6 86.6z"]},ae={prefix:"fas",iconName:"minus",icon:[448,512,[],"f068","M416 208H32c-17.67 0-32 14.33-32 32v32c0 17.67 14.33 32 32 32h384c17.67 0 32-14.33 32-32v-32c0-17.67-14.33-32-32-32z"]},oe={prefix:"fas",iconName:"object-group",icon:[512,512,[],"f247","M480 128V96h20c6.627 0 12-5.373 12-12V44c0-6.627-5.373-12-12-12h-40c-6.627 0-12 5.373-12 12v20H64V44c0-6.627-5.373-12-12-12H12C5.373 32 0 37.373 0 44v40c0 6.627 5.373 12 12 12h20v320H12c-6.627 0-12 5.373-12 12v40c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12v-20h384v20c0 6.627 5.373 12 12 12h40c6.627 0 12-5.373 12-12v-40c0-6.627-5.373-12-12-12h-20V128zM96 276V140c0-6.627 5.373-12 12-12h168c6.627 0 12 5.373 12 12v136c0 6.627-5.373 12-12 12H108c-6.627 0-12-5.373-12-12zm320 96c0 6.627-5.373 12-12 12H236c-6.627 0-12-5.373-12-12v-52h72c13.255 0 24-10.745 24-24v-72h84c6.627 0 12 5.373 12 12v136z"]},ie={prefix:"fas",iconName:"pen",icon:[512,512,[],"f304","M290.74 93.24l128.02 128.02-277.99 277.99-114.14 12.6C11.35 513.54-1.56 500.62.14 485.34l12.7-114.22 277.9-277.88zm207.2-19.06l-60.11-60.11c-18.75-18.75-49.16-18.75-67.91 0l-56.55 56.55 128.02 128.02 56.55-56.55c18.75-18.76 18.75-49.16 0-67.91z"]},le={prefix:"fas",iconName:"plus",icon:[448,512,[],"f067","M416 208H272V64c0-17.67-14.33-32-32-32h-32c-17.67 0-32 14.33-32 32v144H32c-17.67 0-32 14.33-32 32v32c0 17.67 14.33 32 32 32h144v144c0 17.67 14.33 32 32 32h32c17.67 0 32-14.33 32-32V304h144c17.67 0 32-14.33 32-32v-32c0-17.67-14.33-32-32-32z"]},se={prefix:"fas",iconName:"project-diagram",icon:[640,512,[],"f542","M384 320H256c-17.67 0-32 14.33-32 32v128c0 17.67 14.33 32 32 32h128c17.67 0 32-14.33 32-32V352c0-17.67-14.33-32-32-32zM192 32c0-17.67-14.33-32-32-32H32C14.33 0 0 14.33 0 32v128c0 17.67 14.33 32 32 32h95.72l73.16 128.04C211.98 300.98 232.4 288 256 288h.28L192 175.51V128h224V64H192V32zM608 0H480c-17.67 0-32 14.33-32 32v128c0 17.67 14.33 32 32 32h128c17.67 0 32-14.33 32-32V32c0-17.67-14.33-32-32-32z"]},pe={prefix:"fas",iconName:"redo-alt",icon:[512,512,[],"f2f9","M256.455 8c66.269.119 126.437 26.233 170.859 68.685l35.715-35.715C478.149 25.851 504 36.559 504 57.941V192c0 13.255-10.745 24-24 24H345.941c-21.382 0-32.09-25.851-16.971-40.971l41.75-41.75c-30.864-28.899-70.801-44.907-113.23-45.273-92.398-.798-170.283 73.977-169.484 169.442C88.764 348.009 162.184 424 256 424c41.127 0 79.997-14.678 110.629-41.556 4.743-4.161 11.906-3.908 16.368.553l39.662 39.662c4.872 4.872 4.631 12.815-.482 17.433C378.202 479.813 319.926 504 256 504 119.034 504 8.001 392.967 8 256.002 7.999 119.193 119.646 7.755 256.455 8z"]},ce={prefix:"fas",iconName:"skull",icon:[512,512,[],"f54c","M256 0C114.6 0 0 100.3 0 224c0 70.1 36.9 132.6 94.5 173.7 9.6 6.9 15.2 18.1 13.5 29.9l-9.4 66.2c-1.4 9.6 6 18.2 15.7 18.2H192v-56c0-4.4 3.6-8 8-8h16c4.4 0 8 3.6 8 8v56h64v-56c0-4.4 3.6-8 8-8h16c4.4 0 8 3.6 8 8v56h77.7c9.7 0 17.1-8.6 15.7-18.2l-9.4-66.2c-1.7-11.7 3.8-23 13.5-29.9C475.1 356.6 512 294.1 512 224 512 100.3 397.4 0 256 0zm-96 320c-35.3 0-64-28.7-64-64s28.7-64 64-64 64 28.7 64 64-28.7 64-64 64zm192 0c-35.3 0-64-28.7-64-64s28.7-64 64-64 64 28.7 64 64-28.7 64-64 64z"]},ue={prefix:"fas",iconName:"sync-alt",icon:[512,512,[],"f2f1","M370.72 133.28C339.458 104.008 298.888 87.962 255.848 88c-77.458.068-144.328 53.178-162.791 126.85-1.344 5.363-6.122 9.15-11.651 9.15H24.103c-7.498 0-13.194-6.807-11.807-14.176C33.933 94.924 134.813 8 256 8c66.448 0 126.791 26.136 171.315 68.685L463.03 40.97C478.149 25.851 504 36.559 504 57.941V192c0 13.255-10.745 24-24 24H345.941c-21.382 0-32.09-25.851-16.971-40.971l41.75-41.749zM32 296h134.059c21.382 0 32.09 25.851 16.971 40.971l-41.75 41.75c31.262 29.273 71.835 45.319 114.876 45.28 77.418-.07 144.315-53.144 162.787-126.849 1.344-5.363 6.122-9.15 11.651-9.15h57.304c7.498 0 13.194 6.807 11.807 14.176C478.067 417.076 377.187 504 256 504c-66.448 0-126.791-26.136-171.315-68.685L48.97 471.03C33.851 486.149 8 475.441 8 454.059V320c0-13.255 10.745-24 24-24z"]},de={prefix:"fas",iconName:"times",icon:[352,512,[],"f00d","M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z"]},he={prefix:"fas",iconName:"times-circle",icon:[512,512,[],"f057","M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm121.6 313.1c4.7 4.7 4.7 12.3 0 17L338 377.6c-4.7 4.7-12.3 4.7-17 0L256 312l-65.1 65.6c-4.7 4.7-12.3 4.7-17 0L134.4 338c-4.7-4.7-4.7-12.3 0-17l65.6-65-65.6-65.1c-4.7-4.7-4.7-12.3 0-17l39.6-39.6c4.7-4.7 12.3-4.7 17 0l65 65.7 65.1-65.6c4.7-4.7 12.3-4.7 17 0l39.6 39.6c4.7 4.7 4.7 12.3 0 17L312 256l65.6 65.1z"]},be={prefix:"fas",iconName:"trash",icon:[448,512,[],"f1f8","M432 32H312l-9.4-18.7A24 24 0 0 0 281.1 0H166.8a23.72 23.72 0 0 0-21.4 13.3L136 32H16A16 16 0 0 0 0 48v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16zM53.2 467a48 48 0 0 0 47.9 45h245.8a48 48 0 0 0 47.9-45L416 128H32z"]},me={prefix:"fas",iconName:"vector-square",icon:[512,512,[],"f5cb","M512 128V32c0-17.67-14.33-32-32-32h-96c-17.67 0-32 14.33-32 32H160c0-17.67-14.33-32-32-32H32C14.33 0 0 14.33 0 32v96c0 17.67 14.33 32 32 32v192c-17.67 0-32 14.33-32 32v96c0 17.67 14.33 32 32 32h96c17.67 0 32-14.33 32-32h192c0 17.67 14.33 32 32 32h96c17.67 0 32-14.33 32-32v-96c0-17.67-14.33-32-32-32V160c17.67 0 32-14.33 32-32zm-96-64h32v32h-32V64zM64 64h32v32H64V64zm32 384H64v-32h32v32zm352 0h-32v-32h32v32zm-32-96h-32c-17.67 0-32 14.33-32 32v32H160v-32c0-17.67-14.33-32-32-32H96V160h32c17.67 0 32-14.33 32-32V96h192v32c0 17.67 14.33 32 32 32h32v192z"]},ge={prefix:"fas",iconName:"video",icon:[576,512,[],"f03d","M336.2 64H47.8C21.4 64 0 85.4 0 111.8v288.4C0 426.6 21.4 448 47.8 448h288.4c26.4 0 47.8-21.4 47.8-47.8V111.8c0-26.4-21.4-47.8-47.8-47.8zm189.4 37.7L416 177.3v157.4l109.6 75.5c21.2 14.6 50.4-.3 50.4-25.8V127.5c0-25.4-29.1-40.4-50.4-25.8z"]},fe={prefix:"fas",iconName:"window-restore",icon:[512,512,[],"f2d2","M512 48v288c0 26.5-21.5 48-48 48h-48V176c0-44.1-35.9-80-80-80H128V48c0-26.5 21.5-48 48-48h288c26.5 0 48 21.5 48 48zM384 176v288c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V176c0-26.5 21.5-48 48-48h288c26.5 0 48 21.5 48 48zm-68 28c0-6.6-5.4-12-12-12H76c-6.6 0-12 5.4-12 12v52h252v-52z"]},ve={prefix:"fas",iconName:"wrench",icon:[512,512,[],"f0ad","M507.73 109.1c-2.24-9.03-13.54-12.09-20.12-5.51l-74.36 74.36-67.88-11.31-11.31-67.88 74.36-74.36c6.62-6.62 3.43-17.9-5.66-20.16-47.38-11.74-99.55.91-136.58 37.93-39.64 39.64-50.55 97.1-34.05 147.2L18.74 402.76c-24.99 24.99-24.99 65.51 0 90.5 24.99 24.99 65.51 24.99 90.5 0l213.21-213.21c50.12 16.71 107.47 5.68 147.37-34.22 37.07-37.07 49.7-89.32 37.91-136.73zM64 472c-13.25 0-24-10.75-24-24 0-13.26 10.75-24 24-24s24 10.74 24 24c0 13.25-10.75 24-24 24z"]},ye=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){return s.createElement("div",{className:"pane"})},t}(s.Component),Ce=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.onLink=function(){this.props.url?window.open(this.props.url,"_blank"):this.props.onLink&&this.props.onLink()},t.prototype.renderContent=function(){var e=this;return this.props.ignoreValue?null:this.props.onLink||this.props.url?s.createElement("div",{className:"link-value",title:this.props.value,onClick:function(){return e.onLink()}},this.props.url?"doc":this.props.value||"no name"):s.createElement("div",{className:"value",title:this.props.value,style:{color:this.props.color?this.props.color:""}},this.props.value||"no name")},t.prototype.render=function(){var e,t;return s.createElement("div",{className:this.props.underline?"textLine underline":"textLine"+(this.props.additionalClass?" "+this.props.additionalClass:"")},s.createElement("div",{className:"label",title:null!==(e=this.props.label)&&void 0!==e?e:""},null!==(t=this.props.label)&&void 0!==t?t:""),this.renderContent())},t}(s.Component),Ee=function(e){function t(t){var r=e.call(this,t)||this,n=u.DataStorage.ReadBoolean(r.props.title,!r.props.closed);return r.state={isExpanded:n,isHighlighted:!1},r}return a(t,e),t.prototype.switchExpandedState=function(){var e=!this.state.isExpanded;u.DataStorage.WriteBoolean(this.props.title,e),this.setState({isExpanded:e})},t.prototype.componentDidMount=function(){var e=this;this.props.globalState&&(0===this.props.globalState.selectedLineContainerTitles.length&&0===this.props.globalState.selectedLineContainerTitlesNoFocus.length||(this.props.globalState.selectedLineContainerTitles.indexOf(this.props.title)>-1?(setTimeout((function(){e.props.globalState.selectedLineContainerTitles=[]})),this.setState({isExpanded:!0,isHighlighted:!0}),window.setTimeout((function(){e.setState({isHighlighted:!1})}),5e3)):this.props.globalState.selectedLineContainerTitlesNoFocus.indexOf(this.props.title)>-1?this.setState({isExpanded:!0,isHighlighted:!1}):this.setState({isExpanded:!1})))},t.prototype.renderHeader=function(){var e=this,t=this.state.isExpanded?"collapse":"collapse closed";return s.createElement("div",{className:"header",onClick:function(){return e.switchExpandedState()}},s.createElement("div",{className:"title"},this.props.title),s.createElement("div",{className:t},s.createElement(w,{icon:G})))},t.prototype.render=function(){return this.state.isExpanded?s.createElement("div",{className:"paneContainer"},s.createElement("div",{className:"paneContainer-content"},this.renderHeader(),s.createElement("div",{className:"paneList"},this.props.children)),s.createElement("div",{className:"paneContainer-highlight-border"+(this.state.isHighlighted?"":" transparent")})):s.createElement("div",{className:"paneContainer"},s.createElement("div",{className:"paneContainer-content"},this.renderHeader()))},t}(s.Component),Oe=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=void 0!==this.props.fractionDigits?this.props.fractionDigits:2,t=this.props.value.toFixed(e)+(this.props.units?" "+this.props.units:"");return s.createElement("div",{className:"textLine"},s.createElement("div",{className:"label",title:this.props.label},this.props.label),s.createElement("div",{className:"value",style:{color:this.props.color?this.props.color:""}},t))},t}(s.Component),Se=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.value?s.createElement(w,{icon:F}):s.createElement(w,{icon:he}),t=this.props.value?"value check":"value uncheck";return s.createElement("div",{className:"textLine"},s.createElement("div",{className:"label",title:this.props.label},this.props.label),s.createElement("div",{className:t},e))},t}(s.Component),xe=function(e){function t(t){var r=e.call(this,t)||this,n=r.props.scene;return n?(r._sceneInstrumentation=new u.SceneInstrumentation(n),r._sceneInstrumentation.captureActiveMeshesEvaluationTime=!0,r._sceneInstrumentation.captureRenderTargetsRenderTime=!0,r._sceneInstrumentation.captureFrameTime=!0,r._sceneInstrumentation.captureRenderTime=!0,r._sceneInstrumentation.captureInterFrameTime=!0,r._sceneInstrumentation.captureParticlesRenderTime=!0,r._sceneInstrumentation.captureSpritesRenderTime=!0,r._sceneInstrumentation.capturePhysicsTime=!0,r._sceneInstrumentation.captureAnimationsTime=!0,r._engineInstrumentation=new u.EngineInstrumentation(n.getEngine()),r._engineInstrumentation.captureGPUFrameTime=!0,r._timerIntervalId=window.setInterval((function(){return r.forceUpdate()}),500),r):r}return a(t,e),t.prototype.componentWillUnmount=function(){this._sceneInstrumentation&&(this._sceneInstrumentation.dispose(),this._sceneInstrumentation=null),this._engineInstrumentation&&(this._engineInstrumentation.dispose(),this._engineInstrumentation=null),window.clearInterval(this._timerIntervalId)},t.prototype.render=function(){var e=this.props.scene;if(!e||!this._sceneInstrumentation||!this._engineInstrumentation)return null;var t=e.getEngine(),r=this._sceneInstrumentation,n=this._engineInstrumentation,a=t.getCaps();return s.createElement("div",{className:"pane"},s.createElement(Ce,{label:"Version",value:u.Engine.Version,color:"rgb(113, 159, 255)"}),s.createElement(Oe,{label:"FPS",value:t.getFps(),fractionDigits:0}),s.createElement(Ee,{globalState:this.props.globalState,title:"COUNT"},s.createElement(Ce,{label:"Total meshes",value:e.meshes.length.toString()}),s.createElement(Ce,{label:"Active meshes",value:e.getActiveMeshes().length.toString()}),s.createElement(Ce,{label:"Active indices",value:e.getActiveIndices().toString()}),s.createElement(Ce,{label:"Active faces",value:(e.getActiveIndices()/3).toString()}),s.createElement(Ce,{label:"Active bones",value:e.getActiveBones().toString()}),s.createElement(Ce,{label:"Active particles",value:e.getActiveParticles().toString()}),s.createElement(Ce,{label:"Draw calls",value:r.drawCallsCounter.current.toString()}),s.createElement(Ce,{label:"Total lights",value:e.lights.length.toString()}),s.createElement(Ce,{label:"Total vertices",value:e.getTotalVertices().toString()}),s.createElement(Ce,{label:"Total materials",value:e.materials.length.toString()}),s.createElement(Ce,{label:"Total textures",value:e.textures.length.toString()})),s.createElement(Ee,{globalState:this.props.globalState,title:"FRAME STEPS DURATION"},s.createElement(Oe,{label:"Absolute FPS",value:1e3/this._sceneInstrumentation.frameTimeCounter.lastSecAverage,fractionDigits:0}),s.createElement(Oe,{label:"Meshes selection",value:r.activeMeshesEvaluationTimeCounter.lastSecAverage,units:"ms"}),s.createElement(Oe,{label:"Render targets",value:r.renderTargetsRenderTimeCounter.lastSecAverage,units:"ms"}),s.createElement(Oe,{label:"Particles",value:r.particlesRenderTimeCounter.lastSecAverage,units:"ms"}),s.createElement(Oe,{label:"Sprites",value:r.spritesRenderTimeCounter.lastSecAverage,units:"ms"}),s.createElement(Oe,{label:"Animations",value:r.animationsTimeCounter.lastSecAverage,units:"ms"}),s.createElement(Oe,{label:"Physics",value:r.physicsTimeCounter.lastSecAverage,units:"ms"}),s.createElement(Oe,{label:"Render",value:r.renderTimeCounter.lastSecAverage,units:"ms"}),s.createElement(Oe,{label:"Frame total",value:r.frameTimeCounter.lastSecAverage,units:"ms"}),s.createElement(Oe,{label:"Inter-frame",value:r.interFrameTimeCounter.lastSecAverage,units:"ms"}),s.createElement(Oe,{label:"GPU Frame time",value:1e-6*n.gpuFrameTimeCounter.lastSecAverage,units:"ms"}),s.createElement(Oe,{label:"GPU Frame time (average)",value:1e-6*n.gpuFrameTimeCounter.average,units:"ms"})),s.createElement(Ee,{globalState:this.props.globalState,title:"SYSTEM INFO"},s.createElement(Ce,{label:"Resolution",value:t.getRenderWidth()+"x"+t.getRenderHeight()}),s.createElement(Ce,{label:"Hardware scaling level",value:t.getHardwareScalingLevel().toString()}),s.createElement(Ce,{label:"WebGL version",value:t.webGLVersion.toString()}),s.createElement(Se,{label:"Std derivatives",value:a.standardDerivatives}),s.createElement(Se,{label:"Compressed textures",value:void 0!==a.s3tc}),s.createElement(Se,{label:"Hardware instances",value:a.instancedArrays}),s.createElement(Se,{label:"Texture float",value:a.textureFloat}),s.createElement(Se,{label:"Texture half-float",value:a.textureHalfFloat}),s.createElement(Se,{label:"Render to texture float",value:a.textureFloatRender}),s.createElement(Se,{label:"Render to texture half-float",value:a.textureHalfFloatRender}),s.createElement(Se,{label:"32bits indices",value:a.uintIndices}),s.createElement(Se,{label:"Fragment depth",value:a.fragmentDepthSupported}),s.createElement(Se,{label:"High precision shaders",value:a.highPrecisionShaderSupported}),s.createElement(Se,{label:"Draw buffers",value:a.drawBuffersExtension}),s.createElement(Se,{label:"Vertex array object",value:a.vertexArrayObject}),s.createElement(Se,{label:"Timer query",value:void 0!==a.timerQuery}),s.createElement(Se,{label:"Stencil",value:t.isStencilEnable}),s.createElement(Se,{label:"Parallel shader compilation",value:null!=a.parallelShaderCompile}),s.createElement(Oe,{label:"Max textures units",value:a.maxTexturesImageUnits,fractionDigits:0}),s.createElement(Oe,{label:"Max textures size",value:a.maxTextureSize,fractionDigits:0}),s.createElement(Oe,{label:"Max anisotropy",value:a.maxAnisotropy,fractionDigits:0}),s.createElement(Ce,{label:"Driver",value:t.getGlInfo().renderer})))},t}(ye),Pe=function(e){function t(r){var n=e.call(this,r)||this;return n._localChange=!1,n._uniqueId=t._UniqueIdSeed++,n.props.isSelected?n.state={isSelected:n.props.isSelected()}:n.state={isSelected:!0===n.props.target[n.props.propertyName]},n}return a(t,e),t.prototype.shouldComponentUpdate=function(e,t){var r;return!((r=this.props.isSelected?e.isSelected():1==e.target[e.propertyName])===t.isSelected&&!this._localChange&&this.props.label===e.label)&&(t.isSelected=r,this._localChange=!1,!0)},t.prototype.onChange=function(){this._localChange=!0,this.props.onSelect?this.props.onSelect(!this.state.isSelected):(this.props.onPropertyChangedObservable&&this.props.onPropertyChangedObservable.notifyObservers({object:this.props.target,property:this.props.propertyName,value:!this.state.isSelected,initialValue:this.state.isSelected}),this.props.target[this.props.propertyName]=!this.state.isSelected),this.props.onValueChanged&&this.props.onValueChanged(),this.setState({isSelected:!this.state.isSelected})},t.prototype.render=function(){var e=this;return s.createElement("div",{className:"checkBoxLine"},s.createElement("div",{className:"label",title:this.props.label},this.props.label),s.createElement("div",{className:"checkBox"},s.createElement("input",{type:"checkbox",id:"checkbox"+this._uniqueId,className:"cbx hidden",checked:this.state.isSelected,onChange:function(){return e.onChange()}}),s.createElement("label",{htmlFor:"checkbox"+this._uniqueId,className:"lbl"})))},t._UniqueIdSeed=0,t}(s.Component),we=r(15),ke=function(e){function t(t){var r=e.call(this,t)||this;return r.state={isEnabled:!1},r}return a(t,e),t.prototype.componentDidMount=function(){for(var e=0,t=u.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer.utilityLayerScene.meshes;e<t.length;e++){var r=t[e];if(r.reservedDataStore&&r.reservedDataStore.isInspectorGrid)return this._gridMesh=r,void this.setState({isEnabled:!0})}},t.prototype.addOrRemoveGrid=function(){var e=u.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer.utilityLayerScene;if(!this._gridMesh){var t=this.props.scene.getWorldExtends(),r=5*(t.max.x-t.min.x),n=5*(t.max.z-t.min.z);this._gridMesh=u.Mesh.CreateGround("grid",1,1,1,e),this._gridMesh.reservedDataStore||(this._gridMesh.reservedDataStore={}),this._gridMesh.scaling.x=Math.max(r,n),this._gridMesh.scaling.z=this._gridMesh.scaling.x,this._gridMesh.reservedDataStore.isInspectorGrid=!0,this._gridMesh.isPickable=!1;var a=new we.GridMaterial("GridMaterial",e);return a.majorUnitFrequency=10,a.minorUnitVisibility=.3,a.gridRatio=.01,a.backFaceCulling=!1,a.mainColor=new u.Color3(1,1,1),a.lineColor=new u.Color3(1,1,1),a.opacity=.8,a.zOffset=1,a.opacityTexture=new u.Texture("https://assets.babylonjs.com/environments/backgroundGround.png",e),this._gridMesh.material=a,void this.setState({isEnabled:!0})}this.setState({isEnabled:!this.state.isEnabled}),this._gridMesh.dispose(!0,!0),this._gridMesh=null},t.prototype.render=function(){var e=this;return s.createElement("div",null,s.createElement(Pe,{label:"Render grid",isSelected:function(){return e.state.isEnabled},onSelect:function(){return e.addOrRemoveGrid()}}))},t}(s.Component),Ne=function(e){function t(t){var r=e.call(this,t)||this;r._physicsViewersEnabled=!1;var n=r.props.scene;return n?(n.reservedDataStore||(n.reservedDataStore={}),r._physicsViewersEnabled=null!=n.reservedDataStore.physicsViewer,r):r}return a(t,e),t.prototype.switchPhysicsViewers=function(){this._physicsViewersEnabled=!this._physicsViewersEnabled;var e=this.props.scene;if(this._physicsViewersEnabled){var t=new u.PhysicsViewer(e);e.reservedDataStore.physicsViewer=t;for(var r=0,n=e.meshes;r<n.length;r++){var a=n[r];if(a.physicsImpostor){var o=t.showImpostor(a.physicsImpostor,a);o&&(o.reservedDataStore={hidden:!0},o.material.reservedDataStore={hidden:!0})}}}else e.reservedDataStore.physicsViewer.dispose(),e.reservedDataStore.physicsViewer=null},t.prototype.render=function(){var e=this,t=this.props.scene;return t?s.createElement("div",{className:"pane"},s.createElement(Ee,{globalState:this.props.globalState,title:"HELPERS"},s.createElement(ke,{globalState:this.props.globalState,scene:t}),s.createElement(Pe,{label:"Physics",isSelected:function(){return e._physicsViewersEnabled},onSelect:function(){return e.switchPhysicsViewers()}})),s.createElement(Ee,{globalState:this.props.globalState,title:"CORE TEXTURE CHANNELS"},s.createElement(Pe,{label:"Diffuse",isSelected:function(){return u.StandardMaterial.DiffuseTextureEnabled},onSelect:function(){return u.StandardMaterial.DiffuseTextureEnabled=!u.StandardMaterial.DiffuseTextureEnabled}}),s.createElement(Pe,{label:"Ambient",isSelected:function(){return u.StandardMaterial.AmbientTextureEnabled},onSelect:function(){return u.StandardMaterial.AmbientTextureEnabled=!u.StandardMaterial.AmbientTextureEnabled}}),s.createElement(Pe,{label:"Specular",isSelected:function(){return u.StandardMaterial.SpecularTextureEnabled},onSelect:function(){return u.StandardMaterial.SpecularTextureEnabled=!u.StandardMaterial.SpecularTextureEnabled}}),s.createElement(Pe,{label:"Emissive",isSelected:function(){return u.StandardMaterial.EmissiveTextureEnabled},onSelect:function(){return u.StandardMaterial.EmissiveTextureEnabled=!u.StandardMaterial.EmissiveTextureEnabled}}),s.createElement(Pe,{label:"Bump",isSelected:function(){return u.StandardMaterial.BumpTextureEnabled},onSelect:function(){return u.StandardMaterial.BumpTextureEnabled=!u.StandardMaterial.BumpTextureEnabled}}),s.createElement(Pe,{label:"Opacity",isSelected:function(){return u.StandardMaterial.OpacityTextureEnabled},onSelect:function(){return u.StandardMaterial.OpacityTextureEnabled=!u.StandardMaterial.OpacityTextureEnabled}}),s.createElement(Pe,{label:"Reflection",isSelected:function(){return u.StandardMaterial.ReflectionTextureEnabled},onSelect:function(){return u.StandardMaterial.ReflectionTextureEnabled=!u.StandardMaterial.ReflectionTextureEnabled}}),s.createElement(Pe,{label:"Refraction",isSelected:function(){return u.StandardMaterial.RefractionTextureEnabled},onSelect:function(){return u.StandardMaterial.RefractionTextureEnabled=!u.StandardMaterial.RefractionTextureEnabled}}),s.createElement(Pe,{label:"ColorGrading",isSelected:function(){return u.StandardMaterial.ColorGradingTextureEnabled},onSelect:function(){return u.StandardMaterial.ColorGradingTextureEnabled=!u.StandardMaterial.ColorGradingTextureEnabled}}),s.createElement(Pe,{label:"Lightmap",isSelected:function(){return u.StandardMaterial.LightmapTextureEnabled},onSelect:function(){return u.StandardMaterial.LightmapTextureEnabled=!u.StandardMaterial.LightmapTextureEnabled}}),s.createElement(Pe,{label:"Fresnel",isSelected:function(){return u.StandardMaterial.FresnelEnabled},onSelect:function(){return u.StandardMaterial.FresnelEnabled=!u.StandardMaterial.FresnelEnabled}})),s.createElement(Ee,{globalState:this.props.globalState,title:"FEATURES"},s.createElement(Pe,{label:"Animations",isSelected:function(){return t.animationsEnabled},onSelect:function(){return t.animationsEnabled=!t.animationsEnabled}}),s.createElement(Pe,{label:"Physics",isSelected:function(){return t.physicsEnabled},onSelect:function(){return t.physicsEnabled=!t.physicsEnabled}}),s.createElement(Pe,{label:"Collisions",isSelected:function(){return t.collisionsEnabled},onSelect:function(){return t.collisionsEnabled=!t.collisionsEnabled}}),s.createElement(Pe,{label:"Fog",isSelected:function(){return t.fogEnabled},onSelect:function(){return t.fogEnabled=!t.fogEnabled}}),s.createElement(Pe,{label:"Lens flares",isSelected:function(){return t.lensFlaresEnabled},onSelect:function(){return t.lensFlaresEnabled=!t.lensFlaresEnabled}}),s.createElement(Pe,{label:"Lights",isSelected:function(){return t.lightsEnabled},onSelect:function(){return t.lightsEnabled=!t.lightsEnabled}}),s.createElement(Pe,{label:"Particles",isSelected:function(){return t.particlesEnabled},onSelect:function(){return t.particlesEnabled=!t.particlesEnabled}}),s.createElement(Pe,{label:"Post-processes",isSelected:function(){return t.postProcessesEnabled},onSelect:function(){return t.postProcessesEnabled=!t.postProcessesEnabled}}),s.createElement(Pe,{label:"Probes",isSelected:function(){return t.probesEnabled},onSelect:function(){return t.probesEnabled=!t.probesEnabled}}),s.createElement(Pe,{label:"Textures",isSelected:function(){return t.texturesEnabled},onSelect:function(){return t.texturesEnabled=!t.texturesEnabled}}),s.createElement(Pe,{label:"Procedural textures",isSelected:function(){return t.proceduralTexturesEnabled},onSelect:function(){return t.proceduralTexturesEnabled=!t.proceduralTexturesEnabled}}),s.createElement(Pe,{label:"Render targets",isSelected:function(){return t.renderTargetsEnabled},onSelect:function(){return t.renderTargetsEnabled=!t.renderTargetsEnabled}}),s.createElement(Pe,{label:"Shadows",isSelected:function(){return t.shadowsEnabled},onSelect:function(){return t.shadowsEnabled=!t.shadowsEnabled}}),s.createElement(Pe,{label:"Skeletons",isSelected:function(){return t.skeletonsEnabled},onSelect:function(){return t.skeletonsEnabled=!t.skeletonsEnabled}}),s.createElement(Pe,{label:"Sprites",isSelected:function(){return t.spritesEnabled},onSelect:function(){return t.spritesEnabled=!t.spritesEnabled}}))):null},t}(ye),Te=r(8),_e=r.n(Te),Me=function(e){function t(t){var r=e.call(this,t)||this;r._localChange=!1;var n=r.props.target[r.props.propertyName];return r.state={value:n?r.props.isInteger?n.toFixed(0):n.toFixed(r.props.digits||3):"0"},r._store=n,r}return a(t,e),t.prototype.componentWillUnmount=function(){this.unlock()},t.prototype.shouldComponentUpdate=function(e,t){if(this._localChange)return this._localChange=!1,!0;var r=e.target[e.propertyName],n=r?this.props.isInteger?r.toFixed(0):r.toFixed(this.props.digits||3):"0";return n!==t.value&&(t.value=n,!0)},t.prototype.raiseOnPropertyChanged=function(e,t){this.props.onChange&&this.props.onChange(e),this.props.onPropertyChangedObservable&&this.props.onPropertyChangedObservable.notifyObservers({object:this.props.target,property:this.props.propertyName,value:e,initialValue:t})},t.prototype.updateValue=function(e){var t;/[^0-9\.\-]/g.test(e)||(t=this.props.isInteger?parseInt(e):parseFloat(e),isNaN(t)||(void 0!==this.props.min&&t<this.props.min&&(e=(t=this.props.min).toString()),void 0!==this.props.max&&t>this.props.max&&(e=(t=this.props.max).toString())),this._localChange=!0,this.setState({value:e}),isNaN(t)||(this.props.target[this.props.propertyName]=t,this.raiseOnPropertyChanged(t,this._store),this._store=t))},t.prototype.lock=function(){this.props.lockObject&&(this.props.lockObject.lock=!0)},t.prototype.unlock=function(){this.props.lockObject&&(this.props.lockObject.lock=!1)},t.prototype.render=function(){var e,t=this;e=this.props.isInteger?parseInt(this.state.value):parseFloat(this.state.value);var r=this.props.smallUI?"short":"value";return s.createElement("div",null,!this.props.useEuler&&s.createElement("div",{className:this.props.additionalClass?this.props.additionalClass+" floatLine":"floatLine"},s.createElement("div",{className:"label",title:this.props.label},this.props.label),s.createElement("div",{className:r},s.createElement("input",{type:"number",step:this.props.step||this.props.isInteger?"1":"0.01",className:"numeric-input",onKeyDown:function(e){13===e.keyCode&&t.props.onEnter&&t.props.onEnter(t._store)},value:this.state.value,onBlur:function(){t.unlock(),t.props.onEnter&&t.props.onEnter(t._store)},onFocus:function(){return t.lock()},onChange:function(e){return t.updateValue(e.target.value)}}))),this.props.useEuler&&s.createElement(Le,{label:this.props.label,minimum:0,maximum:360,step:.1,directValue:u.Tools.ToDegrees(e),onChange:function(e){return t.updateValue(u.Tools.ToRadians(e).toString())}}))},t}(s.Component),Le=function(e){function t(t){var r=e.call(this,t)||this;if(r._localChange=!1,void 0!==r.props.directValue)r.state={value:r.props.directValue};else{var n=r.props.target[r.props.propertyName];void 0===n&&(n=r.props.maximum),r.state={value:n}}return r}return a(t,e),t.prototype.shouldComponentUpdate=function(e,t){if(void 0!==e.directValue)return t.value=e.directValue,!0;var r=e.target[e.propertyName];return void 0===r&&(r=e.maximum),!(r===t.value&&!this._localChange&&e.maximum===this.props.maximum&&e.minimum===this.props.minimum)&&(t.value=r,this._localChange=!1,!0)},t.prototype.onChange=function(e){this._localChange=!0;var t=parseFloat(e);this.props.useEuler&&(t=u.Tools.ToRadians(t)),this.props.target&&(this.props.onPropertyChangedObservable&&this.props.onPropertyChangedObservable.notifyObservers({object:this.props.target,property:this.props.propertyName,value:t,initialValue:this.state.value}),this.props.target[this.props.propertyName]=t),this.props.onChange&&this.props.onChange(t),this.setState({value:t})},t.prototype.onInput=function(e){var t=parseFloat(e);this.props.onInput&&this.props.onInput(t)},t.prototype.prepareDataToRead=function(e){return null===e&&(e=0),this.props.useEuler?u.Tools.ToDegrees(e):e},t.prototype.render=function(){var e=this;return s.createElement("div",{className:"sliderLine"},s.createElement("div",{className:this.props.margin?"label withMargins":"label",title:this.props.label},this.props.label),s.createElement(Me,{smallUI:!0,label:"",target:this.state,propertyName:"value",min:this.props.minimum,max:this.props.maximum,onEnter:function(){var t=e.prepareDataToRead(e.state.value);e.onChange(t)},onChange:function(t){var r=e.prepareDataToRead(e.state.value);e.onChange(r)}}),s.createElement("div",{className:"slider"},s.createElement("input",{className:"range",type:"range",step:this.props.step,min:this.prepareDataToRead(this.props.minimum),max:this.prepareDataToRead(this.props.maximum),value:this.prepareDataToRead(this.state.value),onInput:function(t){return e.onInput(t.target.value)},onChange:function(t){return e.onChange(t.target.value)}})))},t}(s.Component),De=Number.MAX_SAFE_INTEGER,Re=function(e){function t(t){var r=e.call(this,t)||this;return r._localChange=!1,r.state={value:r.remapValueIn(r.props.extractValue?r.props.extractValue():t.target[t.propertyName])},r}return a(t,e),t.prototype.remapValueIn=function(e){return this.props.allowNullValue&&null===e?De:e},t.prototype.remapValueOut=function(e){return this.props.allowNullValue&&e===De?null:e},t.prototype.shouldComponentUpdate=function(e,t){if(this._localChange)return this._localChange=!1,!0;var r=this.remapValueIn(e.extractValue?e.extractValue():e.target[e.propertyName]);return null!=r&&r!==t.value&&(t.value=r,!0)},t.prototype.raiseOnPropertyChanged=function(e,t){this.props.onPropertyChangedObservable&&this.props.onPropertyChangedObservable.notifyObservers({object:this.props.target,property:this.props.propertyName,value:e,initialValue:t,allowNullValue:this.props.allowNullValue})},t.prototype.updateValue=function(e){var t=parseInt(e);this._localChange=!0;var r=this.props.extractValue?this.props.extractValue():this.props.target[this.props.propertyName];this.props.noDirectUpdate||(this.props.target[this.props.propertyName]=this.remapValueOut(t)),this.setState({value:t}),this.props.onSelect&&this.props.onSelect(t);var n=this.props.extractValue?this.props.extractValue():this.props.target[this.props.propertyName];this.raiseOnPropertyChanged(n,r)},t.prototype.render=function(){var e,t=this;return s.createElement("div",{className:"listLine"},s.createElement("div",{className:"label",title:this.props.label},this.props.label),s.createElement("div",{className:"options"},s.createElement("select",{onChange:function(e){return t.updateValue(e.target.value)},value:null!==(e=this.state.value)&&void 0!==e?e:""},this.props.options.map((function(e,t){return s.createElement("option",{selected:e.selected,key:e.label+t,value:e.value,title:e.label},e.label)})))))},t}(s.Component),Ae=function(e){function t(t){var r=e.call(this,t)||this;return r._localChange=!1,r.state={value:r.props.value.toFixed(void 0!==r.props.precision?r.props.precision:3)},r}return a(t,e),t.prototype.shouldComponentUpdate=function(e,t){return!!this._localChange||e.value.toString()!==t.value&&(t.value=e.value.toFixed(void 0!==this.props.precision?this.props.precision:3),!0)},t.prototype.updateValue=function(e){var t=e.target.value;if(!/[^0-9\.\-]/g.test(t)){var r=parseFloat(t);this._localChange=!0,this.setState({value:t}),isNaN(r)||this.props.onChange(r)}},t.prototype.onBlur=function(){this._localChange=!1;var e=parseFloat(this.state.value);isNaN(e)?this.props.onChange(this.props.value):this.props.onChange(e)},t.prototype.render=function(){var e=this;return s.createElement("div",{className:"numeric"},this.props.label&&s.createElement("div",{className:"numeric-label",title:this.props.label},this.props.label+": "),s.createElement("input",{type:"number",step:this.props.step,className:"numeric-input",value:this.state.value,onChange:function(t){return e.updateValue(t)},onBlur:function(){return e.onBlur()}}))},t.defaultProps={step:1},t}(s.Component),Ie=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.updateValue=function(e){if(!/[^0-9\.\-]/g.test(e)){var t=parseInt(e);isNaN(t)||(null!=this.props.max&&t>this.props.max&&(t=this.props.max),null!=this.props.min&&t<this.props.min&&(t=this.props.min),this.props.onChange(t))}},t.prototype.render=function(){var e=this;return s.createElement("div",{className:"color-picker-component"},s.createElement("div",{className:"color-picker-component-value"},s.createElement("input",{type:"number",step:1,className:"numeric-input",value:this.props.value,onChange:function(t){return e.updateValue(t.target.value)}})),s.createElement("div",{className:"color-picker-component-label"},this.props.label))},t}(s.Component),je=function(e){function t(t){var r=e.call(this,t)||this;return r.state={hex:r.props.value.replace("#","")},r}return a(t,e),t.prototype.shouldComponentUpdate=function(e,t){return e.value!==this.props.value&&(t.hex=e.value.replace("#","")),!0},t.prototype.updateHexValue=function(e){""!=e&&0==/^[0-9A-Fa-f]+$/g.test(e)||(this.setState({hex:e}),e.length===this.props.expectedLength&&this.props.onChange("#"+e))},t.prototype.render=function(){var e=this;return s.createElement("input",{type:"string",className:"hex-input",value:this.state.hex,onChange:function(t){return e.updateHexValue(t.target.value)}})},t}(s.Component);r(27);var ze=function(e){function t(t){var r=e.call(this,t)||this;return r.props.color instanceof u.Color4?r.state={color:new u.Color3(r.props.color.r,r.props.color.g,r.props.color.b),alpha:r.props.color.a}:r.state={color:r.props.color.clone(),alpha:1},r._saturationRef=s.createRef(),r._hueRef=s.createRef(),r}return a(t,e),t.prototype.onSaturationPointerDown=function(e){this._evaluateSaturation(e),this._isSaturationPointerDown=!0,e.currentTarget.setPointerCapture(e.pointerId)},t.prototype.onSaturationPointerUp=function(e){this._isSaturationPointerDown=!1,e.currentTarget.releasePointerCapture(e.pointerId)},t.prototype.onSaturationPointerMove=function(e){this._isSaturationPointerDown&&this._evaluateSaturation(e)},t.prototype.onHuePointerDown=function(e){this._evaluateHue(e),this._isHuePointerDown=!0,e.currentTarget.setPointerCapture(e.pointerId)},t.prototype.onHuePointerUp=function(e){this._isHuePointerDown=!1,e.currentTarget.releasePointerCapture(e.pointerId)},t.prototype.onHuePointerMove=function(e){this._isHuePointerDown&&this._evaluateHue(e)},t.prototype._evaluateSaturation=function(e){var t=e.nativeEvent.offsetX,r=e.nativeEvent.offsetY,n=Math.min(1,Math.max(1e-4,t/this._saturationRef.current.clientWidth)),a=Math.min(1,Math.max(1e-4,1-r/this._saturationRef.current.clientHeight));this.props.debugMode&&(console.log("Saturation: "+n),console.log("Value: "+a));var o=this.state.color.toHSV();u.Color3.HSVtoRGBToRef(o.r,n,a,this.state.color),this.setState({color:this.state.color})},t.prototype._evaluateHue=function(e){var t=e.nativeEvent.offsetX,r=360*Math.min(.9999,Math.max(1e-4,t/this._hueRef.current.clientWidth));this.props.debugMode&&console.log("Hue: "+r);var n=this.state.color.toHSV();u.Color3.HSVtoRGBToRef(r,Math.max(n.g,1e-4),Math.max(n.b,1e-4),this.state.color),this.setState({color:this.state.color})},t.prototype.componentDidUpdate=function(){this.raiseOnColorChanged()},t.prototype.raiseOnColorChanged=function(){if(this.props.onColorChanged)if(this.props.color instanceof u.Color4){var e=u.Color4.FromColor3(this.state.color,this.state.alpha);this.props.onColorChanged(e)}else this.props.onColorChanged(this.state.color.clone())},t.prototype.render=function(){var e=this,t=this.state.color.toHexString(),r=this.state.color.toHSV(),n=new u.Color3;u.Color3.HSVtoRGBToRef(r.r,1,1,n);var a=n.toHexString(),o=this.props.color instanceof u.Color4;return s.createElement("div",{className:"color-picker-container"},s.createElement("div",{className:"color-picker-saturation",onPointerMove:function(t){return e.onSaturationPointerMove(t)},onPointerDown:function(t){return e.onSaturationPointerDown(t)},onPointerUp:function(t){return e.onSaturationPointerUp(t)},ref:this._saturationRef,style:{background:a}},s.createElement("div",{className:"color-picker-saturation-white"}),s.createElement("div",{className:"color-picker-saturation-black"}),s.createElement("div",{className:"color-picker-saturation-cursor",style:{top:-100*r.b+100+"%",left:100*r.g+"%"}})),s.createElement("div",{className:"color-picker-hue"},s.createElement("div",{className:"color-picker-hue-color",style:{background:t}}),s.createElement("div",{className:"color-picker-hue-slider",ref:this._hueRef,onPointerMove:function(t){return e.onHuePointerMove(t)},onPointerDown:function(t){return e.onHuePointerDown(t)},onPointerUp:function(t){return e.onHuePointerUp(t)}},s.createElement("div",{className:"color-picker-hue-cursor",style:{left:r.r/360*100+"%",border:"1px solid "+a}}))),s.createElement("div",{className:"color-picker-rgb"},s.createElement("div",{className:"red"},s.createElement(Ie,{label:"R",min:0,max:255,value:255*this.state.color.r|0,onChange:function(t){e.state.color.r=t/255,e.forceUpdate()}})),s.createElement("div",{className:"green"},s.createElement(Ie,{label:"G",min:0,max:255,value:255*this.state.color.g|0,onChange:function(t){e.state.color.g=t/255,e.forceUpdate()}})),s.createElement("div",{className:"blue"},s.createElement(Ie,{label:"B",min:0,max:255,value:255*this.state.color.b|0,onChange:function(t){e.state.color.b=t/255,e.forceUpdate()}})),s.createElement("div",{className:"alpha"+(o?"":" grayed")},s.createElement(Ie,{label:"A",min:0,max:255,value:255*this.state.alpha|0,onChange:function(t){e.setState({alpha:t/255}),e.forceUpdate()}}))),s.createElement("div",{className:"color-picker-hex"},s.createElement("div",{className:"color-picker-hex-label"},"Hex"),s.createElement("div",{className:"color-picker-hex-value"},s.createElement(je,{expectedLength:6,value:t,onChange:function(t){e.setState({color:u.Color3.FromHexString(t)})}}))))},t}(s.Component),Fe=function(e){function t(t){var r=e.call(this,t)||this;return r.state={pickerEnabled:!1,color:r.props.value,hex:r.props.value.toHexString()},r._floatRef=s.createRef(),r._floatHostRef=s.createRef(),r}return a(t,e),t.prototype.syncPositions=function(){var e=this._floatRef.current,t=this._floatHostRef.current;if(e&&t){var r=t.getBoundingClientRect().top,n=e.getBoundingClientRect().height;r+n+10>window.innerHeight&&(r=window.innerHeight-n-10),e.style.top=r+"px",e.style.left=t.getBoundingClientRect().left-e.getBoundingClientRect().width+"px"}},t.prototype.shouldComponentUpdate=function(e,t){var r=e.value.toHexString()!==this.props.value.toHexString();return r&&(t.color=e.value,t.hex=e.value.toHexString()),r||t.hex!==this.state.hex||t.pickerEnabled!==this.state.pickerEnabled},t.prototype.componentDidUpdate=function(){this.syncPositions()},t.prototype.componentDidMount=function(){this.syncPositions()},t.prototype.render=function(){var e=this,t=this.state.color;return s.createElement("div",{className:"color-picker"},s.createElement("div",{className:"color-rect",ref:this._floatHostRef,style:{background:this.state.hex},onClick:function(){return e.setState({pickerEnabled:!0})}}),this.state.pickerEnabled&&s.createElement(s.Fragment,null,s.createElement("div",{className:"color-picker-cover",onClick:function(t){var r,n;t.target===(null===(n=null===(r=e._floatRef.current)||void 0===r?void 0:r.ownerDocument)||void 0===n?void 0:n.querySelector(".color-picker-cover"))&&e.setState({pickerEnabled:!1})}},s.createElement("div",{className:"color-picker-float",ref:this._floatRef},s.createElement(ze,{color:t,onColorChanged:function(t){var r=t.toHexString();e.setState({hex:r,color:t}),e.props.onColorChanged(r)}})))))},t}(s.Component),Ge=r(14),Ve=function(e){function t(t){var r=e.call(this,t)||this;return r._localChange=!1,r.state={isExpanded:!1,color:r.props.target[r.props.propertyName].clone()},t.isLinear&&r.state.color.toGammaSpaceToRef(r.state.color),t.target._isLinearColor=t.isLinear,r}return a(t,e),t.prototype.shouldComponentUpdate=function(e,t){var r=this.props.isLinear?e.target[e.propertyName].toGammaSpace():e.target[e.propertyName];return!(r.equals(t.color)&&!this._localChange)&&(t.color=r.clone(),this._localChange=!1,!0)},t.prototype.setPropertyValue=function(e){this.props.target[this.props.propertyName]=e,this.props.isLinear&&(this.props.target[this.props.propertyName]=e.toLinearSpace())},t.prototype.onChange=function(e){this._localChange=!0;var t=u.Color3.FromHexString(e);this.props.onPropertyChangedObservable&&this.props.onPropertyChangedObservable.notifyObservers({object:this.props.target,property:this.props.propertyName,value:t,initialValue:this.state.color}),this.setPropertyValue(t),this.setState({color:t})},t.prototype.switchExpandState=function(){this._localChange=!0,this.setState({isExpanded:!this.state.isExpanded})},t.prototype.raiseOnPropertyChanged=function(e){this.props.onPropertyChangedObservable&&this.props.onPropertyChangedObservable.notifyObservers({object:this.props.target,property:this.props.propertyName,value:this.state.color,initialValue:e})},t.prototype.updateStateR=function(e){this._localChange=!0;var t=this.state.color.clone();this.state.color.r=e,this.setPropertyValue(this.state.color),this.setState({color:this.state.color}),this.raiseOnPropertyChanged(t)},t.prototype.updateStateG=function(e){this._localChange=!0;var t=this.state.color.clone();this.state.color.g=e,this.setPropertyValue(this.state.color),this.setState({color:this.state.color}),this.raiseOnPropertyChanged(t)},t.prototype.updateStateB=function(e){this._localChange=!0;var t=this.state.color.clone();this.state.color.b=e,this.setPropertyValue(this.state.color),this.setState({color:this.state.color}),this.raiseOnPropertyChanged(t)},t.prototype.copyToClipboard=function(){var e=document.createElement("div");if(e.textContent=this.state.color.toHexString(),document.body.appendChild(e),window.getSelection){var t=document.createRange();t.selectNode(e),window.getSelection().removeAllRanges(),window.getSelection().addRange(t)}document.execCommand("copy"),e.remove()},t.prototype.render=function(){var e=this,t=this.state.isExpanded?s.createElement(w,{icon:ae}):s.createElement(w,{icon:le});return s.createElement("div",{className:"color3Line"},s.createElement("div",{className:"firstLine",title:this.props.label},s.createElement("div",{className:"label"},this.props.label),s.createElement("div",{className:"color3"},s.createElement(Fe,{value:this.state.color,onColorChanged:function(t){e.onChange(t)}})),s.createElement("div",{className:"copy hoverIcon",onClick:function(){return e.copyToClipboard()},title:"Copy to clipboard"},s.createElement("img",{src:Ge,alt:""})),s.createElement("div",{className:"expand hoverIcon",onClick:function(){return e.switchExpandState()},title:"Expand"},t)),this.state.isExpanded&&s.createElement("div",{className:"secondLine"},s.createElement(Ae,{label:"r",value:this.state.color.r,onChange:function(t){return e.updateStateR(t)}}),s.createElement(Ae,{label:"g",value:this.state.color.g,onChange:function(t){return e.updateStateG(t)}}),s.createElement(Ae,{label:"b",value:this.state.color.b,onChange:function(t){return e.updateStateB(t)}})))},t}(s.Component),Ue=function(e){function t(t){var r=e.call(this,t)||this;return r._localChange=!1,r.state={isExpanded:!1,value:r.getCurrentValue().clone()},r}return a(t,e),t.prototype.getCurrentValue=function(){return this.props.target[this.props.propertyName]},t.prototype.shouldComponentUpdate=function(e,t){var r=this.getCurrentValue();return!(r.equals(t.value)&&!this._localChange)&&(t.value=r.clone(),this._localChange=!1,!0)},t.prototype.switchExpandState=function(){this._localChange=!0,this.setState({isExpanded:!this.state.isExpanded})},t.prototype.raiseOnPropertyChanged=function(e){this.props.onChange&&this.props.onChange(this.state.value),this.props.onPropertyChangedObservable&&this.props.onPropertyChangedObservable.notifyObservers({object:this.props.target,property:this.props.propertyName,value:this.state.value,initialValue:e})},t.prototype.updateVector3=function(){var e=this.props.target[this.props.propertyName].clone();this.props.target[this.props.propertyName]=this.state.value,this.setState({value:e}),this.raiseOnPropertyChanged(e)},t.prototype.updateStateX=function(e){this._localChange=!0,this.state.value.x=e,this.updateVector3()},t.prototype.updateStateY=function(e){this._localChange=!0,this.state.value.y=e,this.updateVector3()},t.prototype.updateStateZ=function(e){this._localChange=!0,this.state.value.z=e,this.updateVector3()},t.prototype.render=function(){var e=this,t=this.state.isExpanded?s.createElement(w,{icon:ae}):s.createElement(w,{icon:le});return s.createElement("div",{className:"vector3Line"},s.createElement("div",{className:"firstLine"},s.createElement("div",{className:"label",title:this.props.label},this.props.label),s.createElement("div",{className:"vector"},!this.props.useEuler&&"X: "+this.state.value.x.toFixed(2)+", Y: "+this.state.value.y.toFixed(2)+", Z: "+this.state.value.z.toFixed(2),this.props.useEuler&&"X: "+u.Tools.ToDegrees(this.state.value.x).toFixed(2)+", Y: "+u.Tools.ToDegrees(this.state.value.y).toFixed(2)+", Z: "+u.Tools.ToDegrees(this.state.value.z).toFixed(2)),s.createElement("div",{className:"expand hoverIcon",onClick:function(){return e.switchExpandState()},title:"Expand"},t)),this.state.isExpanded&&!this.props.useEuler&&s.createElement("div",{className:"secondLine"},s.createElement(Ae,{label:"x",step:this.props.step,value:this.state.value.x,onChange:function(t){return e.updateStateX(t)}}),s.createElement(Ae,{label:"y",step:this.props.step,value:this.state.value.y,onChange:function(t){return e.updateStateY(t)}}),s.createElement(Ae,{label:"z",step:this.props.step,value:this.state.value.z,onChange:function(t){return e.updateStateZ(t)}})),this.state.isExpanded&&this.props.useEuler&&!this.props.noSlider&&s.createElement("div",{className:"secondLine"},s.createElement(Le,{margin:!0,label:"x",minimum:0,maximum:360,step:.1,directValue:u.Tools.ToDegrees(this.state.value.x),onChange:function(t){return e.updateStateX(u.Tools.ToRadians(t))}}),s.createElement(Le,{margin:!0,label:"y",minimum:0,maximum:360,step:.1,directValue:u.Tools.ToDegrees(this.state.value.y),onChange:function(t){return e.updateStateY(u.Tools.ToRadians(t))}}),s.createElement(Le,{margin:!0,label:"z",minimum:0,maximum:360,step:.1,directValue:u.Tools.ToDegrees(this.state.value.z),onChange:function(t){return e.updateStateZ(u.Tools.ToRadians(t))}})),this.state.isExpanded&&this.props.useEuler&&this.props.noSlider&&s.createElement("div",{className:"secondLine"},s.createElement(Ae,{label:"x",step:this.props.step,value:u.Tools.ToDegrees(this.state.value.x),onChange:function(t){return e.updateStateX(u.Tools.ToRadians(t))}}),s.createElement(Ae,{label:"y",step:this.props.step,value:u.Tools.ToDegrees(this.state.value.y),onChange:function(t){return e.updateStateY(u.Tools.ToRadians(t))}}),s.createElement(Ae,{label:"z",step:this.props.step,value:u.Tools.ToDegrees(this.state.value.z),onChange:function(t){return e.updateStateZ(u.Tools.ToRadians(t))}})))},t.defaultProps={step:.001},t}(s.Component),He=function(e){function t(t){var r=e.call(this,t)||this;r._localChange=!1;var n=r.props.target[r.props.propertyName].clone();return r.state={isExpanded:!1,value:n,eulerValue:n.toEulerAngles()},r}return a(t,e),t.prototype._checkRoundCircle=function(e,t){return Math.abs(u.Tools.ToDegrees(e))+Math.abs(u.Tools.ToDegrees(t))===360},t.prototype.shouldComponentUpdate=function(e,t){var r=e.target[e.propertyName];return!(r.equals(t.value)&&!this._localChange)&&(t.value=r.clone(),t.eulerValue=r.toEulerAngles(),this._checkRoundCircle(t.eulerValue.x,this.state.eulerValue.x)&&(t.eulerValue.x=this.state.eulerValue.x),this._checkRoundCircle(t.eulerValue.y,this.state.eulerValue.y)&&(t.eulerValue.y=this.state.eulerValue.y),this._checkRoundCircle(t.eulerValue.z,this.state.eulerValue.z)&&(t.eulerValue.z=this.state.eulerValue.z),this._localChange=!1,!0)},t.prototype.switchExpandState=function(){this._localChange=!0,this.setState({isExpanded:!this.state.isExpanded})},t.prototype.raiseOnPropertyChanged=function(e,t){this.props.onPropertyChangedObservable&&this.props.onPropertyChangedObservable.notifyObservers({object:this.props.target,property:this.props.propertyName,value:e,initialValue:t})},t.prototype.updateQuaternion=function(){var e=this.props.target[this.props.propertyName].clone();this.props.target[this.props.propertyName]=this.state.value,this.setState({value:e}),this.raiseOnPropertyChanged(this.state.value,e)},t.prototype.updateStateX=function(e){this._localChange=!0,this.state.value.x=e,this.updateQuaternion()},t.prototype.updateStateY=function(e){this._localChange=!0,this.state.value.y=e,this.updateQuaternion()},t.prototype.updateStateZ=function(e){this._localChange=!0,this.state.value.z=e,this.updateQuaternion()},t.prototype.updateStateW=function(e){this._localChange=!0,this.state.value.w=e,this.updateQuaternion()},t.prototype.updateQuaternionFromEuler=function(){var e=this.state.eulerValue.toQuaternion();this.state.value.x=e.x,this.state.value.y=e.y,this.state.value.z=e.z,this.state.value.w=e.w,this.updateQuaternion()},t.prototype.updateStateEulerX=function(e){this._localChange=!0,this.state.eulerValue.x=u.Tools.ToRadians(e),this.updateQuaternionFromEuler()},t.prototype.updateStateEulerY=function(e){this._localChange=!0,this.state.eulerValue.y=u.Tools.ToRadians(e),this.updateQuaternionFromEuler()},t.prototype.updateStateEulerZ=function(e){this._localChange=!0,this.state.eulerValue.z=u.Tools.ToRadians(e),this.updateQuaternionFromEuler()},t.prototype.render=function(){var e=this,t=this.state.isExpanded?s.createElement(w,{icon:ae}):s.createElement(w,{icon:le}),r=this.state.value,n=this.state.eulerValue.clone();return n.x=u.Tools.ToDegrees(n.x),n.y=u.Tools.ToDegrees(n.y),n.z=u.Tools.ToDegrees(n.z),s.createElement("div",{className:"vector3Line"},s.createElement("div",{className:"firstLine",title:this.props.label+" (Using Quaternion)"},s.createElement("div",{className:"label"},this.props.label+" (Using Quaternion)"),s.createElement("div",{className:"vector"},!this.props.useEuler&&"X: "+r.x.toFixed(1)+", Y: "+r.y.toFixed(1)+", Z: "+r.z.toFixed(1)+", W: "+r.w.toFixed(1),this.props.useEuler&&"X: "+n.x.toFixed(2)+", Y: "+n.y.toFixed(2)+", Z: "+n.z.toFixed(2)),s.createElement("div",{className:"expand",onClick:function(){return e.switchExpandState()}},t)),this.state.isExpanded&&!this.props.useEuler&&s.createElement("div",{className:"secondLine"},s.createElement(Ae,{label:"x",value:r.x,onChange:function(t){return e.updateStateX(t)}}),s.createElement(Ae,{label:"y",value:r.y,onChange:function(t){return e.updateStateY(t)}}),s.createElement(Ae,{label:"z",value:r.z,onChange:function(t){return e.updateStateZ(t)}}),s.createElement(Ae,{label:"w",value:r.w,onChange:function(t){return e.updateStateW(t)}})),this.state.isExpanded&&this.props.useEuler&&s.createElement("div",{className:"secondLine"},s.createElement(Me,{label:"x",target:n,propertyName:"x",onChange:function(t){e.updateStateEulerX(t)}}),s.createElement(Me,{label:"y",target:n,propertyName:"y",onChange:function(t){e.updateStateEulerY(t)}}),s.createElement(Me,{label:"z",target:n,propertyName:"z",onChange:function(t){e.updateStateEulerZ(t)}})))},t}(s.Component),Be=function(e){function t(t){var r=e.call(this,t)||this;return r._localChange=!1,r.state={value:(void 0!==r.props.value?r.props.value:r.props.target[r.props.propertyName])||""},r}return a(t,e),t.prototype.componentWillUnmount=function(){this.props.lockObject.lock=!1},t.prototype.shouldComponentUpdate=function(e,t){if(this._localChange)return this._localChange=!1,!0;var r=void 0!==e.value?e.value:e.target[e.propertyName];return r!==t.value&&(t.value=r||"",!0)},t.prototype.raiseOnPropertyChanged=function(e,t){this.props.onChange?this.props.onChange(e):this.props.onPropertyChangedObservable&&this.props.onPropertyChangedObservable.notifyObservers({object:this.props.target,property:this.props.propertyName,value:e,initialValue:t})},t.prototype.updateValue=function(e){this._localChange=!0;var t=void 0!==this.props.value?this.props.value:this.props.target[this.props.propertyName];this.setState({value:e}),this.raiseOnPropertyChanged(e,t),this.props.propertyName&&(this.props.target[this.props.propertyName]=e)},t.prototype.render=function(){var e=this;return s.createElement("div",{className:"textInputLine"},s.createElement("div",{className:"label",title:this.props.label},this.props.label),s.createElement("div",{className:"value"},s.createElement("input",{value:this.state.value,onBlur:function(){return e.props.lockObject.lock=!1},onFocus:function(){return e.props.lockObject.lock=!0},onChange:function(t){return e.updateValue(t.target.value)}})))},t}(s.Component),We=function(e){function t(t){var r=e.call(this,t)||this;return r.state={mode:0},r}return a(t,e),t.prototype.renderInspectable=function(e){switch(e.type){case u.InspectableType.Checkbox:return s.createElement(Pe,{key:e.label,label:e.label,target:this.props.target,propertyName:e.propertyName,onPropertyChangedObservable:this.props.onPropertyChangedObservable});case u.InspectableType.Slider:return s.createElement(Le,{key:e.label,label:e.label,target:this.props.target,propertyName:e.propertyName,step:void 0!==e.step?e.step:.1,minimum:void 0!==e.min?e.min:0,maximum:void 0!==e.max?e.max:1,onPropertyChangedObservable:this.props.onPropertyChangedObservable});case u.InspectableType.Vector3:return s.createElement(Ue,{key:e.label,label:e.label,target:this.props.target,propertyName:e.propertyName,onPropertyChangedObservable:this.props.onPropertyChangedObservable});case u.InspectableType.Quaternion:return s.createElement(He,{useEuler:this.props.globalState.onlyUseEulers,key:e.label,label:e.label,target:this.props.target,propertyName:e.propertyName,onPropertyChangedObservable:this.props.onPropertyChangedObservable});case u.InspectableType.Color3:return s.createElement(Ve,{key:e.label,label:e.label,target:this.props.target,propertyName:e.propertyName,onPropertyChangedObservable:this.props.onPropertyChangedObservable});case u.InspectableType.String:return s.createElement(Be,{key:e.label,label:e.label,lockObject:this.props.lockObject,target:this.props.target,propertyName:e.propertyName,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}return null},t.prototype.render=function(){var e=this,t=this.props.target.inspectableCustomProperties;return t&&0!==t.length?s.createElement(Ee,{title:"CUSTOM",globalState:this.props.globalState},t.map((function(t){return e.renderInspectable(t)}))):null},t}(s.Component),Ye=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this;return s.createElement("div",{className:"buttonLine"},s.createElement("button",{onClick:function(){return e.props.onClick()}},this.props.label))},t}(s.Component),Ze=function(e){function t(t){var r,n=e.call(this,t)||this;n._animations=null,n._isPlaying=!1,n._animationControl={from:0,to:0,loop:!1},n.state={currentFrame:0};var a=n.props.animatable;if(n._ranges=a.getAnimationRanges?a.getAnimationRanges():[],a.getAnimatables){var o=a.getAnimatables();n._animations=new Array,o.forEach((function(e){var t;e.animations&&(t=n._animations).push.apply(t,e.animations)})),a.animations&&(r=n._animations).push.apply(r,a.animations),n._animations&&n._animations.length&&n._animations.forEach((function(e){var t=e.getKeys();if(t&&t.length>0){t[0].frame<n._animationControl.from&&(n._animationControl.from=t[0].frame);var r=t.length-1;t[r].frame>n._animationControl.to&&(n._animationControl.to=t[r].frame)}}))}return n.timelineRef=s.createRef(),n}return a(t,e),t.prototype.playOrPause=function(){var e=this.props.animatable;this._isPlaying=this.props.scene.getAllAnimatablesByTarget(e).length>0,this._isPlaying?(this.props.scene.stopAnimation(this.props.animatable),this._mainAnimatable=null):this._mainAnimatable=this.props.scene.beginAnimation(this.props.animatable,this._animationControl.from,this._animationControl.to,this._animationControl.loop),this.forceUpdate()},t.prototype.componentDidMount=function(){var e=this;this._onBeforeRenderObserver=this.props.scene.onBeforeRenderObservable.add((function(){e._isPlaying&&e._mainAnimatable&&e.setState({currentFrame:e._mainAnimatable.masterFrame})}))},t.prototype.componentWillUnmount=function(){this._onBeforeRenderObserver&&(this.props.scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=null)},t.prototype.onCurrentFrameChange=function(e){this._mainAnimatable&&(this._mainAnimatable.goToFrame(e),this.setState({currentFrame:e}))},t.prototype.onChangeFromOrTo=function(){this.playOrPause(),this._isPlaying&&this.playOrPause()},t.prototype.render=function(){var e=this,t=this.props.animatable,r=this.props.animatable,n=this.props.scene.getAllAnimatablesByTarget(t);this._isPlaying=n.length>0,this._isPlaying&&!this._mainAnimatable&&(this._mainAnimatable=n[0],this._mainAnimatable&&(this._animationControl.from=this._mainAnimatable.fromFrame,this._animationControl.to=this._mainAnimatable.toFrame,this._animationControl.loop=this._mainAnimatable.loopAnimation));var a=t.animations;return s.createElement("div",null,this._ranges.length>0&&s.createElement(Ee,{globalState:this.props.globalState,title:"ANIMATION RANGES"},this._ranges.map((function(r,n){return s.createElement(Ye,{key:r.name+n,label:r.name,onClick:function(){e._mainAnimatable=null,e.props.scene.beginAnimation(t,r.from,r.to,!0)}})}))),a&&s.createElement(s.Fragment,null,s.createElement(Ee,{globalState:this.props.globalState,title:"ANIMATIONS"},s.createElement(Ce,{label:"Count",value:a.length.toString()})),a.length>0&&s.createElement(Ee,{globalState:this.props.globalState,title:"ANIMATION GENERAL CONTROL"},s.createElement(Me,{lockObject:this.props.lockObject,isInteger:!0,label:"From",target:this._animationControl,propertyName:"from",onChange:function(){return e.onChangeFromOrTo()}}),s.createElement(Me,{lockObject:this.props.lockObject,isInteger:!0,label:"To",target:this._animationControl,propertyName:"to",onChange:function(){return e.onChangeFromOrTo()}}),s.createElement(Pe,{label:"Loop",onSelect:function(t){return e._animationControl.loop=t},isSelected:function(){return e._animationControl.loop}}),this._isPlaying&&s.createElement(Le,{ref:this.timelineRef,label:"Current frame",minimum:this._animationControl.from,maximum:this._animationControl.to,step:(this._animationControl.to-this._animationControl.from)/1e3,directValue:this.state.currentFrame,onInput:function(t){return e.onCurrentFrameChange(t)}}),s.createElement(Ye,{label:this._isPlaying?"Stop":"Play",onClick:function(){return e.playOrPause()}}),(this._ranges.length>0||this._animations&&this._animations.length>0)&&s.createElement(s.Fragment,null,s.createElement(Pe,{label:"Enable override",onSelect:function(t){t?(r.animationPropertiesOverride=new u.AnimationPropertiesOverride,r.animationPropertiesOverride.blendingSpeed=.05):r.animationPropertiesOverride=null,e.forceUpdate()},isSelected:function(){return null!=r.animationPropertiesOverride},onValueChanged:function(){return e.forceUpdate()}}),null!=r.animationPropertiesOverride&&s.createElement("div",null,s.createElement(Pe,{label:"Enable blending",target:r.animationPropertiesOverride,propertyName:"enableBlending",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Blending speed",target:r.animationPropertiesOverride,propertyName:"blendingSpeed",minimum:0,maximum:.1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}))))))},t}(s.Component),Ke=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e,t=this,r=this.props.material;r.depthFunction=null!==(e=r.depthFunction)&&void 0!==e?e:0;var n=[{label:"Clockwise",value:u.Material.ClockWiseSideOrientation},{label:"Counterclockwise",value:u.Material.CounterClockWiseSideOrientation}],a=[{label:"<Not Defined>",value:De},{label:"Opaque",value:u.PBRMaterial.PBRMATERIAL_OPAQUE},{label:"Alpha test",value:u.PBRMaterial.PBRMATERIAL_ALPHATEST},{label:"Alpha blend",value:u.PBRMaterial.PBRMATERIAL_ALPHABLEND},{label:"Alpha blend and test",value:u.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND}],o=[{label:"Combine",value:u.Constants.ALPHA_COMBINE},{label:"One one",value:u.Constants.ALPHA_ONEONE},{label:"Add",value:u.Constants.ALPHA_ADD},{label:"Subtract",value:u.Constants.ALPHA_SUBTRACT},{label:"Multiply",value:u.Constants.ALPHA_MULTIPLY},{label:"Maximized",value:u.Constants.ALPHA_MAXIMIZED},{label:"Pre-multiplied",value:u.Constants.ALPHA_PREMULTIPLIED}],i=[{label:"<Engine Default>",value:0},{label:"Never",value:u.Engine.NEVER},{label:"Always",value:u.Engine.ALWAYS},{label:"Equal",value:u.Engine.EQUAL},{label:"Less",value:u.Engine.LESS},{label:"Less or equal",value:u.Engine.LEQUAL},{label:"Greater",value:u.Engine.GREATER},{label:"Greater or equal",value:u.Engine.GEQUAL},{label:"Not equal",value:u.Engine.NOTEQUAL}];return s.createElement("div",null,s.createElement(We,{globalState:this.props.globalState,target:r,lockObject:this.props.lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Ce,{label:"ID",value:r.id}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Name",target:r,propertyName:"name",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ce,{label:"Unique ID",value:r.uniqueId.toString()}),s.createElement(Ce,{label:"Class",value:r.getClassName()}),s.createElement(Pe,{label:"Backface culling",target:r,propertyName:"backFaceCulling",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Orientation",options:n,target:r,propertyName:"sideOrientation",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onSelect:function(e){return t.setState({mode:e})}}),s.createElement(Pe,{label:"Disable lighting",target:r,propertyName:"disableLighting",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Disable color write",target:r,propertyName:"disableColorWrite",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Disable depth write",target:r,propertyName:"disableDepthWrite",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Depth function",options:i,target:r,propertyName:"depthFunction",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onSelect:function(e){return t.setState({depthFunction:e})}}),s.createElement(Pe,{label:"Need depth pre-pass",target:r,propertyName:"needDepthPrePass",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Wireframe",target:r,propertyName:"wireframe",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Point cloud",target:r,propertyName:"pointsCloud",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Point size",target:r,propertyName:"pointSize",minimum:0,maximum:100,step:.1,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Z-offset",target:r,propertyName:"zOffset",minimum:-10,maximum:10,step:.1,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ye,{label:"Dispose",onClick:function(){r.dispose(),t.props.globalState.onSelectionChangedObservable.notifyObservers(null)}})),s.createElement(Ee,{globalState:this.props.globalState,title:"TRANSPARENCY"},s.createElement(Le,{label:"Alpha",target:r,propertyName:"alpha",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),void 0!==r.transparencyMode&&s.createElement(Re,{allowNullValue:!0,label:"Transparency mode",options:a,target:r,propertyName:"transparencyMode",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onSelect:function(e){return t.setState({transparencyMode:e})}}),s.createElement(Re,{label:"Alpha mode",options:o,target:r,propertyName:"alphaMode",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onSelect:function(e){return t.setState({alphaMode:e})}}),r.diffuseTexture&&s.createElement(Pe,{label:"Diffuse texture has alpha",target:r.diffuseTexture,propertyName:"hasAlpha",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),void 0!==r.useAlphaFromDiffuseTexture&&s.createElement(Pe,{label:"Use alpha from diffuse texture",target:r,propertyName:"useAlphaFromDiffuseTexture",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),r.albedoTexture&&s.createElement(Pe,{label:"Albedo texture has alpha",target:r.albedoTexture,propertyName:"hasAlpha",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),void 0!==r.useAlphaFromAlbedoTexture&&s.createElement(Pe,{label:"Use alpha from albedo texture",target:r,propertyName:"useAlphaFromAlbedoTexture",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Separate culling pass",target:r,propertyName:"separateCullingPass",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ze,{globalState:this.props.globalState,animatable:r,scene:r.getScene(),lockObject:this.props.lockObject}))},t}(s.Component),Xe=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.material;return s.createElement("div",{className:"pane"},s.createElement(Ke,{globalState:this.props.globalState,lockObject:this.props.lockObject,material:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t}(s.Component),Qe=function(e){function t(r){var n=e.call(this,r)||this;return n._id=t._IDGenerator++,n.uploadInputRef=s.createRef(),n}return a(t,e),t.prototype.onChange=function(e){var t=e.target.files;t&&t.length&&this.props.onClick(t[0]),e.target.value=""},t.prototype.render=function(){var e=this;return s.createElement("div",{className:"buttonLine"},s.createElement("label",{htmlFor:"file-upload"+this._id,className:"file-upload"},this.props.label),s.createElement("input",{ref:this.uploadInputRef,id:"file-upload"+this._id,type:"file",accept:this.props.accept,onChange:function(t){return e.onChange(t)}}))},t._IDGenerator=0,t}(s.Component),qe=function(e){function t(t){var r=e.call(this,t)||this,n=r.props.material,a=r.props.texture;return r.state={isDebugSelected:n&&n.reservedDataStore&&n.reservedDataStore.debugTexture===a},r}return a(t,e),t.prototype.componentDidMount=function(){var e=this;this.props.onDebugSelectionChangeObservable&&(this._onDebugSelectionChangeObserver=this.props.onDebugSelectionChangeObservable.add((function(t){t!==e&&e.setState({isDebugSelected:!1})})))},t.prototype.componentWillUnmount=function(){this.props.onDebugSelectionChangeObservable&&this._onDebugSelectionChangeObserver&&this.props.onDebugSelectionChangeObservable.remove(this._onDebugSelectionChangeObserver)},t.prototype.debugTexture=function(){if(this.props.customDebugAction){var e=!this.state.isDebugSelected;return this.props.customDebugAction(e),this.setState({isDebugSelected:e}),void(this.props.onDebugSelectionChangeObservable&&this.props.onDebugSelectionChangeObservable.notifyObservers(this))}var t=this.props.texture,r=this.props.material;if(r&&t){var n=r.getScene();if(r.reservedDataStore&&r.reservedDataStore.debugTexture===t){var a=r.reservedDataStore.debugMaterial;t.level=r.reservedDataStore.level;for(var o=0,i=n.meshes;o<i.length;o++){(h=i[o]).material===a&&(h.material=r)}return a.dispose(),r.reservedDataStore.debugTexture=null,r.reservedDataStore.debugMaterial=null,void this.setState({isDebugSelected:!1})}var l=r,s=!1;r.reservedDataStore&&r.reservedDataStore.debugTexture&&(l=r.reservedDataStore.debugMaterial,s=!0);var p=new u.StandardMaterial("debugMaterial",n);p.disableLighting=!0,p.sideOrientation=r.sideOrientation,p.emissiveTexture=t,p.forceDepthWrite=!0,p.reservedDataStore={hidden:!0};for(var c=0,d=n.meshes;c<d.length;c++){var h;(h=d[c]).material===l&&(h.material=p)}r.reservedDataStore||(r.reservedDataStore={}),r.reservedDataStore.debugTexture=t,r.reservedDataStore.debugMaterial=p,r.reservedDataStore.level=t.level,t.level=1,this.props.onDebugSelectionChangeObservable&&this.props.onDebugSelectionChangeObservable.notifyObservers(this),s&&l.dispose(),this.setState({isDebugSelected:!0})}},t.prototype.onLink=function(){if(this.props.onSelectionChangedObservable){var e=this.props.texture;this.props.onSelectionChangedObservable.notifyObservers(e)}},t.prototype.updateTexture=function(e){var t=this,r=this.props.material;u.Tools.ReadFile(e,(function(e){var n=new Blob([e],{type:"octet/stream"}),a=URL.createObjectURL(n),o=new u.Texture(a,r.getScene(),!1,!1);t.props.propertyName?r[t.props.propertyName]=o:t.props.onTextureCreated&&t.props.onTextureCreated(o),t.forceUpdate()}),void 0,!0)},t.prototype.removeTexture=function(){var e=this.props.material;this.props.propertyName?e[this.props.propertyName]=null:this.props.onTextureRemoved&&this.props.onTextureRemoved(),this.forceUpdate()},t.prototype.render=function(){var e=this,t=this.props.texture;return t?s.createElement("div",{className:"textureLinkLine"},!t.isCube&&this.props.material&&s.createElement(s.Fragment,null,s.createElement("div",{className:this.state.isDebugSelected?"debug selected":"debug"},s.createElement("span",{className:"actionIcon",onClick:function(){return e.debugTexture()},title:"Render as main texture"},s.createElement(w,{icon:ve})),s.createElement("span",{className:"actionIcon",onClick:function(){return e.removeTexture()},title:"Remove texture"},s.createElement(w,{icon:be})))),s.createElement(Ce,{label:this.props.label,value:t.name,onLink:function(){return e.onLink()}})):this.props.propertyName||this.props.onTextureCreated?s.createElement(Qe,{label:"Add "+this.props.label+" texture",onClick:function(t){return e.updateTexture(t)},accept:".jpg, .png, .tga, .dds, .env"}):null},t}(s.Component),$e=function(e){function t(t){var r=e.call(this,t)||this;return r._onDebugSelectionChangeObservable=new u.Observable,r}return a(t,e),t.prototype.renderTextures=function(){var e=this.props.material,t=this._onDebugSelectionChangeObservable;return s.createElement(Ee,{globalState:this.props.globalState,title:"TEXTURES"},s.createElement(qe,{label:"Diffuse",texture:e.diffuseTexture,propertyName:"diffuseTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Specular",texture:e.specularTexture,propertyName:"specularTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Reflection",texture:e.reflectionTexture,propertyName:"reflectionTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Refraction",texture:e.refractionTexture,propertyName:"refractionTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Emissive",texture:e.emissiveTexture,propertyName:"emissiveTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Bump",texture:e.bumpTexture,propertyName:"bumpTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Opacity",texture:e.opacityTexture,propertyName:"opacityTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Ambient",texture:e.ambientTexture,propertyName:"ambientTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Lightmap",texture:e.lightmapTexture,propertyName:"lightmapTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Detailmap",texture:e.detailMap.texture,material:e,onTextureCreated:function(t){return e.detailMap.texture=t},onTextureRemoved:function(){return e.detailMap.texture=null},onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(Pe,{label:"Use lightmap as shadowmap",target:e,propertyName:"useLightmapAsShadowmap",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Use detailmap",target:e.detailMap,propertyName:"isEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t.prototype.render=function(){var e=this.props.material;return s.createElement("div",{className:"pane"},s.createElement(Ke,{globalState:this.props.globalState,lockObject:this.props.lockObject,material:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),this.renderTextures(),s.createElement(Ee,{globalState:this.props.globalState,title:"LIGHTING & COLORS"},s.createElement(Ve,{label:"Diffuse",target:e,propertyName:"diffuseColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Specular",target:e,propertyName:"specularColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Specular power",target:e,propertyName:"specularPower",minimum:0,maximum:128,step:.1,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Emissive",target:e,propertyName:"emissiveColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Ambient",target:e,propertyName:"ambientColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Use specular over alpha",target:e,propertyName:"useSpecularOverAlpha",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"LEVELS",closed:!0},e.diffuseTexture&&s.createElement(Le,{label:"Diffuse level",target:e.diffuseTexture,propertyName:"level",minimum:0,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),e.specularTexture&&s.createElement(Le,{label:"Specular level",target:e.specularTexture,propertyName:"level",minimum:0,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),e.reflectionTexture&&s.createElement(Le,{label:"Reflection level",target:e.reflectionTexture,propertyName:"level",minimum:0,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),e.refractionTexture&&s.createElement(Le,{label:"Refraction level",target:e.refractionTexture,propertyName:"level",minimum:0,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),e.emissiveTexture&&s.createElement(Le,{label:"Emissive level",target:e.emissiveTexture,propertyName:"level",minimum:0,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),e.bumpTexture&&s.createElement(Le,{label:"Bump level",target:e.bumpTexture,propertyName:"level",minimum:0,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),e.opacityTexture&&s.createElement(Le,{label:"Opacity level",target:e.opacityTexture,propertyName:"level",minimum:0,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),e.ambientTexture&&s.createElement(Le,{label:"Ambient level",target:e.ambientTexture,propertyName:"level",minimum:0,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),e.lightmapTexture&&s.createElement(Le,{label:"Lightmap level",target:e.lightmapTexture,propertyName:"level",minimum:0,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),e.detailMap.isEnabled&&s.createElement(s.Fragment,null,s.createElement(Le,{label:"Detailmap diffuse",target:e.detailMap,propertyName:"diffuseBlendLevel",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Detailmap bump",target:e.detailMap,propertyName:"bumpLevel",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}))),s.createElement(Ee,{globalState:this.props.globalState,title:"NORMAL MAP",closed:!0},s.createElement(Pe,{label:"Invert X axis",target:e,propertyName:"invertNormalMapX",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Invert Y axis",target:e,propertyName:"invertNormalMapY",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),Je="\n#extension GL_EXT_shader_texture_lod : enable\n\nprecision highp float;\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float lod;\nuniform vec2 texSize;\nvoid main(void)\n{\n gl_FragColor = textureLod(textureSampler,vUV,lod);\n}";u.Effect.ShadersStore.lodPixelShader=Je;var et="\nprecision highp float;\n\nvarying vec2 vUV;\nuniform samplerCube textureSampler;\nuniform float lod;\nvoid main(void)\n{\n vec2 uv=vUV*2.0-1.0;\n #ifdef POSITIVEX\n gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x),lod);\n #endif\n #ifdef NEGATIVEX\n gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x),lod);\n #endif\n #ifdef POSITIVEY\n gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x),lod);\n #endif\n #ifdef NEGATIVEY\n gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x),lod);\n #endif\n #ifdef POSITIVEZ\n gl_FragColor=textureCube(textureSampler,vec3(uv,1.001),lod);\n #endif\n #ifdef NEGATIVEZ\n gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001),lod);\n #endif\n}";u.Effect.ShadersStore.lodCubePixelShader=et;var tt=function(){function e(){}return e._ProcessAsync=function(e,t,r,n,a,o,i,l,s){var p,c=this,d=e.getScene(),h=d.getEngine();if(e.isCube){p=new u.PostProcess("lodCube","lodCube",["lod"],null,1,null,u.Texture.NEAREST_NEAREST_MIPNEAREST,h,!1,["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"][n])}else p=new u.PostProcess("lod","lod",["lod"],null,1,null,u.Texture.NEAREST_NEAREST_MIPNEAREST,h);if(!p.getEffect().isReady())return p.dispose(),void setTimeout((function(){c._ProcessAsync(e,t,r,n,a,o,i,l,s)}),250);i&&(i.blockMutationUpdates=!0);var b=new u.RenderTargetTexture("temp",{width:t,height:r},d,!1);p.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",o)};var m=b.getInternalTexture();if(m){var g=m.samplingMode;e.updateSamplingMode(u.Texture.NEAREST_NEAREST_MIPNEAREST),d.postProcessManager.directRender([p],m),e.updateSamplingMode(g);var f=4*t,v=r/2,y=h.readPixels(0,0,t,r);if(!(a.R&&a.G&&a.B&&a.A))for(var C=0;C<t*r*4;C+=4)if(!a.A||a.R||a.G||a.B){var E=y[C],O=y[C+1],S=y[C+2],x=y[C+3];a.A||(x=255),a.R||(E=a.G&&!a.B?O:a.B&&!a.G?S:0),a.G||(O=a.R&&!a.B?E:a.B&&!a.R?S:0),a.B||(S=a.R&&!a.G?E:a.G&&!a.R?O:0),y[C]=E,y[C+1]=O,y[C+2]=S,y[C+3]=x}else y[C]=y[C+3],y[C+1]=y[C+3],y[C+2]=y[C+3],y[C+3]=255;if(e.invertY||e.isCube)for(C=0;C<v;C++)for(var P=0;P<f;P++){var w=P+C*f,k=P+(r-C-1)*f,N=y[w];y[w]=y[k],y[k]=N}l(y),h.unBindFramebuffer(m)}else s();b.dispose(),p.dispose(),i&&(i.blockMutationUpdates=!1)},e.GetTextureDataAsync=function(e,t,r,n,a,o,i){var l=this;return void 0===i&&(i=0),new Promise((function(s,p){e.isReady()||!e._texture?l._ProcessAsync(e,t,r,n,a,i,o||null,s,p):e._texture.onLoadedObservable.addOnce((function(){l._ProcessAsync(e,t,r,n,a,i,o||null,s,p)}))}))},e}(),rt=function(e){function t(r){var n=e.call(this,r)||this;return n.state={channels:t.TextureChannelStates.ALL,face:0},n.canvasRef=s.createRef(),n}return a(t,e),t.prototype.shouldComponentUpdate=function(e,t){return e.texture!==this.props.texture||t.channels!==this.state.channels||t.face!==this.state.face},t.prototype.componentDidMount=function(){this.updatePreview()},t.prototype.componentDidUpdate=function(){this.updatePreview()},t.prototype.updatePreview=function(){return i(this,void 0,void 0,(function(){var e,t,r,n,a,o,i,s,p;return l(this,(function(l){switch(l.label){case 0:return e=this.canvasRef.current,t=this.props.texture,r=t.getSize(),n=r.width/r.height,a=this.props.width,o=a/n|1,[4,tt.GetTextureDataAsync(t,a,o,this.state.face,this.state.channels,this.props.globalState)];case 1:return i=l.sent(),e.width=a,e.height=o,(s=e.getContext("2d"))&&(p=s.createImageData(a,o),p.data.set(i),s.putImageData(p,0,0)),e.style.height=o+"px",[2]}}))}))},t.prototype.render=function(){var e=this,r=this.props.texture;return s.createElement(s.Fragment,null,s.createElement("div",{className:"textureLine"},!this.props.hideChannelSelect&&r.isCube&&s.createElement("div",{className:"control3D"},s.createElement("button",{className:0===this.state.face?"px command selected":"px command",onClick:function(){return e.setState({face:0})}},"+X"),s.createElement("button",{className:1===this.state.face?"nx command selected":"nx command",onClick:function(){return e.setState({face:1})}},"-X"),s.createElement("button",{className:2===this.state.face?"py command selected":"py command",onClick:function(){return e.setState({face:2})}},"+Y"),s.createElement("button",{className:3===this.state.face?"ny command selected":"ny command",onClick:function(){return e.setState({face:3})}},"-Y"),s.createElement("button",{className:4===this.state.face?"pz command selected":"pz command",onClick:function(){return e.setState({face:4})}},"+Z"),s.createElement("button",{className:5===this.state.face?"nz command selected":"nz command",onClick:function(){return e.setState({face:5})}},"-Z")),!this.props.hideChannelSelect&&!r.isCube&&s.createElement("div",{className:"control"},s.createElement("button",{className:this.state.channels===t.TextureChannelStates.R?"red command selected":"red command",onClick:function(){return e.setState({channels:t.TextureChannelStates.R})}},"R"),s.createElement("button",{className:this.state.channels===t.TextureChannelStates.G?"green command selected":"green command",onClick:function(){return e.setState({channels:t.TextureChannelStates.G})}},"G"),s.createElement("button",{className:this.state.channels===t.TextureChannelStates.B?"blue command selected":"blue command",onClick:function(){return e.setState({channels:t.TextureChannelStates.B})}},"B"),s.createElement("button",{className:this.state.channels===t.TextureChannelStates.A?"alpha command selected":"alpha command",onClick:function(){return e.setState({channels:t.TextureChannelStates.A})}},"A"),s.createElement("button",{className:this.state.channels===t.TextureChannelStates.ALL?"all command selected":"all command",onClick:function(){return e.setState({channels:t.TextureChannelStates.ALL})}},"ALL")),s.createElement("canvas",{ref:this.canvasRef,className:"preview"})),r.isRenderTarget&&s.createElement(Ye,{label:"Refresh",onClick:function(){e.updatePreview()}}))},t.TextureChannelStates={R:{R:!0,G:!1,B:!1,A:!1},G:{R:!1,G:!0,B:!1,A:!1},B:{R:!1,G:!1,B:!0,A:!1},A:{R:!1,G:!1,B:!1,A:!0},ALL:{R:!0,G:!0,B:!0,A:!0}},t}(s.Component),nt=r(3),at=function(e){function t(t){var r=e.call(this,t)||this;return r._container=document.createElement("div"),r._container.id=r.props.id,r._window,r.state={isComponentMounted:!1,blockedByBrowser:!1},r}return a(t,e),t.prototype.componentDidMount=function(){this.openPopup(),this.setState({isComponentMounted:!0})},t.prototype.openPopup=function(){var e=this,t=this.props,r=t.title,n=t.size,a=t.onClose,o=t.onOpen,i="window_"+r;this._container=La._CreatePopup(r,i,n.width,n.height,!0),this._container&&(this._curveEditorHost=this._container.ownerDocument.createElement("div"),this._curveEditorHost.id="curve-editor-host",this._curveEditorHost.style.width="auto",this._container.appendChild(this._curveEditorHost)),this._window=La[i],this._window?(o(this._window),this._window.addEventListener("beforeunload",(function(){return e._window&&a(e._window)}))):this._window||this.setState({blockedByBrowser:!0},(function(){e.state.blockedByBrowser&&console.warn("Popup window couldn't be created")}))},t.prototype.componentWillUnmount=function(){this._window&&this._window.close()},t.prototype.getWindow=function(){return this._window},t.prototype.render=function(){return this.state.isComponentMounted&&null!==this._container?c.createPortal(this.props.children,this._curveEditorHost):null},t}(s.Component),ot={vertexSource:"\n precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 worldViewProjection;\n\n varying vec2 vUV;\n\n void main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n vUV = uv;\n }\n ",fragmentSource:"\n precision highp float;\n \n uniform sampler2D textureSampler;\n \n uniform bool r;\n uniform bool g;\n uniform bool b;\n uniform bool a;\n\n uniform int x1;\n uniform int y1;\n uniform int x2;\n uniform int y2;\n uniform int w;\n uniform int h;\n\n uniform int time;\n uniform bool showGrid;\n \n varying vec2 vUV;\n\n float scl = 200.0;\n float speed = 10.0 / 1000.0;\n float smoothing = 0.2;\n \n void main(void) {\n vec2 pos2 = vec2(gl_FragCoord.x, gl_FragCoord.y);\n vec2 pos = floor(pos2 * 0.05);\n float pattern = mod(pos.x + pos.y, 2.0); \n if (pattern == 0.0) {\n pattern = 0.7;\n }\n vec4 bg = vec4(pattern, pattern, pattern, 1.0);\n vec4 col = texture(textureSampler, vUV);\n if (!r && !g && !b) {\n if (a) {\n col = vec4(col.a, col.a, col.a, 1.0);\n } else {\n col = vec4(0.0,0.0,0.0,0.0);\n }\n } else {\n if (!r) {\n col.r = 0.0;\n if (!b) {\n col.r = col.g;\n }\n else if (!g) {\n col.r = col.b;\n }\n }\n if (!g) {\n col.g = 0.0;\n if (!b) {\n col.g = col.r;\n }\n else if (!r) {\n col.g = col.b;\n }\n }\n if (!b) {\n col.b = 0.0;\n if (!r) {\n col.b = col.g;\n } else if (!g) {\n col.b = col.r;\n }\n }\n if (!a) {\n col.a = 1.0;\n }\n }\n gl_FragColor = col * (col.a) + bg * (1.0 - col.a);\n float wF = float(w);\n float hF = float(h);\n int xPixel = int(floor(vUV.x * wF));\n int yPixel = int(floor((1.0 - vUV.y) * hF));\n int xDis = min(abs(xPixel - x1), abs(xPixel - x2));\n int yDis = min(abs(yPixel - y1), abs(yPixel - y2));\n if (showGrid) {\n vec2 frac = fract(vUV * vec2(wF,hF));\n float thickness = 0.1;\n if (abs(frac.x) < thickness || abs (frac.y) < thickness) {\n gl_FragColor = vec4(0.75,0.75,0.75,1.0);\n }\n }\n if (xPixel >= x1 && yPixel >= y1 && xPixel <= x2 && yPixel <= y2) {\n if (xDis <= 4 || yDis <= 4) {\n float c = sin(vUV.x * scl + vUV.y * scl + float(time) * speed);\n c = smoothstep(-smoothing,smoothing,c);\n float val = 1.0 - c;\n gl_FragColor = vec4(val, val, val, 1.0) * 0.7 + gl_FragColor * 0.3;\n }\n }\n }"},it={attributes:["position","uv"],uniforms:["worldViewProjection","textureSampler","r","g","b","a","x1","y1","x2","y2","w","h","time","showGrid"]},lt=function(){function e(e,t,r,n,a,o,i,l,s,p){var c,d=this;this._isPanning=!1,this._channels=[],this._face=0,this._mipLevel=0,this._originalInternalTexture=null,this._didEdit=!1,this._keyMap={},this.ZOOM_MOUSE_SPEED=.001,this.ZOOM_KEYBOARD_SPEED=.4,this.ZOOM_IN_KEY="+",this.ZOOM_OUT_KEY="-",this.PAN_SPEED=.003,this.PAN_MOUSE_BUTTON=1,this.MIN_SCALE=.01,this.GRID_SCALE=.047,this.MAX_SCALE=10,this.SELECT_ALL_KEY="KeyA",this.SAVE_KEY="KeyS",this.RESET_KEY="KeyR",this.DESELECT_KEY="Escape",this.PUSH_FREQUENCY=32,this._editing3D=!1,this._canPush=!0,this._shouldPush=!1,this._window=t,this._UICanvas=r,this._2DCanvas=n,this._3DCanvas=a,this._paintCanvas=document.createElement("canvas"),this._setPixelData=o,this._metadata=i,this._onUpdate=l,this._setMetadata=s,this._setMipLevel=p,this._size=e.getSize(),this._originalTexture=e,this._originalInternalTexture=this._originalTexture._texture,this._engine=new u.Engine(this._UICanvas,!0),this._scene=new u.Scene(this._engine,{virtual:!0}),this._scene.clearColor=new u.Color4(.11,.11,.11,1),this._camera=new u.FreeCamera("camera",new u.Vector3(0,0,-1),this._scene),this._camera.mode=u.Camera.ORTHOGRAPHIC_CAMERA,this._cameraPos=new u.Vector2,this._channelsTexture=new u.HtmlElementTexture("ct",this._2DCanvas,{engine:this._engine,scene:null,samplingMode:u.Texture.NEAREST_SAMPLINGMODE,generateMipMaps:!0}),this._3DEngine=new u.Engine(this._3DCanvas),this._3DScene=new u.Scene(this._3DEngine,{virtual:!0}),this._3DScene.clearColor=new u.Color4(0,0,0,0),this._3DCanvasTexture=new u.HtmlElementTexture("canvas",this._2DCanvas,{engine:this._3DEngine,scene:this._3DScene}),this._3DCanvasTexture.hasAlpha=!0;var h=new u.FreeCamera("camera",new u.Vector3(0,0,-1),this._3DScene);h.mode=u.Camera.ORTHOGRAPHIC_CAMERA,c=[-.5,-.5,.5,.5],h.orthoBottom=c[0],h.orthoLeft=c[1],h.orthoTop=c[2],h.orthoRight=c[3],this._3DPlane=u.PlaneBuilder.CreatePlane("texture",{width:1,height:1},this._3DScene),this._3DPlane.hasVertexAlpha=!0;var b=new u.StandardMaterial("material",this._3DScene);b.diffuseTexture=this._3DCanvasTexture,b.useAlphaFromDiffuseTexture=!0,b.disableLighting=!0,b.emissiveColor=u.Color3.White(),this._3DPlane.material=b,this._planeMaterial=new u.ShaderMaterial("canvasShader",this._scene,ot,it),this.grabOriginalTexture(),this._planeMaterial.setTexture("textureSampler",this._channelsTexture),this._planeMaterial.setFloat("r",1),this._planeMaterial.setFloat("g",1),this._planeMaterial.setFloat("b",1),this._planeMaterial.setFloat("a",1),this._planeMaterial.setInt("x1",-1),this._planeMaterial.setInt("y1",-1),this._planeMaterial.setInt("x2",-1),this._planeMaterial.setInt("y2",-1),this._planeMaterial.setInt("w",this._size.width),this._planeMaterial.setInt("h",this._size.height),this._planeMaterial.setInt("time",0),this._planeMaterial.setFloat("showGrid",0),this._plane.material=this._planeMaterial,this._window.addEventListener("keydown",(function(e){d._keyMap[e.code]=!0,e.code===d.SELECT_ALL_KEY&&e.ctrlKey&&(d._setMetadata({select:{x1:0,y1:0,x2:d._size.width,y2:d._size.height}}),e.preventDefault()),e.code===d.SAVE_KEY&&e.ctrlKey&&(d.saveTexture(),e.preventDefault()),e.code===d.RESET_KEY&&e.ctrlKey&&(d.reset(),e.preventDefault()),e.code===d.DESELECT_KEY&&d._setMetadata({select:{x1:-1,y1:-1,x2:-1,y2:-1}})})),this._window.addEventListener("keyup",(function(e){d._keyMap[e.code]=!1})),this._engine.runRenderLoop((function(){d._engine.resize(),d._scene.render(),d._planeMaterial.setInt("time",(new Date).getTime())})),this._scale=1.5/Math.max(this._size.width,this._size.height),this._isPanning=!1,this._scene.onBeforeRenderObservable.add((function(){var e,t;d._scale=Math.min(Math.max(d._scale,d.MIN_SCALE/Math.log2(Math.min(d._size.width,d._size.height))),d.MAX_SCALE),d._scale>d.GRID_SCALE?d._planeMaterial.setFloat("showGrid",1):d._planeMaterial.setFloat("showGrid",0);var r=(null===(e=d._UICanvas)||void 0===e?void 0:e.width)/(null===(t=d._UICanvas)||void 0===t?void 0:t.height),n=d._cameraPos,a=n.x,o=n.y;d._camera.orthoBottom=o-1/d._scale,d._camera.orthoTop=o+1/d._scale,d._camera.orthoLeft=a-r/d._scale,d._camera.orthoRight=a+r/d._scale})),this._scene.onPointerObservable.add((function(e){var t;switch(e.type){case u.PointerEventTypes.POINTERWHEEL:var r=e.event;d._scale-=r.deltaY*d.ZOOM_MOUSE_SPEED*d._scale;break;case u.PointerEventTypes.POINTERDOWN:e.event.button===d.PAN_MOUSE_BUTTON&&(d._isPanning=!0,d._mouseX=e.event.x,d._mouseY=e.event.y,e.event.preventDefault());break;case u.PointerEventTypes.POINTERUP:e.event.button===d.PAN_MOUSE_BUTTON&&(d._isPanning=!1);break;case u.PointerEventTypes.POINTERMOVE:if(d._isPanning&&(d._cameraPos.x-=(e.event.x-d._mouseX)*d.PAN_SPEED/d._scale,d._cameraPos.y+=(e.event.y-d._mouseY)*d.PAN_SPEED/d._scale,d._mouseX=e.event.x,d._mouseY=e.event.y),null===(t=e.pickInfo)||void 0===t?void 0:t.hit){var n=d.getMouseCoordinates(e),a=4*(n.x+n.y*d._size.width);d._setPixelData({x:n.x,y:n.y,r:d._imageData[a],g:d._imageData[a+1],b:d._imageData[a+2],a:d._imageData[a+3]})}else d._setPixelData({})}})),this._scene.onKeyboardObservable.add((function(e){switch(e.type){case u.KeyboardEventTypes.KEYDOWN:switch(d._keyMap[e.event.key]=!0,e.event.key){case d.ZOOM_IN_KEY:d._scale+=d.ZOOM_KEYBOARD_SPEED*d._scale;break;case d.ZOOM_OUT_KEY:d._scale-=d.ZOOM_KEYBOARD_SPEED*d._scale}break;case u.KeyboardEventTypes.KEYUP:d._keyMap[e.event.key]=!1}}))}return e.prototype.updateTexture=function(){var e,t;return i(this,void 0,void 0,(function(){var r;return l(this,(function(n){switch(n.label){case 0:return 0===this._mipLevel?[3,2]:[4,this._setMipLevel(0)];case 1:n.sent(),n.label=2;case 2:return this._didEdit=!0,r=this._editing3D?this._3DCanvas:this._2DCanvas,this._editing3D&&(this._3DCanvasTexture.update(),this._3DScene.render()),this._originalTexture.isCube||(this._target?this._target.element=r:this._target=new u.HtmlElementTexture("editor",r,{engine:null===(e=this._originalTexture.getScene())||void 0===e?void 0:e.getEngine(),scene:null,samplingMode:this._originalTexture.samplingMode,generateMipMaps:null===(t=this._originalInternalTexture)||void 0===t?void 0:t.generateMipMaps}),this.pushTexture()),this._originalTexture._texture=this._target._texture,this._channelsTexture.element=r,this.updateDisplay(),this._onUpdate(),[2]}}))}))},e.prototype.pushTexture=function(){var e,t=this;this._canPush?(this._target.update(this._originalTexture.invertY),null===(e=this._target._texture)||void 0===e||e.updateSize(this._size.width,this._size.height),this._editing3D?this._imageData=this._3DEngine.readPixels(0,0,this._size.width,this._size.height):this._imageData=this._2DCanvas.getContext("2d").getImageData(0,0,this._size.width,this._size.height).data,this._canPush=!1,this._shouldPush=!1,setTimeout((function(){t._canPush=!0,t._shouldPush&&t.pushTexture()}),this.PUSH_FREQUENCY)):this._shouldPush=!0},e.prototype.startPainting=function(){return i(this,void 0,void 0,(function(){var e,t,r,n,a;return l(this,(function(o){switch(o.label){case 0:return 0==this._mipLevel?[3,2]:[4,this._setMipLevel(0)];case 1:o.sent(),o.label=2;case 2:return e=0,t=0,r=this._size.width,n=this._size.height,-1!=this._metadata.select.x1&&(e=this._metadata.select.x1,t=this._metadata.select.y1,r=this._metadata.select.x2-this._metadata.select.x1,n=this._metadata.select.y2-this._metadata.select.y1),this._paintCanvas.width=r,this._paintCanvas.height=n,(a=this._paintCanvas.getContext("2d")).imageSmoothingEnabled=!1,a.drawImage(this._2DCanvas,e,t,r,n,0,0,r,n),[2,a]}}))}))},e.prototype.updatePainting=function(){var e=0,t=0,r=this._size.width,n=this._size.height;-1!=this._metadata.select.x1&&(e=this._metadata.select.x1,t=this._metadata.select.y1,r=this._metadata.select.x2-this._metadata.select.x1,n=this._metadata.select.y2-this._metadata.select.y1);var a,o=!0;this._channels.forEach((function(e){e.editable||(o=!1)})),o||(a=this._2DCanvas.getContext("2d").getImageData(e,t,r,n).data);var i=this._paintCanvas.getContext("2d"),l=this.canvas2D.getContext("2d");if(l.globalAlpha=1,l.globalCompositeOperation="destination-out",l.fillStyle="white",l.fillRect(e,t,r,n),l.imageSmoothingEnabled=!1,o)l.globalCompositeOperation="source-over",l.globalAlpha=1,l.drawImage(i.canvas,e,t);else{var s=i.getImageData(0,0,r,n),p=s.data;this._channels.forEach((function(e,t){if(!e.editable)for(var o=t;o<r*n*4;o+=4)p[o]=a[o]})),l.globalCompositeOperation="source-over",l.globalAlpha=1,l.putImageData(s,e,t)}this.updateTexture()},e.prototype.stopPainting=function(){this._paintCanvas.getContext("2d").clearRect(0,0,this._paintCanvas.width,this._paintCanvas.height)},e.prototype.updateDisplay=function(){this._3DScene.render(),this._channelsTexture.update(!0)},Object.defineProperty(e.prototype,"channels",{set:function(e){var t=this,r=!1;e.length!==this._channels.length?r=!0:e.forEach((function(e,n){e.visible!==t._channels[n].visible&&(r=!0,t._planeMaterial.setFloat(e.id.toLowerCase(),e.visible?1:0))})),this._channels=e,r&&this.updateDisplay()},enumerable:!1,configurable:!0}),e.prototype.paintPixelsOnCanvas=function(e,t){var r=t.getContext("2d"),n=r.createImageData(t.width,t.height);n.data.set(e),r.putImageData(n,0,0)},e.prototype.grabOriginalTexture=function(){return i(this,void 0,void 0,(function(){var e;return l(this,(function(t){switch(t.label){case 0:return this.setSize(this._originalTexture.getSize()),[4,tt.GetTextureDataAsync(this._originalTexture,this._size.width,this._size.height,this._face,{R:!0,G:!0,B:!0,A:!0},void 0,this._mipLevel)];case 1:return e=t.sent(),this._imageData=e,this.paintPixelsOnCanvas(e,this._2DCanvas),this._3DCanvasTexture.update(),this.updateDisplay(),[2,e]}}))}))},e.prototype.getMouseCoordinates=function(e){var t;if(null===(t=e.pickInfo)||void 0===t?void 0:t.hit){var r=Math.floor(e.pickInfo.getTextureCoordinates().x*this._size.width),n=Math.floor((1-e.pickInfo.getTextureCoordinates().y)*this._size.height);return new u.Vector2(r,n)}return new u.Vector2},Object.defineProperty(e.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"canvas2D",{get:function(){return this._2DCanvas},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"size",{get:function(){return this._size},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"tool",{get:function(){return this._tool},set:function(e){var t;this._tool&&this._tool.instance.cleanup(),this._tool=e,this._tool&&(this._tool.instance.setup(),this._editing3D&&!this._tool.is3D?(this._editing3D=!1,null===(t=this._2DCanvas.getContext("2d"))||void 0===t||t.drawImage(this._3DCanvas,0,0)):!this._editing3D&&this._tool.is3D&&(this._editing3D=!0,this.updateTexture()))},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"face",{set:function(e){this._face!==e&&(this._face=e,this.grabOriginalTexture(),this.updateDisplay())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"mipLevel",{set:function(e){this._mipLevel!==e&&(this._mipLevel=e,this.grabOriginalTexture())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"scene3D",{get:function(){return this._3DScene},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"metadata",{set:function(e){this._metadata=e;var t=e.select,r=t.x1,n=t.y1,a=t.x2,o=t.y2;this._planeMaterial.setInt("x1",r),this._planeMaterial.setInt("y1",n),this._planeMaterial.setInt("x2",a),this._planeMaterial.setInt("y2",o)},enumerable:!1,configurable:!0}),e.prototype.makePlane=function(){this._plane&&this._plane.dispose(),this._plane=u.PlaneBuilder.CreatePlane("plane",{width:this._size.width,height:this._size.height},this._scene),this._plane.enableEdgesRendering(),this._plane.edgesWidth=4,this._plane.edgesColor=new u.Color4(1,1,1,1),this._plane.enablePointerMoveEvents=!0,this._plane.material=this._planeMaterial},e.prototype.reset=function(){this._tool&&this._tool.instance.onReset&&this._tool.instance.onReset(),this._originalTexture._texture=this._originalInternalTexture,this.grabOriginalTexture(),this.makePlane(),this._didEdit=!1,this._onUpdate()},e.prototype.resize=function(e){return i(this,void 0,void 0,(function(){var t;return l(this,(function(r){switch(r.label){case 0:return[4,tt.GetTextureDataAsync(this._originalTexture,e.width,e.height,this._face,{R:!0,G:!0,B:!0,A:!0})];case 1:return t=r.sent(),this.setSize(e),this.paintPixelsOnCanvas(t,this._2DCanvas),this.updateTexture(),this._didEdit=!0,[2]}}))}))},e.prototype.setSize=function(e){var t=this._size;this._size=e,this._2DCanvas.width=this._size.width,this._2DCanvas.height=this._size.height,this._3DCanvas.width=this._size.width,this._3DCanvas.height=this._size.height,this._planeMaterial.setInt("w",this._size.width),this._planeMaterial.setInt("h",this._size.height),t.width==e.width&&t.height==e.height||(this._cameraPos.x=0,this._cameraPos.y=0,this._scale=1.5/Math.max(this._size.width,this._size.height)),this.makePlane()},e.prototype.upload=function(e){var t=this;u.Tools.ReadFile(e,(function(r){var n=new Blob([r],{type:"octet/stream"}),a=void 0;e.name.toLowerCase().indexOf(".dds")>0?a=".dds":e.name.toLowerCase().indexOf(".env")>0&&(a=".env");var o=new FileReader;o.readAsDataURL(n),o.onloadend=function(){var e=o.result;if(".dds"===a||".env"===a)t._originalTexture.updateURL(e,a,(function(){return t.grabOriginalTexture()}));else var r=new u.Texture(e,t._scene,t._originalTexture.noMipmap,!1,u.Texture.NEAREST_SAMPLINGMODE,(function(){tt.GetTextureDataAsync(r,r.getSize().width,r.getSize().height,0,{R:!0,G:!0,B:!0,A:!0}).then((function(e){return i(t,void 0,void 0,(function(){return l(this,(function(t){switch(t.label){case 0:return this._tool&&this._tool.instance.onReset&&this._tool.instance.onReset(),r.dispose(),this.setSize(r.getSize()),this.paintPixelsOnCanvas(e,this._2DCanvas),[4,this.updateTexture()];case 1:return t.sent(),this._setMipLevel(0),[2]}}))}))}))}))}}),void 0,!0)},e.prototype.saveTexture=function(){var e=this,t=this._editing3D?this._3DCanvas:this._2DCanvas;u.Tools.ToBlob(t,(function(t){u.Tools.Download(t,e._originalTexture.name)}))},e.prototype.dispose=function(){var e,t;this._didEdit&&(null===(e=this._originalInternalTexture)||void 0===e||e.dispose()),this._tool&&this._tool.instance.cleanup(),null===(t=this._paintCanvas.parentNode)||void 0===t||t.removeChild(this._paintCanvas),this._3DPlane.dispose(),this._3DCanvasTexture.dispose(),this._3DScene.dispose(),this._3DEngine.dispose(),this._plane.dispose(),this._channelsTexture.dispose(),this._planeMaterial.dispose(),this._camera.dispose(),this._scene.dispose(),this._engine.dispose()},e}(),st=function(e){function t(t){var r=e.call(this,t)||this;return r.state={toolURL:"",addOpen:!1},r}return a(t,e),t.prototype.computeRGBAColor=function(){var e=Math.floor(255*this.props.metadata.alpha).toString(16).padStart(2,"0");return u.Color4.FromHexString(""+this.props.metadata.color+e)},t.prototype.shouldComponentUpdate=function(e){return e.tools!=this.props.tools||e.activeToolIndex!==this.props.activeToolIndex||e.metadata!=this.props.metadata||e.pickerOpen!=this.props.pickerOpen},t.prototype.render=function(){var e=this;return s.createElement("div",{id:"toolbar"},s.createElement("div",{id:"tools"},this.props.tools.map((function(t,r){return s.createElement("img",{src:"data:image/svg+xml;base64,"+t.icon,className:r===e.props.activeToolIndex?"icon button active":"icon button",alt:t.name,title:t.name,onClick:function(t){0===t.button&&e.props.changeTool(r)},key:r})}))),s.createElement("div",{id:"color",onClick:function(){e.props.pickerOpen||e.props.setPickerOpen(!0)},title:"Color",className:"icon button"+(this.props.pickerOpen?" active":"")},s.createElement("div",{id:"active-color-bg"},s.createElement("div",{id:"active-color",style:{backgroundColor:this.props.metadata.color,opacity:this.props.metadata.alpha}}))),this.props.pickerOpen&&s.createElement("div",{id:"color-picker",ref:this.props.pickerRef},s.createElement(ze,{color:this.computeRGBAColor(),onColorChanged:function(t){var r={color:t.toHexString(!0),alpha:t.a};r.color===e.props.metadata.color&&r.alpha===e.props.metadata.alpha||e.props.setMetadata(r)}})))},t}(s.Component),pt=function(e){function t(t){var n=e.call(this,t)||this;return n._resetButton=r(29),n._uploadButton=r(30),n._saveButton=r(31),n._babylonLogo=r(32),n._resizeButton=r(33),n._mipUp=r(34),n._mipDown=r(35),n._faces=[r(36),r(37),r(38),r(39),r(40),r(41)],n.state={width:t.size.width,height:t.size.height},n}return a(t,e),t.prototype.pixelData=function(e){return s.createElement("span",{className:"pixel-data"},e.name,": ",s.createElement("span",{className:"value"},void 0!==e.data?e.data:"-"))},t.prototype.getNewDimension=function(e,t){return!isNaN(t)&&parseInt(t)>0&&Number.isInteger(parseInt(t))?parseInt(t):e},t.prototype.componentWillUpdate=function(e){e.size.width==this.props.size.width&&e.size.height==this.props.size.height||this.setState({width:e.size.width,height:e.size.height})},t.prototype.render=function(){var e=this,t=this.props,r=t.mipLevel,n=t.setMipLevel,a=t.pixelData,o=t.resizeTexture,i=t.texture,l=t.face,p=t.setFace,c=t.saveTexture,u=t.resetTexture,d=t.uploadTexture,h=Math.floor(Math.log2(Math.max(i.getSize().width,i.getSize().height))),b=i.getScene().getEngine(),m=!i.noMipmap&&(2==b.webGLVersion||b._gl.getExtension("EXT_shader_texture_lod"));return s.createElement("div",{id:"properties"},s.createElement("div",{className:"tab",id:"logo-tab"},s.createElement("img",{className:"icon",src:this._babylonLogo})),s.createElement("div",{id:"left"},s.createElement("div",{className:"tab",id:"dimensions-tab"},s.createElement("form",{onSubmit:function(t){e.props.resizeTexture(e.state.width,e.state.height),t.preventDefault()}},s.createElement("label",{className:"dimensions"},"W: ",s.createElement("input",{type:"text",value:this.state.width,readOnly:i.isCube,onChange:function(t){return e.setState({width:e.getNewDimension(e.state.width,t.target.value)})}})),s.createElement("label",{className:"dimensions"},"H: ",s.createElement("input",{type:"text",value:this.state.height,readOnly:i.isCube,onChange:function(t){return e.setState({height:e.getNewDimension(e.state.height,t.target.value)})}})),!i.isCube&&s.createElement("img",{id:"resize",className:"icon button",title:"Resize",alt:"Resize",src:this._resizeButton,onClick:function(){return o(e.state.width,e.state.height)}}))),s.createElement("div",{className:"tab",id:"pixel-coords-tab"},s.createElement(this.pixelData,{name:"X",data:a.x}),s.createElement(this.pixelData,{name:"Y",data:a.y})),s.createElement("div",{className:"tab",id:"pixel-color-tab"},s.createElement(this.pixelData,{name:"R",data:a.r}),s.createElement(this.pixelData,{name:"G",data:a.g}),s.createElement(this.pixelData,{name:"B",data:a.b}),s.createElement(this.pixelData,{name:"A",data:a.a})),i.isCube&&s.createElement("div",{className:"tab",id:"face-tab"},this._faces.map((function(e,t){return s.createElement("img",{key:t,className:l==t?"icon face button active":"icon face button",src:e,onClick:function(){return p(t)}})}))),m&&s.createElement("div",{className:"tab",id:"mip-tab"},s.createElement("img",{title:"Mip Preview Up",className:"icon button",src:this._mipUp,onClick:function(){return r>0&&n(r-1)}}),s.createElement("img",{title:"Mip Preview Down",className:"icon button",src:this._mipDown,onClick:function(){return r<h&&n(r+1)}}))),s.createElement("div",{className:"tab",id:"right-tab"},s.createElement("img",{title:"Reset",className:"icon button",src:this._resetButton,onClick:function(){return u()}}),s.createElement("label",null,s.createElement("input",{accept:".jpg, .png, .tga, .dds, .env",type:"file",onChange:function(e){var t=e.target.files;t&&t.length&&d(t[0]),e.target.value=""}}),s.createElement("img",{title:"Upload",className:"icon button",src:this._uploadButton})),s.createElement("img",{title:"Save",className:"icon button",src:this._saveButton,onClick:function(){return c()}})))},t}(s.PureComponent),ct=r(42),ut=r(43),dt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return a(t,e),t.prototype.render=function(){var e=this;return s.createElement("div",{id:"channels-bar"},this.props.channels.map((function(t,r){var n=t.visible?"Hide":"Show",a=t.editable?"Lock":"Unlock";return s.createElement("div",{key:t.name,className:t.editable?"channel":"channel uneditable"},s.createElement("img",{className:t.visible?"icon channel-visibility visible":"icon channel-visibility",onClick:function(){var t=e.props.channels;t[r].visible=!t[r].visible,e.props.setChannels(t)},src:t.visible?ct:ut,title:n+" "+t.name}),s.createElement("img",{className:"icon channel-name",onClick:function(){var t=e.props.channels;t[r].editable=!t[r].editable,e.props.setChannels(t)},src:t.icon,title:a+" "+t.name}))})))},t}(s.PureComponent),ht=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return a(t,e),t.prototype.render=function(){var e=Math.pow(2,this.props.mipLevel),t=Math.ceil(this.props.texture.getSize().width/e),r=Math.ceil(this.props.texture.getSize().height/e);return s.createElement("div",{id:"bottom-bar"},s.createElement("span",{id:"file-url"},this.props.texture.name),!this.props.texture.noMipmap&&s.createElement("span",{id:"mip-level"},"MIP Preview: ",this.props.mipLevel," ",t,"x",r))},t}(s.PureComponent),bt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return a(t,e),t.prototype.render=function(){return s.createElement("div",null,s.createElement("canvas",{id:"canvas-ui",ref:this.props.canvasUI,tabIndex:1}),s.createElement("canvas",{id:"canvas-2D",ref:this.props.canvas2D,width:this.props.texture.getSize().width,height:this.props.texture.getSize().height,hidden:!0}),s.createElement("canvas",{id:"canvas-3D",ref:this.props.canvas3D,width:this.props.texture.getSize().width,height:this.props.texture.getSize().height,hidden:!0}))},t}(s.Component),mt={name:"Paintbrush",type:function(){function e(e){this.width=15,this.mousePos=null,this.getParameters=e}return e.prototype.paint=function(e){var t=this.getParameters(),r=t.getMouseCoordinates,n=t.metadata,a=t.updatePainting,o=r(e),i=o.x,l=o.y;-1!=n.select.x1&&(i-=n.select.x1,l-=n.select.y1);var s,p,c=this.ctx;if(p=new u.Vector2,null==this.mousePos)this.mousePos=new u.Vector2(i,l),s=1;else{var d=this.width/4,h=new u.Vector2(i-this.mousePos.x,l-this.mousePos.y);s=Math.ceil(h.length()/d);var b=h.length()/s;p=h.normalize().multiplyByFloats(b,b)}for(var m=this.mousePos.clone(),g=0;g<s;g++)c.globalAlpha=1,c.globalCompositeOperation="destination-out",c.drawImage(this.circleCanvas,Math.ceil(m.x-this.width/2),Math.ceil(m.y-this.width/2)),c.globalAlpha=n.alpha,c.globalCompositeOperation="source-over",c.drawImage(this.circleCanvas,Math.ceil(m.x-this.width/2),Math.ceil(m.y-this.width/2)),m.addInPlace(p);a(),this.mousePos=new u.Vector2(i,l)},e.prototype.setBrushWidth=function(e){this.width=e},e.prototype.setup=function(){var e=this,t=this.getParameters().scene;this.pointerObserver=t.onPointerObservable.add((function(t){return i(e,void 0,void 0,(function(){var e,r,n,a,o,i,s,p,c,d,h,b,m,g,f,v,y,C;return l(this,(function(l){switch(l.label){case 0:if(e=this.getParameters(),r=e.startPainting,n=e.stopPainting,a=e.metadata,!(null===(y=t.pickInfo)||void 0===y?void 0:y.hit))return[3,3];if(t.type!==u.PointerEventTypes.POINTERDOWN)return[3,2];if(0!=t.event.button)return[3,2];for(this.isPainting=!0,(o=document.createElement("canvas")).width=this.width,o.height=this.width,(i=o.getContext("2d")).imageSmoothingEnabled=!1,s=new Array(4*this.width*this.width),p=this.width*this.width/4,c=u.Color3.FromHexString(a.color),d=Math.floor(255*c.r),h=Math.floor(255*c.g),b=Math.floor(255*c.b),m=0,g=-Math.floor(this.width/2);g<Math.ceil(this.width/2);g++)for(f=-Math.floor(this.width/2);f<Math.ceil(this.width/2);f++)s[m++]=d,s[m++]=h,s[m++]=b,s[m++]=f*f+g*g<=p?255:0;return i.putImageData(new ImageData(Uint8ClampedArray.from(s),this.width,this.width),0,0),this.circleCanvas=o,v=this,[4,r()];case 1:v.ctx=l.sent(),this.paint(t),l.label=2;case 2:t.type===u.PointerEventTypes.POINTERMOVE&&this.isPainting&&this.paint(t),l.label=3;case 3:return t.type===u.PointerEventTypes.POINTERUP&&0==t.event.button&&(this.isPainting=!1,null===(C=this.circleCanvas.parentNode)||void 0===C||C.removeChild(this.circleCanvas),n(),this.mousePos=null),[2]}}))}))})),this.isPainting=!1},e.prototype.cleanup=function(){this.isPainting=!1,this.pointerObserver&&this.getParameters().scene.onPointerObservable.remove(this.pointerObserver)},e}(),settingsComponent:function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return a(t,e),t.prototype.render=function(){var e=this,t=this.props.instance;return s.createElement("div",null,s.createElement("label",{className:"tool-slider-input"},s.createElement("span",null,"Size: ",t.width),s.createElement("input",{id:"contrast-slider",type:"range",min:1,max:100,value:t.width,onChange:function(r){t.setBrushWidth(r.target.valueAsNumber),e.forceUpdate()}})))},t}(s.Component),icon:"PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDQwIDQwIj48cmVjdCB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHN0eWxlPSJmaWxsOm5vbmUiLz48cGF0aCBkPSJNMjksMTFhMy41NywzLjU3LDAsMCwxLDAsNS4wNkwxNywyOGEyLjM0LDIuMzQsMCwwLDEtMSwuNThMMTAuOTEsMzBhLjc1Ljc1LDAsMCwxLS45Mi0uOTJMMTEuMzgsMjRBMi4zNCwyLjM0LDAsMCwxLDEyLDIzbDEyLTEyQTMuNTcsMy41NywwLDAsMSwyOSwxMVpNMjMsMTQuMSwxMywyNGEuNjkuNjksMCwwLDAtLjE5LjMzbC0xLjA1LDMuODUsMy44NS0xQS42OS42OSwwLDAsMCwxNiwyN0wyNS45LDE3Wm0yLTItMSwxTDI3LDE2bDEtMUEyLjA4LDIuMDgsMCwxLDAsMjUsMTIuMDdaIiBzdHlsZT0iZmlsbDojZmZmIi8+PC9zdmc+",cursor:"iVBORw0KGgoAAAANSUhEUgAAABUAAAAVAgMAAADUeU0FAAAACVBMVEUAAAAAAAD///+D3c/SAAAAAXRSTlMAQObYZgAAAAFiS0dEAmYLfGQAAAA3SURBVAjXY2CAgVUNYGoqhFJjwE2BgQYDBwMXUGiFGtcyBgbVkKmtYXAeVA4O8BkGtQ9qOwgAAEPfC1QJPmWqAAAAAElFTkSuQmCC"},gt={name:"Eyedropper",type:function(){function e(e){this.getParameters=e}return e.prototype.pick=function(e){var t=this.getParameters(),r=t.canvas2D,n=t.setMetadata,a=t.getMouseCoordinates,o=r.getContext("2d"),i=a(e),l=i.x,s=i.y,p=o.getImageData(l,s,1,1).data;n({color:u.Color3.FromInts(p[0],p[1],p[2]).toHexString(),alpha:p[3]/255})},e.prototype.setup=function(){var e=this;this.pointerObserver=this.getParameters().scene.onPointerObservable.add((function(t){var r;(null===(r=t.pickInfo)||void 0===r?void 0:r.hit)&&(t.type===u.PointerEventTypes.POINTERDOWN&&(e.isPicking=!0,e.pick(t)),t.type===u.PointerEventTypes.POINTERMOVE&&e.isPicking&&e.pick(t),t.type===u.PointerEventTypes.POINTERUP&&(e.isPicking=!1))})),this.isPicking=!1},e.prototype.cleanup=function(){this.pointerObserver&&this.getParameters().scene.onPointerObservable.remove(this.pointerObserver)},e}(),icon:"PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDQwIDQwIj48cmVjdCB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHN0eWxlPSJmaWxsOm5vbmUiLz48cGF0aCBkPSJNMjkuMzIsMTAu\n NjhjLTEuNjYtMS42Ni00LjA2LTEtNS41Ni41YTExLjg5LDExLjg5LDAsMCwwLTEuNjYsMi4zMUwyMiwxMy40MWExLjg5LDEuODksMCwwLDAtMi42NiwwbC0uOS45YTEuODksMS44OSwwLDAsMC0uMjIsMi4zOWwtNi4wOSw2LjA5YTIuNzUsMi43NSwwLDAsMC0uNzMs\n MS4yOGwtLjgxLDMuMjYtLjU2LjU2YTEuMTYsMS4xNiwwLDAsMCwwLDEuNjVsLjQxLjQxYTEuMTcsMS4xNywwLDAsMCwxLjY1LDBsLjU2LS41NiwzLjI2LS44MWEyLjc1LDIuNzUsMCwwLDAsMS4yOC0uNzNsNi4xNC02LjE0YTEuODcsMS44NywwLDAsMCwuODQuMjEs\n MS44MywxLjgzLDAsMCwwLDEuMzMtLjU1bC45LS45YTEuODcsMS44NywwLDAsMCwuMDgtMi41NywxMS41NCwxMS41NCwwLDAsMCwyLjMyLTEuNjZDMzAuMzIsMTQuNzQsMzEsMTIuMzUsMjkuMzIsMTAuNjhaTTE2LjE1LDI2Ljc5YTEuMjEsMS4yMSwwLDAsMS0uNTgu\n MzNMMTIsMjhsLjktMy41OWExLjIxLDEuMjEsMCwwLDEsLjMzLS41OGw2LjA3LTYuMDcsMi45NCwyLjk0Wm05LjIxLTcuMzgtLjkuOWMtLjE5LjItLjM0LjItLjU0LDBsLTQuNC00LjRhLjQuNCwwLDAsMSwwLS41NGwuOS0uOWEuNDMuNDMsMCwwLDEsLjI3LS4xMS4z\n OS4zOSwwLDAsMSwuMjcuMTFsNC40LDQuNEEuMzguMzgsMCwwLDEsMjUuMzYsMTkuNDFabTMuMzgtNS45M2EzLjcsMy43LDAsMCwxLTEsMS43LDExLjY3LDExLjY3LDAsMCwxLTIuMzUsMS42MkwyMy4yLDE0LjU5YTExLjY3LDExLjY3LDAsMCwxLDEuNjItMi4zNSwz\n LjcsMy43LDAsMCwxLDEuNy0xLDEuODMsMS44MywwLDAsMSwyLjIyLDIuMjJaIiBzdHlsZT0iZmlsbDojZmZmIi8+PC9zdmc+",cursor:"iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAABmJLR0QA/wD/AP+gvaeTAAAByklEQVQ4jbWUv4saQRTHd+4s/BuCYRH1n7BQEhCRuyJ3RQgpRVt/tFvYSAjLxMPiWIJ1OA6OKwKBdCGBkIS4pFs76xgXhOlyyconzSrrojub4l618+a9z/u+mTdrGPdgIk0QwDZBCG3OUerqepYeCgigAbyJ+a+AEyB9lTDxAfBhPp9jWRZh+wB0u11msxnAJyCXSmkI/DIejx9Vq1Ujm83u7OdyOaPRaBi2bVeAr8BDnUIBfJRSUi6XWSwWa+B1VClw6ft+UKlUsG0b4DNw+G6AU8/zME2T5XIZAE9C/xYark983/9rmubmKM6SoNedTofRaARwqenqQkpJr9cDuI3uiYiSvbaZS4Dod1J8JrJIUoUQYgs+FLuplYk79lQ2hBAipvSggH2Vbvr9PlJKgFea2JeO49BqtQDeJgWee55HPp9ntVr9AR6H/vjtV5VSd8Vikel0CvA0CXoEfBsOh9RqNZRSd8CL2JwOlVK/6/X65rVNgWPdEeTX6/XPwWBAqVRiMpnsPFPHcSgUCliWRRAEv4BCIjAKBr67rkuz2dyBttttXNcF+AEUUwEj4GPgGfAu1v574DmQ0UI0BXYuSmepf9L/NZv3Yf8AKtG4imEra4UAAAAASUVORK5CYII="},ft={name:"Floodfill",type:function(){function e(e){this.getParameters=e}return e.prototype.fill=function(){return i(this,void 0,void 0,(function(){var e,t,r,n,a,o;return l(this,(function(i){switch(i.label){case 0:return e=this.getParameters(),t=e.metadata,r=e.startPainting,n=e.updatePainting,a=e.stopPainting,[4,r()];case 1:return(o=i.sent()).fillStyle=t.color,o.globalAlpha=t.alpha,o.globalCompositeOperation="copy",o.fillRect(0,0,o.canvas.width,o.canvas.height),n(),a(),[2]}}))}))},e.prototype.setup=function(){var e=this;this.pointerObserver=this.getParameters().scene.onPointerObservable.add((function(t){var r;(null===(r=t.pickInfo)||void 0===r?void 0:r.hit)&&t.type===u.PointerEventTypes.POINTERDOWN&&0===t.event.button&&e.fill()}))},e.prototype.cleanup=function(){this.pointerObserver&&this.getParameters().scene.onPointerObservable.remove(this.pointerObserver)},e}(),icon:"PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDQwIDQwIj48cmVjdCB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHN0eWxlPSJmaWxsOm5vbmUiLz48cGF0aCBkPSJNMjAsMTAuNWEu\n NzUuNzUsMCwwLDAtMS41LDB2MS4yNWEyLjE0LDIuMTQsMCwwLDAtLjg0LjUzbC02Ljg4LDYuODhhMi4yNSwyLjI1LDAsMCwwLDAsMy4xOGw0Ljg4LDQuODhhMi4yNSwyLjI1LDAsMCwwLDMuMTgsMGw2Ljg4LTYuODhhMi4yNSwyLjI1LDAsMCwwLDAtMy4xOGwtNC44\n OC00Ljg4YTIuMjksMi4yOSwwLDAsMC0uODQtLjUzWm0tOC4xNiw5LjcyLDYuNjYtNi42NlYxNUEuNzUuNzUsMCwwLDAsMjAsMTVWMTMuNTZsNC42Niw0LjY2YS43NS43NSwwLDAsMSwwLDEuMDZsLTEsMUgxMS44Wm0uNDcsMS41M2g5Ljg4bC00LjQxLDQuNDFhLjc1\n Ljc1LDAsMCwxLTEuMDYsMFoiIHN0eWxlPSJmaWxsOiNmZmYiLz48cGF0aCBkPSJNMjcuNTEsMjEuODVhLjg4Ljg4LDAsMCwwLTEuNTQsMGwtMiwzLjc3YTMuMTUsMy4xNSwwLDEsMCw1LjU2LDBabS0yLjIzLDQuNDcsMS40Ni0yLjczLDEuNDUsMi43M2ExLjY1LDEu\n NjUsMCwxLDEtMi45MSwwWiIgc3R5bGU9ImZpbGw6I2ZmZiIvPjwvc3ZnPg=="},vt=[{name:"Rectangle Select",type:function(){function e(e){this.isSelecting=!1,this.xStart=-1,this.yStart=-1,this.getParameters=e}return e.prototype.setup=function(){var e=this,t=this.getParameters().scene;this.pointerObserver=t.onPointerObservable.add((function(t){var r,n,a=e.getParameters(),o=a.getMouseCoordinates,i=a.setMetadata,l=a.metadata;if(null===(n=t.pickInfo)||void 0===n?void 0:n.hit){if(t.type===u.PointerEventTypes.POINTERDOWN&&0==t.event.button){e.isSelecting=!0;var s=(r=o(t),e.xStart=r.x,e.yStart=r.y,r);i({select:{x1:c=s.x,y1:d=s.y,x2:c,y2:d}})}if(t.type===u.PointerEventTypes.POINTERMOVE&&e.isSelecting){var p=o(t),c=p.x,d=p.y;i({select:{x1:Math.min(c,e.xStart),y1:Math.min(d,e.yStart),x2:Math.max(c,e.xStart),y2:Math.max(d,e.yStart)}})}}t.type===u.PointerEventTypes.POINTERUP&&0==t.event.button&&(e.isSelecting=!1,l.select.x1!==l.select.x2&&l.select.y1!==l.select.y2||i({select:{x1:-1,y1:-1,x2:-1,y2:-1}}))}))},e.prototype.cleanup=function(){this.isSelecting=!1,this.pointerObserver&&this.getParameters().scene.onPointerObservable.remove(this.pointerObserver)},e}(),icon:"PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgdmlld0JveD0iMCAwIDQwIDQwIj48cmVjdCB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHN0eWxlPSJmaWxsOm5vbmUiLz48cGF0aCBkPSJNMTEuNjMsMTUuNjNIMTAuMzh2LTMuN2ExLjU0LDEuNTQsMCwwLDEsMS41NS0xLjU1aDMuN3YxLjI1SDEyLjI1YS42Mi42MiwwLDAsMC0uNjIuNjJaIiBzdHlsZT0iZmlsbDojZmZmIi8+PHBhdGggZD0iTTExLjYzLDIyLjYzSDEwLjM4VjE3LjM4aDEuMjVaIiBzdHlsZT0iZmlsbDojZmZmIi8+PHBhdGggZD0iTTI5LjYzLDIyLjYzSDI4LjM4VjE3LjM4aDEuMjVaIiBzdHlsZT0iZmlsbDojZmZmIi8+PHBhdGggZD0iTTE1LjYzLDI5LjYzaC0zLjdhMS41NSwxLjU1LDAsMCwxLTEuNTUtMS41NlYyNC4zOGgxLjI1djMuMzdhLjYzLjYzLDAsMCwwLC42Mi42M2gzLjM4WiIgc3R5bGU9ImZpbGw6I2ZmZiIvPjxwYXRoIGQ9Ik0yOC4wNywyOS42M0gyNC4zOFYyOC4zOGgzLjM3YS42NC42NCwwLDAsMCwuNjMtLjYzVjI0LjM4aDEuMjV2My42OUExLjU2LDEuNTYsMCwwLDEsMjguMDcsMjkuNjNaIiBzdHlsZT0iZmlsbDojZmZmIi8+PHBhdGggZD0iTTIyLjYzLDExLjYzSDE3LjM4VjEwLjM4aDUuMjVaIiBzdHlsZT0iZmlsbDojZmZmIi8+PHBhdGggZD0iTTI5LjYzLDE1LjYzSDI4LjM4VjEyLjI1YS42My42MywwLDAsMC0uNjMtLjYySDI0LjM4VjEwLjM4aDMuNjlhMS41NSwxLjU1LDAsMCwxLDEuNTYsMS41NVoiIHN0eWxlPSJmaWxsOiNmZmYiLz48cGF0aCBkPSJNMjIuNjMsMjkuNjNIMTcuMzhWMjguMzhoNS4yNVoiIHN0eWxlPSJmaWxsOiNmZmYiLz48L3N2Zz4=",cursor:"iVBORw0KGgoAAAANSUhEUgAAABUAAAAVAgMAAADUeU0FAAAACVBMVEUAAAAAAAD///+D3c/SAAAAAXRSTlMAQObYZgAAAAFiS0dEAmYLfGQAAAAnSURBVAjXY2CAAS0IpUY0BdG1ikNrFQODaqiaaBicBwfEG6aF0AQA4oYGiJg4woEAAAAASUVORK5CYII="},mt,gt,ft],yt=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return a(t,e),t.prototype.render=function(){return this.props.tool&&this.props.tool.settingsComponent?s.createElement("div",{id:"tool-ui"},s.createElement(this.props.tool.settingsComponent,{instance:this.props.tool.instance})):s.createElement(s.Fragment,null)},t}(s.Component);r(44);var Ct,Et=function(e){function t(t){var n=e.call(this,t)||this;n._UICanvas=s.createRef(),n._2DCanvas=s.createRef(),n._3DCanvas=s.createRef(),n._pickerRef=s.createRef();var a=[{name:"Red",visible:!0,editable:!0,id:"R",icon:r(46)},{name:"Green",visible:!0,editable:!0,id:"G",icon:r(47)},{name:"Blue",visible:!0,editable:!0,id:"B",icon:r(48)}];return n.props.texture.isCube?a.push({name:"Display",visible:!0,editable:!0,id:"A",icon:r(49)}):a.push({name:"Alpha",visible:!0,editable:!0,id:"A",icon:r(50)}),n.state={tools:[],activeToolIndex:-1,metadata:{color:"#ffffff",alpha:1,select:{x1:-1,y1:-1,x2:-1,y2:-1}},channels:a,pixelData:{},face:0,mipLevel:0,pickerOpen:!1},n.loadToolFromURL=n.loadToolFromURL.bind(n),n.changeTool=n.changeTool.bind(n),n.setMetadata=n.setMetadata.bind(n),n.saveTexture=n.saveTexture.bind(n),n.resetTexture=n.resetTexture.bind(n),n.resizeTexture=n.resizeTexture.bind(n),n.uploadTexture=n.uploadTexture.bind(n),n.setPickerOpen=n.setPickerOpen.bind(n),n.onPointerDown=n.onPointerDown.bind(n),n}return a(t,e),t.prototype.componentDidMount=function(){var e=this;this._textureCanvasManager=new lt(this.props.texture,this.props.window.current.getWindow(),this._UICanvas.current,this._2DCanvas.current,this._3DCanvas.current,(function(t){e.setState({pixelData:t})}),this.state.metadata,(function(){return e.textureDidUpdate()}),(function(t){return e.setMetadata(t)}),(function(t){return e.setState({mipLevel:t})})),this.addTools(vt)},t.prototype.componentDidUpdate=function(){var e=[];this.state.channels.forEach((function(t){return e.push(o({},t))})),this._textureCanvasManager.channels=e,this._textureCanvasManager.face=this.state.face,this._textureCanvasManager.mipLevel=this.state.mipLevel},t.prototype.componentWillUnmount=function(){this._textureCanvasManager.dispose()},t.prototype.textureDidUpdate=function(){var e=this;null!=this._timer&&clearTimeout(this._timer),this._timer=window.setTimeout((function(){e.props.onUpdate(),e._timer=null}),t.PREVIEW_UPDATE_DELAY_MS)},t.prototype.loadToolFromURL=function(e){var t=this;u.Tools.LoadScript(e,(function(){t.addTools([_TOOL_DATA_])}))},t.prototype.addTools=function(e){var t=this,r=[];e.forEach((function(e){var n=o(o({},e),{instance:new e.type((function(){return t.getToolParameters()}))});r=r.concat(n)})),r=this.state.tools.concat(r),this.setState({tools:r}),console.log(r)},t.prototype.getToolParameters=function(){var e=this;return{scene:this._textureCanvasManager.scene,canvas2D:this._textureCanvasManager.canvas2D,scene3D:this._textureCanvasManager.scene3D,size:this._textureCanvasManager.size,updateTexture:function(){return e._textureCanvasManager.updateTexture()},startPainting:function(){return e._textureCanvasManager.startPainting()},stopPainting:function(){return e._textureCanvasManager.stopPainting()},updatePainting:function(){return e._textureCanvasManager.updatePainting()},metadata:this.state.metadata,setMetadata:function(t){return e.setMetadata(t)},getMouseCoordinates:function(t){return e._textureCanvasManager.getMouseCoordinates(t)},BABYLON:BABYLON}},t.prototype.changeTool=function(e){this._textureCanvasManager.tool=-1!=e?this.state.tools[e]:null,this.setState({activeToolIndex:e})},t.prototype.setMetadata=function(e){var t=o(o({},this.state.metadata),e);this.setState({metadata:t}),this._textureCanvasManager.metadata=t},t.prototype.setPickerOpen=function(e){this.setState({pickerOpen:e})},t.prototype.onPointerDown=function(e){var t;(null===(t=this._pickerRef.current)||void 0===t?void 0:t.contains(e.target))||this.setPickerOpen(!1)},t.prototype.saveTexture=function(){this._textureCanvasManager.saveTexture()},t.prototype.resetTexture=function(){this._textureCanvasManager.reset()},t.prototype.resizeTexture=function(e,t){this._textureCanvasManager.resize({width:e,height:t})},t.prototype.uploadTexture=function(e){this._textureCanvasManager.upload(e)},t.prototype.render=function(){var e,t=this,r=this.state.tools[this.state.activeToolIndex],n="initial";return r&&r.cursor&&(n="url(data:image/png;base64,"+r.cursor+") 10 10, auto"),s.createElement("div",{id:"texture-editor",onPointerDown:this.onPointerDown,style:{cursor:n}},s.createElement(pt,{texture:this.props.texture,saveTexture:this.saveTexture,pixelData:this.state.pixelData,face:this.state.face,setFace:function(e){return t.setState({face:e})},resetTexture:this.resetTexture,resizeTexture:this.resizeTexture,uploadTexture:this.uploadTexture,mipLevel:this.state.mipLevel,setMipLevel:function(e){return t.setState({mipLevel:e})},size:(null===(e=this._textureCanvasManager)||void 0===e?void 0:e.size)||this.props.texture.getSize()}),!this.props.texture.isCube&&s.createElement(st,{tools:this.state.tools,activeToolIndex:this.state.activeToolIndex,addTool:this.loadToolFromURL,changeTool:this.changeTool,metadata:this.state.metadata,setMetadata:this.setMetadata,pickerOpen:this.state.pickerOpen,setPickerOpen:this.setPickerOpen,pickerRef:this._pickerRef,hasAlpha:-1===this.props.texture.textureFormat||this.props.texture.textureFormat===u.Constants.TEXTUREFORMAT_RGBA}),s.createElement(dt,{channels:this.state.channels,setChannels:function(e){t.setState({channels:e})}}),s.createElement(bt,{canvas2D:this._2DCanvas,canvas3D:this._3DCanvas,canvasUI:this._UICanvas,texture:this.props.texture}),s.createElement(yt,{tool:r}),s.createElement(ht,{texture:this.props.texture,mipLevel:this.state.mipLevel}))},t.PREVIEW_UPDATE_DELAY_MS=160,t}(s.Component),Ot=function(e){function t(t){var r=e.call(this,t)||this;r._textureInspectorSize={width:1024,height:490},r.state={isTextureEditorOpen:!1,textureEditing:null};var n=r.props.texture;if(r.textureLineRef=s.createRef(),r.popoutWindowRef=s.createRef(),!n||!n.rootContainer)return r;var a=n;return r._adtInstrumentation=new nt.AdvancedDynamicTextureInstrumentation(a),r._adtInstrumentation.captureRenderTime=!0,r._adtInstrumentation.captureLayoutTime=!0,r.onOpenTextureEditor.bind(r),r.onCloseTextureEditor.bind(r),r.openTextureEditor.bind(r),r}return a(t,e),t.prototype.componentWillUnmount=function(){this._adtInstrumentation&&(this._adtInstrumentation.dispose(),this._adtInstrumentation=null)},t.prototype.updateTexture=function(e){var t=this,r=this.props.texture;u.Tools.ReadFile(e,(function(n){var a=new Blob([n],{type:"octet/stream"}),o=new FileReader;o.readAsDataURL(a),o.onloadend=function(){var n=o.result;if(r.isCube){var a=void 0;e.name.toLowerCase().indexOf(".dds")>0?a=".dds":e.name.toLowerCase().indexOf(".env")>0&&(a=".env"),r.updateURL(n,a,(function(){return t.forceRefresh()}))}else r.updateURL(n,null,(function(){return t.forceRefresh()}))}}),void 0,!0)},t.prototype.openTextureEditor=function(){var e=this;this.state.isTextureEditorOpen?this.onCloseTextureEditor((function(){return e.openTextureEditor()})):this.setState({isTextureEditorOpen:!0,textureEditing:this.props.texture})},t.prototype.onOpenTextureEditor=function(e){},t.prototype.onCloseTextureEditor=function(e){this.setState({isTextureEditorOpen:!1,textureEditing:null},e)},t.prototype.forceRefresh=function(){this.forceUpdate(),this.textureLineRef.current.updatePreview()},t.prototype.render=function(){var e=this,t=this.props.texture,r=[{label:"Nearest",value:u.Texture.NEAREST_NEAREST},{label:"Nearest & linear mip",value:u.Texture.NEAREST_LINEAR},{label:"Linear",value:u.Texture.LINEAR_LINEAR_MIPLINEAR}],n=[{label:"Explicit",value:u.Texture.EXPLICIT_MODE},{label:"Cubic",value:u.Texture.CUBIC_MODE},{label:"Inverse cubic",value:u.Texture.INVCUBIC_MODE},{label:"Equirectangular",value:u.Texture.EQUIRECTANGULAR_MODE},{label:"Fixed equirectangular",value:u.Texture.FIXED_EQUIRECTANGULAR_MODE},{label:"Fixed equirectangular mirrored",value:u.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE},{label:"Planar",value:u.Texture.PLANAR_MODE},{label:"Projection",value:u.Texture.PROJECTION_MODE},{label:"Skybox",value:u.Texture.SKYBOX_MODE},{label:"Spherical",value:u.Texture.SPHERICAL_MODE}],a="",o=t.url,i=o&&"data"!==o.substring(0,4)&&"blob"!==o.substring(0,4)?o:"";if(i)for(var l=i.length-1;l>=0&&"."!==i[l];l--)a=i[l]+a;return s.createElement("div",{className:"pane"},s.createElement(Ee,{globalState:this.props.globalState,title:"PREVIEW"},s.createElement(rt,{ref:this.textureLineRef,texture:t,width:256,height:256,globalState:this.props.globalState}),s.createElement(Qe,{label:"Load texture from file",onClick:function(t){return e.updateTexture(t)},accept:".jpg, .png, .tga, .dds, .env"}),s.createElement(Ye,{label:"Edit",onClick:function(){return e.openTextureEditor()}}),s.createElement(Be,{label:"URL",value:i,lockObject:this.props.lockObject,onChange:function(r){t.updateURL(r),e.forceRefresh()}})),this.state.isTextureEditorOpen&&s.createElement(at,{id:"texture-editor",title:"Texture Inspector",size:this._textureInspectorSize,onOpen:this.onOpenTextureEditor,onClose:function(){return e.onCloseTextureEditor},ref:this.popoutWindowRef},s.createElement(Et,{texture:this.props.texture,url:i,window:this.popoutWindowRef,onUpdate:function(){return e.forceRefresh()}})),s.createElement(We,{globalState:this.props.globalState,target:t,lockObject:this.props.lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Ce,{label:"Width",value:t.getSize().width.toString()}),s.createElement(Ce,{label:"Height",value:t.getSize().height.toString()}),t.isRenderTarget&&s.createElement(Ye,{label:"Scale up",onClick:function(){var r=t.getScene();t.scale(2),setTimeout((function(){e.props.globalState.onSelectionChangedObservable.notifyObservers(r.getTextureByUniqueID(t.uniqueId))}))}}),t.isRenderTarget&&s.createElement(Ye,{label:"Scale down",onClick:function(){var r=t.getScene();t.scale(.5),setTimeout((function(){e.props.globalState.onSelectionChangedObservable.notifyObservers(r.getTextureByUniqueID(t.uniqueId))}))}}),a&&s.createElement(Ce,{label:"File format",value:a}),s.createElement(Ce,{label:"Unique ID",value:t.uniqueId.toString()}),s.createElement(Ce,{label:"Class",value:t.getClassName()}),s.createElement(Ce,{label:"Has alpha",value:t.hasAlpha?"Yes":"No"}),s.createElement(Ce,{label:"Is 3D",value:t.is3D?"Yes":"No"}),s.createElement(Ce,{label:"Is 2D array",value:t.is2DArray?"Yes":"No"}),s.createElement(Ce,{label:"Is cube",value:t.isCube?"Yes":"No"}),s.createElement(Ce,{label:"Is render target",value:t.isRenderTarget?"Yes":"No"}),t instanceof u.Texture&&s.createElement(Ce,{label:"Stored as inverted on Y",value:t.invertY?"Yes":"No"}),s.createElement(Ce,{label:"Has mipmaps",value:t.noMipmap?"No":"Yes"}),s.createElement(Le,{label:"UV set",target:t,propertyName:"coordinatesIndex",minimum:0,maximum:3,step:1,onPropertyChangedObservable:this.props.onPropertyChangedObservable,decimalCount:0}),s.createElement(Re,{label:"Mode",options:n,target:t,propertyName:"coordinatesMode",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onSelect:function(e){return t.coordinatesMode=e}}),s.createElement(Le,{label:"Level",target:t,propertyName:"level",minimum:0,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.updateSamplingMode&&s.createElement(Re,{label:"Sampling",options:r,target:t,noDirectUpdate:!0,propertyName:"samplingMode",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onSelect:function(e){return t.updateSamplingMode(e)}})),t.getScene()&&s.createElement(Ze,{globalState:this.props.globalState,animatable:t,scene:t.getScene(),lockObject:this.props.lockObject}),t.rootContainer&&this._adtInstrumentation&&s.createElement(Ee,{globalState:this.props.globalState,title:"ADVANCED TEXTURE PROPERTIES"},s.createElement(Oe,{label:"Last layout time",value:this._adtInstrumentation.renderTimeCounter.current,units:"ms"}),s.createElement(Oe,{label:"Last render time",value:this._adtInstrumentation.layoutTimeCounter.current,units:"ms"}),s.createElement(Le,{label:"Render scale",minimum:.1,maximum:5,step:.1,target:t,propertyName:"renderScale",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Premultiply alpha",target:t,propertyName:"premulAlpha",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Ideal width",target:t,propertyName:"idealWidth",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Ideal height",target:t,propertyName:"idealHeight",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Use smallest ideal",target:t,propertyName:"useSmallestIdeal",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Render at ideal size",target:t,propertyName:"renderAtIdealSize",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Invalidate Rect optimization",target:t,propertyName:"useInvalidateRectOptimization",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"TRANSFORM"},!t.isCube&&s.createElement("div",null,s.createElement(Me,{lockObject:this.props.lockObject,label:"U offset",target:t,propertyName:"uOffset",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"V offset",target:t,propertyName:"vOffset",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"U scale",target:t,propertyName:"uScale",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"V scale",target:t,propertyName:"vScale",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"U angle",useEuler:this.props.globalState.onlyUseEulers,target:t,propertyName:"uAng",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"V angle",useEuler:this.props.globalState.onlyUseEulers,target:t,propertyName:"vAng",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"W angle",useEuler:this.props.globalState.onlyUseEulers,target:t,propertyName:"wAng",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Clamp U",isSelected:function(){return t.wrapU===u.Texture.CLAMP_ADDRESSMODE},onSelect:function(e){return t.wrapU=e?u.Texture.CLAMP_ADDRESSMODE:u.Texture.WRAP_ADDRESSMODE}}),s.createElement(Pe,{label:"Clamp V",isSelected:function(){return t.wrapV===u.Texture.CLAMP_ADDRESSMODE},onSelect:function(e){return t.wrapV=e?u.Texture.CLAMP_ADDRESSMODE:u.Texture.WRAP_ADDRESSMODE}})),t.isCube&&s.createElement("div",null,s.createElement(Le,{label:"Rotation Y",useEuler:this.props.globalState.onlyUseEulers,minimum:0,maximum:2*Math.PI,step:.1,target:t,propertyName:"rotationY"}))))},t}(s.Component),St=function(e){function t(t){var r=e.call(this,t)||this;return r._localChange=!1,r.state={isExpanded:!1,value:r.props.target[r.props.propertyName].clone()},r}return a(t,e),t.prototype.shouldComponentUpdate=function(e,t){var r=e.target[e.propertyName];return!(r.equals(t.value)&&!this._localChange)&&(t.value=r.clone(),this._localChange=!1,!0)},t.prototype.switchExpandState=function(){this._localChange=!0,this.setState({isExpanded:!this.state.isExpanded})},t.prototype.raiseOnPropertyChanged=function(e){this.props.onChange&&this.props.onChange(this.state.value),this.props.onPropertyChangedObservable&&this.props.onPropertyChangedObservable.notifyObservers({object:this.props.target,property:this.props.propertyName,value:this.state.value,initialValue:e})},t.prototype.updateStateX=function(e){this._localChange=!0;var t=this.state.value.clone();this.props.target[this.props.propertyName].x=e,this.state.value.x=e,this.setState({value:this.state.value}),this.raiseOnPropertyChanged(t)},t.prototype.updateStateY=function(e){this._localChange=!0;var t=this.state.value.clone();this.props.target[this.props.propertyName].y=e,this.state.value.y=e,this.setState({value:this.state.value}),this.raiseOnPropertyChanged(t)},t.prototype.render=function(){var e=this,t=this.state.isExpanded?s.createElement(w,{icon:ae}):s.createElement(w,{icon:le});return s.createElement("div",{className:"vector3Line"},s.createElement("div",{className:"firstLine",title:this.props.label},s.createElement("div",{className:"label"},this.props.label),s.createElement("div",{className:"vector"},"X: "+this.state.value.x.toFixed(2)+", Y: "+this.state.value.y.toFixed(2)),s.createElement("div",{className:"expand hoverIcon",onClick:function(){return e.switchExpandState()},title:"Expand"},t)),this.state.isExpanded&&s.createElement("div",{className:"secondLine"},s.createElement(Ae,{label:"x",step:this.props.step,value:this.state.value.x,onChange:function(t){return e.updateStateX(t)}}),s.createElement(Ae,{label:"y",step:this.props.step,value:this.state.value.y,onChange:function(t){return e.updateStateY(t)}})))},t.defaultProps={step:.001},t}(s.Component),xt=function(e){function t(t){var r=e.call(this,t)||this;return r._onDebugSelectionChangeObservable=new u.Observable,r}return a(t,e),t.prototype.switchAmbientMode=function(e){this.props.material.debugMode=e?21:0},t.prototype.switchMetallicMode=function(e){this.props.material.debugMode=e?62:0},t.prototype.switchRoughnessMode=function(e){this.props.material.debugMode=e?63:0},t.prototype.renderTextures=function(e){var t=this,r=this.props.material;return s.createElement(Ee,{globalState:this.props.globalState,title:"CHANNELS"},s.createElement(qe,{label:"Albedo",texture:r.albedoTexture,propertyName:"albedoTexture",material:r,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:e}),s.createElement(qe,{customDebugAction:function(e){return t.switchMetallicMode(e)},label:"Metallic",texture:r.metallicTexture,propertyName:"metallicTexture",material:r,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:e}),s.createElement(qe,{customDebugAction:function(e){return t.switchRoughnessMode(e)},label:"Roughness",texture:r.metallicTexture,propertyName:"metallicTexture",material:r,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:e}),s.createElement(qe,{label:"Reflection",texture:r.reflectionTexture,propertyName:"reflectionTexture",material:r,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:e}),s.createElement(qe,{label:"Refraction",texture:r.refractionTexture,propertyName:"refractionTexture",material:r,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:e}),s.createElement(qe,{label:"Reflectivity",texture:r.reflectivityTexture,propertyName:"reflectivityTexture",material:r,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:e}),s.createElement(qe,{label:"Micro-surface",texture:r.microSurfaceTexture,propertyName:"microSurfaceTexture",material:r,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:e}),s.createElement(qe,{label:"Bump",texture:r.bumpTexture,propertyName:"bumpTexture",material:r,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:e}),s.createElement(qe,{label:"Emissive",texture:r.emissiveTexture,propertyName:"emissiveTexture",material:r,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:e}),s.createElement(qe,{label:"Opacity",texture:r.opacityTexture,propertyName:"opacityTexture",material:r,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:e}),s.createElement(qe,{customDebugAction:function(e){return t.switchAmbientMode(e)},label:"Ambient",texture:r.ambientTexture,propertyName:"ambientTexture",material:r,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:e}),s.createElement(qe,{label:"Lightmap",texture:r.lightmapTexture,propertyName:"lightmapTexture",material:r,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:e}),s.createElement(qe,{label:"Detailmap",texture:r.detailMap.texture,material:r,onTextureCreated:function(e){return r.detailMap.texture=e},onTextureRemoved:function(){return r.detailMap.texture=null},onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:e}),s.createElement(Pe,{label:"Use lightmap as shadowmap",target:r,propertyName:"useLightmapAsShadowmap",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Use detailmap",target:r.detailMap,propertyName:"isEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t.prototype.render=function(){var e,t,r,n=this,a=this.props.material,o=[{label:"Low",value:u.Constants.TEXTURE_FILTERING_QUALITY_LOW},{label:"Medium",value:u.Constants.TEXTURE_FILTERING_QUALITY_MEDIUM},{label:"High",value:u.Constants.TEXTURE_FILTERING_QUALITY_HIGH}];return a.sheen._useRoughness=null!==(e=a.sheen._useRoughness)&&void 0!==e?e:null!==a.sheen.roughness,a.sheen.roughness=null!==(r=null!==(t=a.sheen.roughness)&&void 0!==t?t:a.sheen._saveRoughness)&&void 0!==r?r:0,a.sheen._useRoughness||(a.sheen._saveRoughness=a.sheen.roughness,a.sheen.roughness=null),s.createElement("div",{className:"pane"},s.createElement(Ke,{globalState:this.props.globalState,lockObject:this.props.lockObject,material:a,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),this.renderTextures(this._onDebugSelectionChangeObservable),s.createElement(Ee,{globalState:this.props.globalState,title:"LIGHTING & COLORS"},s.createElement(Ve,{label:"Albedo",target:a,propertyName:"albedoColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable,isLinear:!0}),s.createElement(Ve,{label:"Reflectivity",target:a,propertyName:"reflectivityColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable,isLinear:!0}),s.createElement(Le,{label:"Micro-surface",target:a,propertyName:"microSurface",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Emissive",target:a,propertyName:"emissiveColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable,isLinear:!0}),s.createElement(Ve,{label:"Ambient",target:a,propertyName:"ambientColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable,isLinear:!0}),s.createElement(Pe,{label:"Use physical light falloff",target:a,propertyName:"usePhysicalLightFalloff",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"METALLIC WORKFLOW"},s.createElement(Le,{label:"Metallic",target:a,propertyName:"metallic",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Roughness",target:a,propertyName:"roughness",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Index of Refraction",target:a,propertyName:"indexOfRefraction",minimum:1,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"F0 Factor",target:a,propertyName:"metallicF0Factor",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Reflectance Color",target:a,propertyName:"metallicReflectanceColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable,isLinear:!0}),s.createElement(qe,{label:"Reflectance Texture",texture:a.metallicReflectanceTexture,onTextureCreated:function(e){return a.metallicReflectanceTexture=e},onTextureRemoved:function(){return a.metallicReflectanceTexture=null},material:a,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:this._onDebugSelectionChangeObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"CLEAR COAT"},s.createElement(Pe,{label:"Enabled",target:a.clearCoat,propertyName:"isEnabled",onValueChanged:function(){return n.forceUpdate()},onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.clearCoat.isEnabled&&s.createElement("div",{className:"fragment"},s.createElement(Le,{label:"Intensity",target:a.clearCoat,propertyName:"intensity",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Roughness",target:a.clearCoat,propertyName:"roughness",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"IOR",target:a.clearCoat,propertyName:"indexOfRefraction",minimum:1,maximum:3,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Remap F0",target:a.clearCoat,propertyName:"remapF0OnInterfaceChange",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(qe,{label:"Clear coat",texture:a.clearCoat.texture,onTextureCreated:function(e){return a.clearCoat.texture=e},onTextureRemoved:function(){return a.clearCoat.texture=null},material:a,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:this._onDebugSelectionChangeObservable}),s.createElement(qe,{label:"Roughness",texture:a.clearCoat.textureRoughness,onTextureCreated:function(e){return a.clearCoat.textureRoughness=e},onTextureRemoved:function(){return a.clearCoat.textureRoughness=null},material:a,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:this._onDebugSelectionChangeObservable}),s.createElement(qe,{label:"Bump",texture:a.clearCoat.bumpTexture,onTextureCreated:function(e){return a.clearCoat.bumpTexture=e},onTextureRemoved:function(){return a.clearCoat.bumpTexture=null},material:a,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:this._onDebugSelectionChangeObservable}),a.clearCoat.bumpTexture&&s.createElement(Le,{label:"Bump strength",target:a.clearCoat.bumpTexture,propertyName:"level",minimum:0,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Use roughness from main texture",target:a.clearCoat,propertyName:"useRoughnessFromMainTexture",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Tint",target:a.clearCoat,propertyName:"isTintEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.clearCoat.isEnabled&&a.clearCoat.isTintEnabled&&s.createElement(Ve,{label:"Tint Color",target:a.clearCoat,propertyName:"tintColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable,isLinear:!0}),a.clearCoat.isEnabled&&a.clearCoat.isTintEnabled&&s.createElement(Le,{label:"At Distance",target:a.clearCoat,propertyName:"tintColorAtDistance",minimum:0,maximum:20,step:.1,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.clearCoat.isEnabled&&a.clearCoat.isTintEnabled&&s.createElement(Le,{label:"Tint Thickness",target:a.clearCoat,propertyName:"tintThickness",minimum:0,maximum:20,step:.1,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.clearCoat.isEnabled&&a.clearCoat.isTintEnabled&&s.createElement(qe,{label:"Tint",texture:a.clearCoat.tintTexture,onTextureCreated:function(e){return a.clearCoat.tintTexture=e},onTextureRemoved:function(){return a.clearCoat.tintTexture=null},material:a,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:this._onDebugSelectionChangeObservable}))),s.createElement(Ee,{globalState:this.props.globalState,title:"ANISOTROPIC"},s.createElement(Pe,{label:"Enabled",target:a.anisotropy,propertyName:"isEnabled",onValueChanged:function(){return n.forceUpdate()},onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.anisotropy.isEnabled&&s.createElement("div",{className:"fragment"},s.createElement(Le,{label:"Intensity",target:a.anisotropy,propertyName:"intensity",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(St,{label:"Direction",target:a.anisotropy,propertyName:"direction",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(qe,{label:"Anisotropic",texture:a.anisotropy.texture,onTextureCreated:function(e){return a.anisotropy.texture=e},onTextureRemoved:function(){return a.anisotropy.texture=null},material:a,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:this._onDebugSelectionChangeObservable}))),s.createElement(Ee,{globalState:this.props.globalState,title:"SHEEN"},s.createElement(Pe,{label:"Enabled",target:a.sheen,propertyName:"isEnabled",onValueChanged:function(){return n.forceUpdate()},onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.sheen.isEnabled&&s.createElement("div",{className:"fragment"},s.createElement(Pe,{label:"Link to Albedo",target:a.sheen,propertyName:"linkSheenWithAlbedo",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Intensity",target:a.sheen,propertyName:"intensity",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Color",target:a.sheen,propertyName:"color",onPropertyChangedObservable:this.props.onPropertyChangedObservable,isLinear:!0}),s.createElement(qe,{label:"Sheen",texture:a.sheen.texture,onTextureCreated:function(e){return a.sheen.texture=e},onTextureRemoved:function(){return a.sheen.texture=null},material:a,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:this._onDebugSelectionChangeObservable}),s.createElement(qe,{label:"Roughness",texture:a.sheen.textureRoughness,onTextureCreated:function(e){return a.sheen.textureRoughness=e},onTextureRemoved:function(){return a.sheen.textureRoughness=null},material:a,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:this._onDebugSelectionChangeObservable}),s.createElement(Pe,{label:"Use roughness",target:a.sheen,propertyName:"_useRoughness"}),a.sheen._useRoughness&&s.createElement(Le,{label:"Roughness",target:a.sheen,propertyName:"roughness",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Use roughness from main texture",target:a.sheen,propertyName:"useRoughnessFromMainTexture",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Albedo scaling",target:a.sheen,propertyName:"albedoScaling",onPropertyChangedObservable:this.props.onPropertyChangedObservable}))),s.createElement(Ee,{globalState:this.props.globalState,title:"SUBSURFACE"},s.createElement(qe,{label:"Thickness",texture:a.subSurface.thicknessTexture,onTextureCreated:function(e){return a.subSurface.thicknessTexture=e},onTextureRemoved:function(){return a.subSurface.thicknessTexture=null},material:a,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:this._onDebugSelectionChangeObservable}),s.createElement(Le,{label:"Min Thickness",target:a.subSurface,propertyName:"minimumThickness",minimum:0,maximum:10,step:.1,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Max Thickness",target:a.subSurface,propertyName:"maximumThickness",minimum:0,maximum:10,step:.1,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Mask From Thickness",target:a.subSurface,propertyName:"useMaskFromThicknessTexture",onValueChanged:function(){return n.forceUpdate()},onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Tint Color",target:a.subSurface,propertyName:"tintColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable,isLinear:!0}),s.createElement(Pe,{label:"Scattering Enabled",target:a.subSurface,propertyName:"isScatteringEnabled",onValueChanged:function(){return n.forceUpdate()},onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.subSurface.isScatteringEnabled&&a.getScene().prePassRenderer&&a.getScene().subSurfaceConfiguration&&s.createElement(Le,{label:"Meters per unit",target:a.getScene().subSurfaceConfiguration,propertyName:"metersPerUnit",minimum:.01,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Refraction Enabled",target:a.subSurface,propertyName:"isRefractionEnabled",onValueChanged:function(){return n.forceUpdate()},onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.subSurface.isRefractionEnabled&&s.createElement("div",{className:"fragment"},s.createElement(Le,{label:"Intensity",target:a.subSurface,propertyName:"refractionIntensity",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(qe,{label:"Refraction",texture:a.subSurface.refractionTexture,onTextureCreated:function(e){return a.subSurface.refractionTexture=e},onTextureRemoved:function(){return a.subSurface.refractionTexture=null},material:a,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:this._onDebugSelectionChangeObservable}),s.createElement(Le,{label:"Index of Refraction",target:a.subSurface,propertyName:"indexOfRefraction",minimum:1,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Tint at Distance",target:a.subSurface,propertyName:"tintColorAtDistance",minimum:0,maximum:10,step:.1,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Link refraction with transparency",target:a.subSurface,propertyName:"linkRefractionWithTransparency",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Use albedo to tint surface transparency",target:a.subSurface,propertyName:"useAlbedoToTintRefraction",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Pe,{label:"Translucency Enabled",target:a.subSurface,propertyName:"isTranslucencyEnabled",onValueChanged:function(){return n.forceUpdate()},onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.subSurface.isTranslucencyEnabled&&s.createElement("div",{className:"fragment"},s.createElement(Le,{label:"Intensity",target:a.subSurface,propertyName:"translucencyIntensity",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Diffusion Distance",target:a.subSurface,propertyName:"diffusionDistance",onPropertyChangedObservable:this.props.onPropertyChangedObservable,isLinear:!0}))),s.createElement(Ee,{globalState:this.props.globalState,title:"LEVELS",closed:!0},s.createElement(Le,{label:"Environment",target:a,propertyName:"environmentIntensity",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Specular",target:a,propertyName:"specularIntensity",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Emissive",target:a,propertyName:"emissiveIntensity",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Direct",target:a,propertyName:"directIntensity",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.bumpTexture&&s.createElement(Le,{label:"Bump strength",target:a.bumpTexture,propertyName:"level",minimum:0,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.ambientTexture&&s.createElement(Le,{label:"Ambient strength",target:a,propertyName:"ambientTextureStrength",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.reflectionTexture&&s.createElement(Le,{label:"Reflection strength",target:a.reflectionTexture,propertyName:"level",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.clearCoat.texture&&s.createElement(Le,{label:"Clear coat",target:a.clearCoat.texture,propertyName:"level",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.clearCoat.bumpTexture&&s.createElement(Le,{label:"Clear coat bump",target:a.clearCoat.bumpTexture,propertyName:"level",minimum:0,maximum:2,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.clearCoat.tintTexture&&!1,a.anisotropy.texture&&s.createElement(Le,{label:"Anisotropic",target:a.anisotropy.texture,propertyName:"level",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.sheen.texture&&s.createElement(Le,{label:"Sheen",target:a.sheen.texture,propertyName:"level",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.subSurface.thicknessTexture&&s.createElement(Le,{label:"Thickness",target:a.subSurface.thicknessTexture,propertyName:"level",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.subSurface.refractionTexture&&s.createElement(Le,{label:"Refraction",target:a.subSurface.refractionTexture,propertyName:"level",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a.detailMap.isEnabled&&s.createElement(s.Fragment,null,s.createElement(Le,{label:"Detailmap diffuse",target:a.detailMap,propertyName:"diffuseBlendLevel",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Detailmap bump",target:a.detailMap,propertyName:"bumpLevel",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Detailmap roughness",target:a.detailMap,propertyName:"roughnessBlendLevel",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}))),s.createElement(Ee,{globalState:this.props.globalState,title:"RENDERING",closed:!0},s.createElement(Pe,{label:"Alpha from albedo",target:a,propertyName:"useAlphaFromAlbedoTexture",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Ambient in grayscale",target:a,propertyName:"useAmbientInGrayScale",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Radiance over alpha",target:a,propertyName:"useRadianceOverAlpha",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Micro-surface from ref. map alpha",target:a,propertyName:"useMicroSurfaceFromReflectivityMapAlpha",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Specular over alpha",target:a,propertyName:"useSpecularOverAlpha",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Specular anti-aliasing",target:a,propertyName:"enableSpecularAntiAliasing",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Realtime Filtering",target:a,propertyName:"realTimeFiltering",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{allowNullValue:!0,label:"Realtime Filtering quality",options:o,target:a,propertyName:"realTimeFilteringQuality",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"NORMAL MAP",closed:!0},s.createElement(Pe,{label:"Invert X axis",target:a,propertyName:"invertNormalMapX",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Invert Y axis",target:a,propertyName:"invertNormalMapY",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"ADVANCED",closed:!0},s.createElement(Pe,{label:"Energy Conservation",target:a.brdf,propertyName:"useEnergyConservation",onValueChanged:function(){return n.forceUpdate()},onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Spherical Harmonics",target:a.brdf,propertyName:"useSphericalHarmonics",onValueChanged:function(){return n.forceUpdate()},onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Radiance occlusion",target:a,propertyName:"useRadianceOcclusion",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Horizon occlusion ",target:a,propertyName:"useHorizonOcclusion",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Unlit",target:a,propertyName:"unlit",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"DEBUG",closed:!0},s.createElement(Re,{label:"Debug mode",options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"UV1",value:6},{label:"UV2",value:7},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Albdeo Map",value:20},{label:"Ambient Map",value:21},{label:"Opacity Map",value:22},{label:"Emissive Map",value:23},{label:"Light Map",value:24},{label:"Metallic Map",value:25},{label:"Reflectivity Map",value:26},{label:"ClearCoat Map",value:27},{label:"ClearCoat Tint Map",value:28},{label:"Sheen Map",value:29},{label:"Anisotropic Map",value:30},{label:"Thickness Map",value:31},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87}],target:a,propertyName:"debugMode"}),s.createElement(Le,{label:"Split position",target:a,propertyName:"debugLimit",minimum:-1,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Output factor",target:a,propertyName:"debugFactor",minimum:0,maximum:5,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),Pt=function(e){function t(t){var r=e.call(this,t)||this;return r.state={isSelected:r.props.isSelected()},r}return a(t,e),t.prototype.componentDidMount=function(){var e=this;this._onSelectionChangedObserver=this.props.onSelectionChangedObservable.add((function(t){e.setState({isSelected:t===e})}))},t.prototype.componentWillUnmount=function(){this._onSelectionChangedObserver&&(this.props.onSelectionChangedObservable.remove(this._onSelectionChangedObserver),this._onSelectionChangedObserver=null)},t.prototype.onChange=function(){this.props.onSelect(),this.props.onSelectionChangedObservable.notifyObservers(this)},t.prototype.render=function(){var e=this;return s.createElement("div",{className:"radioLine"},s.createElement("div",{className:"label",title:this.props.label},this.props.label),s.createElement("div",{className:"radioContainer"},s.createElement("input",{id:this.props.label,className:"radio",type:"radio",checked:this.state.isSelected,onChange:function(){return e.onChange()}}),s.createElement("label",{htmlFor:this.props.label,className:"labelForRadio"})))},t}(s.Component),wt=function(e){function t(t){var r=e.call(this,t)||this;return r.state={mode:r.props.scene.fogMode},r}return a(t,e),t.prototype.render=function(){var e=this,t=this.props.scene,r=[{label:"None",value:u.Scene.FOGMODE_NONE},{label:"Linear",value:u.Scene.FOGMODE_LINEAR},{label:"Exp",value:u.Scene.FOGMODE_EXP},{label:"Exp2",value:u.Scene.FOGMODE_EXP2}];return s.createElement("div",null,s.createElement(Re,{label:"Fog mode",options:r,target:t,propertyName:"fogMode",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onSelect:function(t){return e.setState({mode:t})}}),this.state.mode!==u.Scene.FOGMODE_NONE&&s.createElement(Ve,{label:"Fog color",target:t,propertyName:"fogColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),(this.state.mode===u.Scene.FOGMODE_EXP||this.state.mode===u.Scene.FOGMODE_EXP2)&&s.createElement(Me,{lockObject:this.props.lockObject,label:"Fog density",target:t,propertyName:"fogDensity",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),this.state.mode===u.Scene.FOGMODE_LINEAR&&s.createElement(Me,{lockObject:this.props.lockObject,label:"Fog start",target:t,propertyName:"fogStart",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),this.state.mode===u.Scene.FOGMODE_LINEAR&&s.createElement(Me,{lockObject:this.props.lockObject,label:"Fog end",target:t,propertyName:"fogEnd",onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t}(s.Component),kt=function(e){function t(t){var r=e.call(this,t)||this;return r._renderingModeGroupObservable=new u.Observable,r}return a(t,e),t.prototype.setRenderingModes=function(e,t){var r=this.props.scene;r.forcePointsCloud=e,r.forceWireframe=t},t.prototype.switchIBL=function(){var e=this.props.scene;e.environmentTexture?(this._storedEnvironmentTexture=e.environmentTexture,e.environmentTexture=null):(e.environmentTexture=this._storedEnvironmentTexture,this._storedEnvironmentTexture=null)},t.prototype.updateEnvironmentTexture=function(e){var t=e.name.toLowerCase().indexOf(".dds")>0,r=e.name.toLowerCase().indexOf(".env")>0;if(t||r){var n=this.props.scene;u.Tools.ReadFile(e,(function(e){var r=new Blob([e],{type:"octet/stream"}),a=URL.createObjectURL(r);n.environmentTexture=t?u.CubeTexture.CreateFromPrefilteredData(a,n,".dds"):new u.CubeTexture(a,n,void 0,void 0,void 0,(function(){}),(function(e){e&&console.error(e)}),void 0,void 0,".env")}),void 0,!0)}else console.error("Unable to update environment texture. Please select a dds or env file.")},t.prototype.updateGravity=function(e){this.props.scene.getPhysicsEngine().setGravity(e)},t.prototype.updateTimeStep=function(e){this.props.scene.getPhysicsEngine().setTimeStep(e)},t.prototype.normalizeScene=function(){this.props.scene.meshes.forEach((function(e){e.normalizeToUnitCube(!0),e.computeWorldMatrix(!0)}))},t.prototype.render=function(){var e=this,t=this.props.scene,r=t.getPhysicsEngine(),n=null;r&&(n={gravity:r.gravity,timeStep:r.getTimeStep()});var a=t.imageProcessingConfiguration,o=[{label:"Standard",value:u.ImageProcessingConfiguration.TONEMAPPING_STANDARD},{label:"ACES",value:u.ImageProcessingConfiguration.TONEMAPPING_ACES}],i=[{label:"Multiply",value:u.ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY},{label:"Opaque",value:u.ImageProcessingConfiguration.VIGNETTEMODE_OPAQUE}];return s.createElement("div",{className:"pane"},s.createElement(Ee,{globalState:this.props.globalState,title:"RENDERING MODE"},s.createElement(Pt,{onSelectionChangedObservable:this._renderingModeGroupObservable,label:"Point",isSelected:function(){return t.forcePointsCloud},onSelect:function(){return e.setRenderingModes(!0,!1)}}),s.createElement(Pt,{onSelectionChangedObservable:this._renderingModeGroupObservable,label:"Wireframe",isSelected:function(){return t.forceWireframe},onSelect:function(){return e.setRenderingModes(!1,!0)}}),s.createElement(Pt,{onSelectionChangedObservable:this._renderingModeGroupObservable,label:"Solid",isSelected:function(){return!t.forcePointsCloud&&!t.forceWireframe},onSelect:function(){return e.setRenderingModes(!1,!1)}})),s.createElement(Ee,{globalState:this.props.globalState,title:"ENVIRONMENT"},s.createElement(Ve,{label:"Clear color",target:t,propertyName:"clearColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Clear color enabled",target:t,propertyName:"autoClear",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Ambient color",target:t,propertyName:"ambientColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Environment texture (IBL)",isSelected:function(){return null!=t.environmentTexture},onSelect:function(){return e.switchIBL()}}),t.environmentTexture&&s.createElement(qe,{label:"Env. texture",texture:t.environmentTexture,onSelectionChangedObservable:this.props.onSelectionChangedObservable}),s.createElement(Qe,{label:"Update environment texture",onClick:function(t){return e.updateEnvironmentTexture(t)},accept:".dds, .env"}),s.createElement(Le,{minimum:0,maximum:2,step:.01,label:"IBL Intensity",target:t,propertyName:"environmentIntensity",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(wt,{globalState:this.props.globalState,lockObject:this.props.lockObject,scene:t,onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ze,{globalState:this.props.globalState,animatable:t,scene:t,lockObject:this.props.lockObject}),s.createElement(Ee,{globalState:this.props.globalState,title:"MATERIAL IMAGE PROCESSING"},s.createElement(Le,{minimum:0,maximum:4,step:.1,label:"Contrast",target:a,propertyName:"contrast",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{minimum:0,maximum:4,step:.1,label:"Exposure",target:a,propertyName:"exposure",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Tone mapping",target:a,propertyName:"toneMappingEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Tone mapping type",options:o,target:a,propertyName:"toneMappingType",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onSelect:function(t){return e.setState({mode:t})}}),s.createElement(Pe,{label:"Vignette",target:a,propertyName:"vignetteEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{minimum:0,maximum:4,step:.1,label:"Vignette weight",target:a,propertyName:"vignetteWeight",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{minimum:0,maximum:1,step:.1,label:"Vignette stretch",target:a,propertyName:"vignetteStretch",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{minimum:0,maximum:Math.PI,step:.1,label:"Vignette FOV",target:a,propertyName:"vignetteCameraFov",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{minimum:0,maximum:1,step:.1,label:"Vignette center X",target:a,propertyName:"vignetteCentreX",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{minimum:0,maximum:1,step:.1,label:"Vignette center Y",target:a,propertyName:"vignetteCentreY",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Vignette color",target:a,propertyName:"vignetteColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Vignette blend mode",options:i,target:a,propertyName:"vignetteBlendMode",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onSelect:function(t){return e.setState({mode:t})}})),null!==n&&s.createElement(Ee,{globalState:this.props.globalState,title:"PHYSICS",closed:!0},s.createElement(Me,{lockObject:this.props.lockObject,label:"Time step",target:n,propertyName:"timeStep",onChange:function(t){return e.updateTimeStep(t)},onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Gravity",target:n,propertyName:"gravity",onChange:function(t){return e.updateGravity(t)},onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"COLLISIONS",closed:!0},s.createElement(Ue,{label:"Gravity",target:t,propertyName:"gravity",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"SHADOWS",closed:!0},s.createElement(Ye,{label:"Normalize scene",onClick:function(){return e.normalizeScene()}})))},t}(s.Component),Nt=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this,t=this.props.light;return s.createElement("div",null,s.createElement(We,{globalState:this.props.globalState,target:t,lockObject:this.props.lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Ce,{label:"ID",value:t.id}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Name",target:t,propertyName:"name",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ce,{label:"Unique ID",value:t.uniqueId.toString()}),s.createElement(Ce,{label:"Class",value:t.getClassName()}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Intensity",target:t,propertyName:"intensity",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ye,{label:"Dispose",onClick:function(){t.dispose(),e.props.globalState.onSelectionChangedObservable.notifyObservers(null)}})),s.createElement(Ze,{globalState:this.props.globalState,animatable:t,scene:t.getScene(),lockObject:this.props.lockObject}))},t}(s.Component),Tt=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.light;return s.createElement("div",{className:"pane"},s.createElement(Nt,{globalState:this.props.globalState,lockObject:this.props.lockObject,light:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"SETUP"},s.createElement(Ve,{label:"Diffuse",target:e,propertyName:"diffuse",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Ground",target:e,propertyName:"groundColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Direction",target:e,propertyName:"direction",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),_t=function(e){function t(t){var r=e.call(this,t)||this;return r._internals={generatorType:0,mapSize:1024},r}return a(t,e),t.prototype.createShadowGenerator=function(){var e=this.props.light,t=e.getScene(),r=this._internals,n=0===r.generatorType?new u.ShadowGenerator(r.mapSize,e):new u.CascadedShadowGenerator(r.mapSize,e);t.meshes.forEach((function(e){e.infiniteDistance||(n.addShadowCaster(e),e.isAnInstance||(e.receiveShadows=!0))})),this.forceUpdate()},t.prototype.disposeShadowGenerator=function(){var e;null===(e=this.props.light.getShadowGenerator())||void 0===e||e.dispose(),this.forceUpdate()},t.prototype.render=function(){var e=this,t=this.props.light,r=this._internals,n=t.getShadowGenerator()||null,a=n instanceof u.CascadedShadowGenerator,o=t.getScene().activeCamera,i=[{label:"Shadow Generator",value:0}];t instanceof u.DirectionalLight&&i.push({label:"Cascaded Shadow Generator",value:1});var l;l=n instanceof u.CascadedShadowGenerator?[{label:"None",value:u.ShadowGenerator.FILTER_NONE},{label:"PCF",value:u.ShadowGenerator.FILTER_PCF},{label:"PCSS",value:u.ShadowGenerator.FILTER_PCSS}]:[{label:"None",value:u.ShadowGenerator.FILTER_NONE},{label:"PCF",value:u.ShadowGenerator.FILTER_PCF},{label:"PCSS",value:u.ShadowGenerator.FILTER_PCSS},{label:"Poisson",value:u.ShadowGenerator.FILTER_POISSONSAMPLING},{label:"Exponential",value:u.ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP},{label:"Blurred exponential",value:u.ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP},{label:"Close exponential",value:u.ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP},{label:"Blurred close exponential",value:u.ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}];var p=[{label:"Low",value:u.ShadowGenerator.QUALITY_LOW},{label:"Medium",value:u.ShadowGenerator.QUALITY_MEDIUM},{label:"High",value:u.ShadowGenerator.QUALITY_HIGH}],c=o?o.minZ:0,d=o?o.maxZ:0,h=n?n.filter:0;return s.createElement("div",null,s.createElement(Ee,{globalState:this.props.globalState,title:"SHADOWS"},s.createElement(Pe,{label:"Shadows enabled",target:t,propertyName:"shadowEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),!a&&s.createElement(s.Fragment,null,s.createElement(Me,{lockObject:this.props.lockObject,label:"Shadows near plane",target:t,propertyName:"shadowMinZ",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Shadows far plane",target:t,propertyName:"shadowMaxZ",onPropertyChangedObservable:this.props.onPropertyChangedObservable}))),null==n&&s.createElement(Ee,{globalState:this.props.globalState,title:"SHADOW GENERATOR"},s.createElement(Re,{label:"Type",options:i,target:r,propertyName:"generatorType"}),s.createElement(Re,{label:"Map size",options:[{label:"2048x2048",value:2048},{label:"1024x1024",value:1024},{label:"512x512",value:512},{label:"256x256",value:256}],target:r,propertyName:"mapSize"}),s.createElement(Ye,{label:"Create generator",onClick:function(){return e.createShadowGenerator()}})),null!==n&&s.createElement(Ee,{globalState:this.props.globalState,title:"SHADOW GENERATOR"},s.createElement(Ye,{label:"Dispose generator",onClick:function(){return e.disposeShadowGenerator()}}),a&&s.createElement(s.Fragment,null,s.createElement(Re,{label:"Num cascades",options:[{label:"2",value:2},{label:"3",value:3},{label:"4",value:4}],target:n,propertyName:"numCascades",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Debug mode",target:n,propertyName:"debug",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Stabilize cascades",target:n,propertyName:"stabilizeCascades",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Lambda",minimum:0,maximum:1,step:.01,target:n,propertyName:"lambda",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Cascade blend",minimum:0,maximum:1,step:.01,target:n,propertyName:"cascadeBlendPercentage",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Depth clamp",target:n,propertyName:"depthClamp",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Auto-Calc depth bounds",target:n,propertyName:"autoCalcDepthBounds",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Shadow MaxZ",minimum:c,maximum:d,step:.5,target:n,propertyName:"shadowMaxZ",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Me,{lockObject:this.props.lockObject,digits:4,step:"0.0001",label:"Bias",target:n,propertyName:"bias",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Normal bias",target:n,propertyName:"normalBias",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Darkness",target:n,minimum:0,maximum:1,step:.01,propertyName:"darkness",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Allow transparent shadows",target:n,propertyName:"transparencyShadow",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Filter",options:l,onSelect:function(){e.forceUpdate()},target:n,propertyName:"filter",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),(h===u.ShadowGenerator.FILTER_PCF||h===u.ShadowGenerator.FILTER_PCSS)&&s.createElement(Re,{label:"Filtering quality",options:p,onSelect:function(){e.forceUpdate()},target:n,propertyName:"filteringQuality",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),h===u.ShadowGenerator.FILTER_PCSS&&s.createElement(Le,{label:"Penumbra ratio",minimum:0,maximum:.5,step:.001,target:n,propertyName:"contactHardeningLightSizeUVRatio",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),!a&&(h===u.ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP||h===u.ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&s.createElement(Pe,{label:"Use kernel blur",target:n,propertyName:"useKernelBlur",onValueChanged:function(){return e.forceUpdate()},onPropertyChangedObservable:this.props.onPropertyChangedObservable}),n instanceof u.ShadowGenerator&&(h===u.ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP||h===u.ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&!n.useKernelBlur&&s.createElement(Le,{label:"Blur box offset",target:n,propertyName:"blurBoxOffset",minimum:1,maximum:64,step:1,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),n instanceof u.ShadowGenerator&&(h===u.ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP||h===u.ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&n.useKernelBlur&&s.createElement(Le,{label:"Blur kernel",target:n,propertyName:"blurKernel",minimum:1,maximum:64,step:1,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),n instanceof u.ShadowGenerator&&(h===u.ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP||h===u.ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP)&&s.createElement(Me,{lockObject:this.props.lockObject,label:"Depth scale",target:n,propertyName:"depthScale",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),n instanceof u.ShadowGenerator&&(h===u.ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP||h===u.ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP)&&s.createElement(Le,{label:"Blur scale",target:n,propertyName:"blurScale",minimum:1,maximum:4,step:1,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),a&&h===u.ShadowGenerator.FILTER_PCSS&&s.createElement(Le,{label:"Penumbra darkness",minimum:0,maximum:1,step:.01,target:n,propertyName:"penumbraDarkness",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),Mt=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.light;return s.createElement("div",{className:"pane"},s.createElement(Nt,{globalState:this.props.globalState,lockObject:this.props.lockObject,light:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"SETUP"},s.createElement(Ve,{label:"Diffuse",target:e,propertyName:"diffuse",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Specular",target:e,propertyName:"specular",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Position",target:e,propertyName:"position",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(_t,{globalState:this.props.globalState,lockObject:this.props.lockObject,light:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t}(s.Component),Lt=function(e){function t(t){var r=e.call(this,t)||this;r._localChange=!1,r._propertyChange=!0;var n=r.props.target[r.props.propertyName];return r.state={value:n?r.props.isInteger?n.toFixed(0):n.toFixed(r.props.digits||3):"0"},r._store=n,r}return a(t,e),t.prototype.componentWillUnmount=function(){this.unlock()},t.prototype.shouldComponentUpdate=function(e,t){if(this._localChange)return this._localChange=!1,!0;var r=e.target[e.propertyName],n=r?this.props.isInteger?r.toFixed(0):r.toFixed(this.props.digits||3):"0";return n!==t.value&&(t.value=n,!0)},t.prototype.raiseOnPropertyChanged=function(e,t){var r;this.props.onChange&&this.props.onChange(e),this.props.onPropertyChangedObservable&&this.props.onPropertyChangedObservable.notifyObservers({object:null!==(r=this.props.replaySourceReplacement)&&void 0!==r?r:this.props.target,property:this.props.propertyName,value:e,initialValue:t})},t.prototype.convertToHexString=function(e){for(;e.length<10;)e+="0";return e},t.prototype.updateValue=function(e,t){"0x"!=e.substr(0,2)&&(e="0"!=e.substr(0,1)?"0x"+e:"0x"+e.substr(1));var r=e.substr(2);if(!(""!=r&&0==/^[0-9A-Fa-f]+$/g.test(r)||e.length>10)){var n,a=this.convertToHexString(e);n=parseInt(a),isNaN(n)||void 0===this.props.min||n<this.props.min&&(e=(n=this.props.min).toString()),this._localChange=!0,isNaN(n)||(this.setState({value:e}),t?(this._propertyChange=!0,this.props.target[this.props.propertyName]=n,this.raiseOnPropertyChanged(n,this._store)):this._propertyChange=!1,this._store=n)}},t.prototype.lock=function(){this.props.lockObject&&(this.props.lockObject.lock=!0)},t.prototype.unlock=function(){this.props.lockObject&&(this.props.lockObject.lock=!1)},t.prototype.render=function(){var e,t=this;if(this._propertyChange){e=parseInt(this.state.value).toString(16);for(var r="",n=0;n<8-e.length;n++)r+="0";e="0x"+e.toUpperCase()+r}else e=this.state.value;return s.createElement("div",null,!this.props.useEuler&&s.createElement("div",{className:this.props.additionalClass?this.props.additionalClass+" floatLine":"floatLine"},s.createElement("div",{className:"label",title:this.props.label},this.props.label),s.createElement("div",{className:"value"},s.createElement("input",{type:"string",className:"hex-input",value:e,onBlur:function(){return t.unlock()},onFocus:function(){return t.lock()},onChange:function(e){return t.updateValue(e.target.value,!1)},onKeyDown:function(e){13===e.keyCode&&t.updateValue(t.state.value,!0)}}))))},t}(s.Component),Dt=function(e){function t(t){var r=e.call(this,t)||this;return r.state={mode:r.props.camera.mode},r}return a(t,e),t.prototype.render=function(){var e=this,t=this.props.camera,r=[{label:"Perspective",value:u.Camera.PERSPECTIVE_CAMERA},{label:"Orthographic",value:u.Camera.ORTHOGRAPHIC_CAMERA}];return s.createElement("div",null,s.createElement(We,{globalState:this.props.globalState,target:t,lockObject:this.props.lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Ce,{label:"ID",value:t.id}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Name",target:t,propertyName:"name",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ce,{label:"Unique ID",value:t.uniqueId.toString()}),s.createElement(Ce,{label:"Class",value:t.getClassName()}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Near plane",target:t,propertyName:"minZ",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Far plane",target:t,propertyName:"maxZ",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Inertia",target:t,propertyName:"inertia",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Lt,{isInteger:!0,lockObject:this.props.lockObject,label:"Layer mask",target:t,propertyName:"layerMask",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Mode",options:r,target:t,propertyName:"mode",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onSelect:function(t){return e.setState({mode:t})}}),t.mode===u.Camera.PERSPECTIVE_CAMERA&&s.createElement(Le,{label:"Field of view",target:t,useEuler:this.props.globalState.onlyUseEulers,propertyName:"fov",minimum:.1,maximum:Math.PI,step:.1,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.mode===u.Camera.ORTHOGRAPHIC_CAMERA&&s.createElement(Me,{lockObject:this.props.lockObject,label:"Left",target:t,propertyName:"orthoLeft",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.mode===u.Camera.ORTHOGRAPHIC_CAMERA&&s.createElement(Me,{lockObject:this.props.lockObject,label:"Top",target:t,propertyName:"orthoTop",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.mode===u.Camera.ORTHOGRAPHIC_CAMERA&&s.createElement(Me,{lockObject:this.props.lockObject,label:"Right",target:t,propertyName:"orthoRight",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.mode===u.Camera.ORTHOGRAPHIC_CAMERA&&s.createElement(Me,{lockObject:this.props.lockObject,label:"Bottom",target:t,propertyName:"orthoBottom",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ye,{label:"Dispose",onClick:function(){t.dispose(),e.props.globalState.onSelectionChangedObservable.notifyObservers(null)}})),s.createElement(Ze,{globalState:this.props.globalState,animatable:t,scene:t.getScene(),lockObject:this.props.lockObject}))},t}(s.Component),Rt=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.camera;return s.createElement("div",{className:"pane"},s.createElement(Dt,{globalState:this.props.globalState,lockObject:this.props.lockObject,camera:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"TRANSFORMS"},s.createElement(Ue,{label:"Target",target:e,propertyName:"target",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Position",target:e,propertyName:"position",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Rotation",noSlider:!0,useEuler:this.props.globalState.onlyUseEulers,target:e,propertyName:"rotation",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"CONTROLS",closed:!0},s.createElement(Me,{lockObject:this.props.lockObject,label:"Angular sensitivity",target:e,propertyName:"angularSensibility",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Speed",target:e,propertyName:"speed",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"COLLISIONS",closed:!0},s.createElement(Pe,{label:"Check collisions",target:e,propertyName:"checkCollisions",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Apply gravity",target:e,propertyName:"applyGravity",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Ellipsoid",target:e,propertyName:"ellipsoid",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Ellipsoid offset",target:e,propertyName:"ellipsoidOffset",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),At=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.camera;return s.createElement("div",{className:"pane"},s.createElement(Dt,{globalState:this.props.globalState,lockObject:this.props.lockObject,camera:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"TRANSFORMS"},s.createElement(Ue,{label:"Target",target:e,propertyName:"target",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Alpha",useEuler:this.props.globalState.onlyUseEulers,target:e,propertyName:"alpha",minimum:e.lowerAlphaLimit||0,maximum:e.upperAlphaLimit||2*Math.PI,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Beta",useEuler:this.props.globalState.onlyUseEulers,target:e,propertyName:"beta",minimum:e.lowerAlphaLimit||0,maximum:e.upperBetaLimit||2*Math.PI,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Radius",target:e,propertyName:"radius",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"CONTROLS",closed:!0},s.createElement(Me,{lockObject:this.props.lockObject,label:"Angular sensitivity X",target:e,propertyName:"angularSensibilityX",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Angular sensitivity Y",target:e,propertyName:"angularSensibilityY",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Panning sensitivity",target:e,propertyName:"panningSensibility",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Pinch delta percentage",target:e,propertyName:"pinchDeltaPercentage",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Wheel delta percentage",target:e,propertyName:"wheelDeltaPercentage",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Speed",target:e,propertyName:"speed",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"COLLISIONS",closed:!0},s.createElement(Pe,{label:"Check collisions",target:e,propertyName:"checkCollisions",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Collision radius",target:e,propertyName:"collisionRadius",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"LIMITS",closed:!0},s.createElement(Me,{lockObject:this.props.lockObject,label:"Lower alpha limit",target:e,propertyName:"lowerAlphaLimit",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Upper alpha limit",target:e,propertyName:"upperAlphaLimit",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Lower beta limit",target:e,propertyName:"lowerBetaLimit",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Upper beta limit",target:e,propertyName:"upperBetaLimit",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Lower radius limit",target:e,propertyName:"lowerRadiusLimit",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Upper radius limit",target:e,propertyName:"upperRadiusLimit",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"BEHAVIORS",closed:!0},s.createElement(Pe,{label:"Auto rotation",target:e,propertyName:"useAutoRotationBehavior",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Bouncing",target:e,propertyName:"useBouncingBehavior",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Framing",target:e,propertyName:"useFramingBehavior",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),It=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype._getVariantsExtension=function(){var e;return null===(e=this.props.globalState)||void 0===e?void 0:e.glTFLoaderExtensions.KHR_materials_variants},t.prototype.render=function(){var e=this,t=this._getVariantsExtension();if(!t)return null;var r=t.getAvailableVariants(this.props.host);if(!r||0===r.length)return null;var n=r.sort().map((function(e,t){return{label:e,value:t+1}}));return n.splice(0,0,{label:"Original",value:0}),s.createElement("div",null,s.createElement(Ee,{globalState:this.props.globalState,title:"VARIANTS"},s.createElement(Re,{label:"Active variant",options:n,noDirectUpdate:!0,target:this.props.host,propertyName:"",onSelect:function(n){0===n?t.reset(e.props.host):t.selectVariant(e.props.host,r[n-1]),e.forceUpdate()},extractValue:function(){var n=t.getLastSelectedVariant(e.props.host)||0,a=0;return n&&"[object String]"===Object.prototype.toString.call(n)&&(a=r.indexOf(n))>-1&&(a+=1),a}})))},t}(s.Component),jt=function(e){function t(t){var r=e.call(this,t)||this,n=r.props.mesh;return r.state={displayNormals:!1,displayVertexColors:!1,displayBoneWeights:!(!n.material||"BoneWeightShader"!==n.material.getClassName()),displayBoneIndex:0,displaySkeletonMap:!1},r}return a(t,e),t.prototype.renderWireframeOver=function(){var e=this.props.mesh,t=e.getScene();if(e.reservedDataStore&&e.reservedDataStore.wireframeOver)return e.reservedDataStore.wireframeOver.dispose(!1,!0),e.reservedDataStore.wireframeOver=null,void this.forceUpdate();var r=e.clone();r.reservedDataStore={hidden:!0},r.parent=e,r.position=u.Vector3.Zero(),r.scaling=new u.Vector3(1,1,1),r.rotation=u.Vector3.Zero(),r.rotationQuaternion=null;var n=new u.StandardMaterial("wireframeOver",t);n.reservedDataStore={hidden:!0},r.material=n,n.zOffset=1,n.disableLighting=!0,n.backFaceCulling=!1,n.emissiveColor=u.Color3.White(),n.wireframe=!0,e.reservedDataStore||(e.reservedDataStore={}),e.reservedDataStore.wireframeOver=r,this.forceUpdate()},t.prototype.renderNormalVectors=function(){var e=this.props.mesh,t=e.getScene();if(e.reservedDataStore&&e.reservedDataStore.normalLines)return e.reservedDataStore.normalLines.dispose(),e.reservedDataStore.normalLines=null,void this.forceUpdate();for(var r=e.getVerticesData(u.VertexBuffer.NormalKind),n=e.getVerticesData(u.VertexBuffer.PositionKind),a=u.Color3.White(),o=e.getBoundingInfo(),i=.05*o.maximum.subtractToRef(o.minimum,u.TmpVectors.Vector3[0]).length(),l=[],s=0;s<r.length;s+=3){var p=u.Vector3.FromArray(n,s),c=p.add(u.Vector3.FromArray(r,s).scaleInPlace(i));l.push([p,c])}var d=u.LinesBuilder.CreateLineSystem("normalLines",{lines:l},t);d.color=a,d.parent=e,d.reservedDataStore={hidden:!0},e.reservedDataStore||(e.reservedDataStore={}),e.reservedDataStore.normalLines=d,this.forceUpdate()},t.prototype.displayNormals=function(){var e=this,t=this.props.mesh,r=t.getScene();if(t.material&&"NormalMaterial"===t.material.getClassName())t.material.dispose(),t.material=t.reservedDataStore.originalMaterial,t.reservedDataStore.originalMaterial=null,this.setState({displayNormals:!1});else{if(!BABYLON.NormalMaterial)return this.setState({displayNormals:!0}),void u.Tools.LoadScript("https://preview.babylonjs.com/materialsLibrary/babylonjs.materials.js",(function(){e.displayNormals()}));t.reservedDataStore||(t.reservedDataStore={}),t.reservedDataStore.originalMaterial||(t.reservedDataStore.originalMaterial=t.material);var n=new BABYLON.NormalMaterial("normalMaterial",r);n.disableLighting=!0,t.material&&(n.sideOrientation=t.material.sideOrientation),n.reservedDataStore={hidden:!0},t.material=n,this.setState({displayNormals:!0})}},t.prototype.displayVertexColors=function(){var e=this.props.mesh,t=e.getScene();if(e.material&&e.material.reservedDataStore&&e.material.reservedDataStore.isVertexColorMaterial)e.material.dispose(),e.material=e.reservedDataStore.originalMaterial,e.reservedDataStore.originalMaterial=null,this.setState({displayVertexColors:!1});else{e.reservedDataStore||(e.reservedDataStore={}),e.reservedDataStore.originalMaterial||(e.reservedDataStore.originalMaterial=e.material);var r=new u.StandardMaterial("vertex colors",t);r.disableLighting=!0,r.emissiveColor=u.Color3.White(),e.material&&(r.sideOrientation=e.material.sideOrientation),r.reservedDataStore={hidden:!0,isVertexColorMaterial:!0},e.useVertexColors=!0,e.material=r,this.setState({displayVertexColors:!0})}},t.prototype.displayBoneWeights=function(){var e=this.props.mesh,t=e.getScene();if(e.material&&"BoneWeightShader"===e.material.getClassName())e.material.dispose(),e.material=e.reservedDataStore.originalMaterial,e.reservedDataStore.originalMaterial=null,this.setState({displayBoneWeights:!1});else if(e.reservedDataStore||(e.reservedDataStore={}),e.reservedDataStore.originalMaterial||(e.reservedDataStore.originalMaterial=e.material),e.reservedDataStore.displayBoneIndex||(e.reservedDataStore.displayBoneIndex=this.state.displayBoneIndex),e.skeleton){var r=u.SkeletonViewer.CreateBoneWeightShader({skeleton:e.skeleton},t);r.reservedDataStore={hidden:!0},e.material=r,this.setState({displayBoneWeights:!0})}},t.prototype.displaySkeletonMap=function(){var e=this.props.mesh,t=e.getScene();if(e.material&&"SkeletonMapShader"===e.material.getClassName())e.material.dispose(),e.material=e.reservedDataStore.originalMaterial,e.reservedDataStore.originalMaterial=null,this.setState({displaySkeletonMap:!1});else if(e.reservedDataStore||(e.reservedDataStore={}),e.reservedDataStore.originalMaterial||(e.reservedDataStore.originalMaterial=e.material),e.skeleton){var r=u.SkeletonViewer.CreateSkeletonMapShader({skeleton:e.skeleton},t);r.reservedDataStore={hidden:!0},e.material=r,this.setState({displaySkeletonMap:!0})}},t.prototype.onBoneDisplayIndexChange=function(e){var t=this.props.mesh;t.reservedDataStore.displayBoneIndex=e,this.setState({displayBoneIndex:e}),t.material&&"BoneWeightShader"===t.material.getClassName()&&t.material.setFloat("targetBoneIndex",e)},t.prototype.onMaterialLink=function(){if(this.props.onSelectionChangedObservable){var e=this.props.mesh;this.props.onSelectionChangedObservable.notifyObservers(e.material)}},t.prototype.onSourceMeshLink=function(){if(this.props.onSelectionChangedObservable){var e=this.props.mesh;this.props.onSelectionChangedObservable.notifyObservers(e.sourceMesh)}},t.prototype.onSkeletonLink=function(){if(this.props.onSelectionChangedObservable){var e=this.props.mesh;this.props.onSelectionChangedObservable.notifyObservers(e.skeleton)}},t.prototype.convertPhysicsTypeToString=function(){switch(this.props.mesh.physicsImpostor.type){case u.PhysicsImpostor.NoImpostor:return"No impostor";case u.PhysicsImpostor.SphereImpostor:return"Sphere";case u.PhysicsImpostor.BoxImpostor:return"Box";case u.PhysicsImpostor.PlaneImpostor:return"Plane";case u.PhysicsImpostor.MeshImpostor:return"Mesh";case u.PhysicsImpostor.CylinderImpostor:return"Cylinder";case u.PhysicsImpostor.ParticleImpostor:return"Particle";case u.PhysicsImpostor.HeightmapImpostor:return"Heightmap";case u.PhysicsImpostor.ConvexHullImpostor:return"Convex hull";case u.PhysicsImpostor.RopeImpostor:return"Rope";case u.PhysicsImpostor.SoftbodyImpostor:return"Soft body"}return"Unknown"},t.prototype.render=function(){var e,t=this,r=this.props.mesh,n=r.getScene(),a=null!=r.material&&"NormalMaterial"===r.material.getClassName(),o=!(null==r.material||!r.material.reservedDataStore||!r.material.reservedDataStore.isVertexColorMaterial),i=!(!r.reservedDataStore||!r.reservedDataStore.normalLines),l=!(!r.reservedDataStore||!r.reservedDataStore.wireframeOver),p=null!=r.material&&"BoneWeightShader"===r.material.getClassName(),c=null!=r.material&&"SkeletonMapShader"===r.material.getClassName(),d=[];if(r.morphTargetManager)for(var h=0;h<r.morphTargetManager.numTargets;h++)d.push(r.morphTargetManager.getTarget(h));var b=[{label:"Accurate",value:u.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE},{label:"Conservative",value:u.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE}],m=[{label:"None",value:u.AbstractMesh.OCCLUSION_TYPE_NONE},{label:"Optimistic",value:u.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC},{label:"Strict",value:u.AbstractMesh.OCCLUSION_TYPE_STRICT}],g=n.materials.slice(0).sort((function(e,t){return(e.name||"no name").localeCompare(t.name||"no name")})),f=g.map((function(e,t){return{label:e.name||"no name",value:t}}));f.splice(0,0,{label:"None (Default Fallback)",value:-1});var v=r.skeleton?r.skeleton.bones.filter((function(e){return e.getIndex()>=0})).sort((function(e,t){return e.getIndex()-t.getIndex()})).map((function(e,t){return{label:e.name,value:e.getIndex()}})):[];return s.createElement("div",{className:"pane"},s.createElement(We,{globalState:this.props.globalState,target:r,lockObject:this.props.lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Ce,{label:"ID",value:r.id}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Name",target:r,propertyName:"name",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ce,{label:"Unique ID",value:r.uniqueId.toString()}),s.createElement(Ce,{label:"Class",value:r.getClassName()}),s.createElement(Ce,{label:"Vertices",value:r.getTotalVertices().toString()}),s.createElement(Ce,{label:"Faces",value:(r.getTotalIndices()/3).toFixed(0)}),s.createElement(Ce,{label:"Sub-meshes",value:r.subMeshes?r.subMeshes.length.toString():"0"}),r.parent&&s.createElement(Ce,{label:"Parent",value:r.parent.name,onLink:function(){return t.props.globalState.onSelectionChangedObservable.notifyObservers(r.parent)}}),r.skeleton&&s.createElement(Ce,{label:"Skeleton",value:r.skeleton.name,onLink:function(){return t.onSkeletonLink()}}),s.createElement(Pe,{label:"Is enabled",isSelected:function(){return r.isEnabled()},onSelect:function(e){return r.setEnabled(e)}}),s.createElement(Pe,{label:"Is pickable",target:r,propertyName:"isPickable",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),r.material&&(!r.material.reservedDataStore||!r.material.reservedDataStore.hidden)&&s.createElement(Ce,{label:"Link to material",value:r.material.name,onLink:function(){return t.onMaterialLink()}}),!r.isAnInstance&&s.createElement(Re,{label:"Active material",options:f,target:r,propertyName:"material",noDirectUpdate:!0,onSelect:function(e){r.material=e<0?null:g[e],t.forceUpdate()},extractValue:function(){return r.material?g.indexOf(r.material):-1},onPropertyChangedObservable:this.props.onPropertyChangedObservable}),r.isAnInstance&&s.createElement(Ce,{label:"Source",value:r.sourceMesh.name,onLink:function(){return t.onSourceMeshLink()}}),s.createElement(Ye,{label:"Dispose",onClick:function(){r.dispose(),t.props.globalState.onSelectionChangedObservable.notifyObservers(null)}})),s.createElement(It,{host:r,lockObject:this.props.lockObject,globalState:this.props.globalState}),s.createElement(Ee,{globalState:this.props.globalState,title:"TRANSFORMS"},s.createElement(Ue,{label:"Position",target:r,propertyName:"position",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),!r.rotationQuaternion&&s.createElement(Ue,{label:"Rotation",useEuler:this.props.globalState.onlyUseEulers,target:r,propertyName:"rotation",step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),r.rotationQuaternion&&s.createElement(He,{label:"Rotation",useEuler:this.props.globalState.onlyUseEulers,target:r,propertyName:"rotationQuaternion",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Scaling",target:r,propertyName:"scaling",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"DISPLAY",closed:!0},!r.isAnInstance&&s.createElement(Le,{label:"Visibility",target:r,propertyName:"visibility",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Alpha index",target:r,propertyName:"alphaIndex",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Receive shadows",target:r,propertyName:"receiveShadows",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),r.isVerticesDataPresent(u.VertexBuffer.ColorKind)&&s.createElement(Pe,{label:"Use vertex colors",target:r,propertyName:"useVertexColors",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),r.isVerticesDataPresent(u.VertexBuffer.ColorKind)&&s.createElement(Pe,{label:"Has vertex alpha",target:r,propertyName:"hasVertexAlpha",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),n.fogMode!==u.Scene.FOGMODE_NONE&&s.createElement(Pe,{label:"Apply fog",target:r,propertyName:"applyFog",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),!r.parent&&s.createElement(Pe,{label:"Infinite distance",target:r,propertyName:"infiniteDistance",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Rendering group ID",decimalCount:0,target:r,propertyName:"renderingGroupId",minimum:u.RenderingManager.MIN_RENDERINGGROUPS,maximum:u.RenderingManager.MAX_RENDERINGGROUPS-1,step:1,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Lt,{isInteger:!0,lockObject:this.props.lockObject,label:"Layer mask",target:r,propertyName:"layerMask",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),null!=r.morphTargetManager&&s.createElement(Ee,{globalState:this.props.globalState,title:"MORPH TARGETS",closed:!0},d.map((function(e,r){return s.createElement(Le,{key:r,label:e.name,target:e,propertyName:"influence",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:t.props.onPropertyChangedObservable})}))),s.createElement(Ze,{globalState:this.props.globalState,animatable:r,scene:r.getScene(),lockObject:this.props.lockObject}),s.createElement(Ee,{globalState:this.props.globalState,title:"ADVANCED",closed:!0},r.useBones&&s.createElement(Pe,{label:"Compute bones using shaders",target:r,propertyName:"computeBonesUsingShaders",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Collisions",target:r,propertyName:"checkCollisions",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ce,{label:"Geometry ID",value:null===(e=r.geometry)||void 0===e?void 0:e.uniqueId.toString()}),s.createElement(Ce,{label:"Has normals",value:r.isVerticesDataPresent(u.VertexBuffer.NormalKind)?"Yes":"No"}),s.createElement(Ce,{label:"Has vertex colors",value:r.isVerticesDataPresent(u.VertexBuffer.ColorKind)?"Yes":"No"}),s.createElement(Ce,{label:"Has UV set 0",value:r.isVerticesDataPresent(u.VertexBuffer.UVKind)?"Yes":"No"}),s.createElement(Ce,{label:"Has UV set 1",value:r.isVerticesDataPresent(u.VertexBuffer.UV2Kind)?"Yes":"No"}),s.createElement(Ce,{label:"Has UV set 2",value:r.isVerticesDataPresent(u.VertexBuffer.UV3Kind)?"Yes":"No"}),s.createElement(Ce,{label:"Has UV set 3",value:r.isVerticesDataPresent(u.VertexBuffer.UV4Kind)?"Yes":"No"}),s.createElement(Ce,{label:"Has tangents",value:r.isVerticesDataPresent(u.VertexBuffer.TangentKind)?"Yes":"No"}),s.createElement(Ce,{label:"Has matrix weights",value:r.isVerticesDataPresent(u.VertexBuffer.MatricesWeightsKind)?"Yes":"No"}),s.createElement(Ce,{label:"Has matrix indices",value:r.isVerticesDataPresent(u.VertexBuffer.MatricesIndicesKind)?"Yes":"No"})),null!=r.physicsImpostor&&s.createElement(Ee,{globalState:this.props.globalState,title:"PHYSICS",closed:!0},s.createElement(Me,{lockObject:this.props.lockObject,label:"Mass",target:r.physicsImpostor,propertyName:"mass",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Friction",target:r.physicsImpostor,propertyName:"friction",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Restitution",target:r.physicsImpostor,propertyName:"restitution",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ce,{label:"Type",value:this.convertPhysicsTypeToString()})),s.createElement(Ee,{globalState:this.props.globalState,title:"OCCLUSIONS",closed:!0},s.createElement(Re,{label:"Type",options:m,target:r,propertyName:"occlusionType",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Retry count",minimum:-1,maximum:10,decimalCount:0,step:1,target:r,propertyName:"occlusionRetryCount",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Algorithm",options:b,target:r,propertyName:"occlusionQueryAlgorithmType",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"EDGE RENDERING",closed:!0},s.createElement(Pe,{label:"Enable",target:r,isSelected:function(){return null!=r.edgesRenderer},onSelect:function(e){e?r.enableEdgesRendering():r.disableEdgesRendering()}}),s.createElement(Le,{label:"Edge width",minimum:0,maximum:10,step:.1,target:r,propertyName:"edgesWidth",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Edge color",target:r,propertyName:"edgesColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),!r.isAnInstance&&s.createElement(Ee,{globalState:this.props.globalState,title:"OUTLINE & OVERLAY",closed:!0},s.createElement(Pe,{label:"Render overlay",target:r,propertyName:"renderOverlay",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Overlay color",target:r,propertyName:"overlayColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Render outline",target:r,propertyName:"renderOutline",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Outline color",target:r,propertyName:"outlineColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"DEBUG",closed:!0},!r.isAnInstance&&s.createElement(Pe,{label:"Display normals",isSelected:function(){return a},onSelect:function(){return t.displayNormals()}}),!r.isAnInstance&&s.createElement(Pe,{label:"Display vertex colors",isSelected:function(){return o},onSelect:function(){return t.displayVertexColors()}}),r.isVerticesDataPresent(u.VertexBuffer.NormalKind)&&s.createElement(Pe,{label:"Render vertex normals",isSelected:function(){return i},onSelect:function(){return t.renderNormalVectors()}}),!r.isAnInstance&&s.createElement(Pe,{label:"Render wireframe over mesh",isSelected:function(){return l},onSelect:function(){return t.renderWireframeOver()}}),!r.isAnInstance&&r.skeleton&&s.createElement(Pe,{label:"Display BoneWeights",isSelected:function(){return p},onSelect:function(){return t.displayBoneWeights()}}),!r.isAnInstance&&this.state.displayBoneWeights&&r.skeleton&&s.createElement(Re,{label:"Target Bone Name",options:v,target:r.reservedDataStore,propertyName:"displayBoneIndex",noDirectUpdate:!0,onSelect:function(e){t.onBoneDisplayIndexChange(e),t.forceUpdate()}}),!r.isAnInstance&&this.state.displayBoneWeights&&r.skeleton&&s.createElement(Le,{label:"Target Bone",decimalCount:0,target:r.reservedDataStore,propertyName:"displayBoneIndex",minimum:0,maximum:v.length-1||0,step:1,onChange:function(e){t.onBoneDisplayIndexChange(e),t.forceUpdate()}}),!r.isAnInstance&&r.skeleton&&s.createElement(Pe,{label:"Display SkeletonMap",isSelected:function(){return c},onSelect:function(){return t.displaySkeletonMap()}})))},t}(s.Component),zt=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this,t=this.props.transformNode;return s.createElement("div",{className:"pane"},s.createElement(We,{globalState:this.props.globalState,target:t,lockObject:this.props.lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Ce,{label:"ID",value:t.id}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Name",target:t,propertyName:"name",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ce,{label:"Unique ID",value:t.uniqueId.toString()}),s.createElement(Ce,{label:"Class",value:t.getClassName()}),s.createElement(Pe,{label:"IsEnabled",isSelected:function(){return t.isEnabled()},onSelect:function(e){return t.setEnabled(e)}}),t.parent&&s.createElement(Ce,{label:"Parent",value:t.parent.name,onLink:function(){return e.props.globalState.onSelectionChangedObservable.notifyObservers(t.parent)}}),s.createElement(Ye,{label:"Dispose",onClick:function(){t.dispose(),e.props.globalState.onSelectionChangedObservable.notifyObservers(null)}})),s.createElement(It,{host:t,lockObject:this.props.lockObject,globalState:this.props.globalState}),s.createElement(Ee,{globalState:this.props.globalState,title:"TRANSFORMATIONS"},s.createElement(Ue,{label:"Position",target:t,propertyName:"position",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),!t.rotationQuaternion&&s.createElement(Ue,{label:"Rotation",useEuler:this.props.globalState.onlyUseEulers,target:t,propertyName:"rotation",step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.rotationQuaternion&&s.createElement(He,{label:"Rotation",useEuler:this.props.globalState.onlyUseEulers,target:t,propertyName:"rotationQuaternion",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Scaling",target:t,propertyName:"scaling",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ze,{globalState:this.props.globalState,animatable:t,scene:t.getScene(),lockObject:this.props.lockObject}))},t}(s.Component),Ft=function(e){function t(t){var r=e.call(this,t)||this;return r._onDebugSelectionChangeObservable=new u.Observable,r}return a(t,e),t.prototype.renderTextures=function(){var e=this.props.material,t=this._onDebugSelectionChangeObservable;return s.createElement(Ee,{globalState:this.props.globalState,title:"TEXTURES"},s.createElement(qe,{label:"Diffuse",texture:e.diffuseTexture,material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Reflection",texture:e.reflectionTexture,material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),e.reflectionTexture&&s.createElement(Le,{label:"Reflection blur",target:e,propertyName:"reflectionBlur",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t.prototype.render=function(){var e=this.props.material;return s.createElement("div",{className:"pane"},s.createElement(Ke,{globalState:this.props.globalState,lockObject:this.props.lockObject,material:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"LIGHTING & COLORS"},s.createElement(Ve,{label:"Primary",target:e,propertyName:"primaryColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Shadow level",target:e,propertyName:"primaryColorShadowLevel",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Highlight level",target:e,propertyName:"primaryColorHighlightLevel",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable})),this.renderTextures(),s.createElement(Ee,{globalState:this.props.globalState,title:"RENDERING",closed:!0},s.createElement(Pe,{label:"Enable noise",target:e,propertyName:"enableNoise",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Opacity fresnel",target:e,propertyName:"opacityFresnel",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Reflection fresnel",target:e,propertyName:"reflectionFresnel",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Reflection amount",target:e,propertyName:"reflectionAmount",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),Gt=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.renderGridInformation=function(){var e=this.props.control;if(!e.parent)return null;var t=e.parent;if(void 0===t.rowCount)return null;var r=t.getChildCellInfo(e);if(void 0===r)return null;var n=r.split(":");return s.createElement(Ee,{globalState:this.props.globalState,title:"GRID"},s.createElement(Ce,{label:"Row",value:n[0]}),s.createElement(Ce,{label:"Column",value:n[1]}))},t.prototype.render=function(){var e=this.props.control,t=[{label:"Left",value:nt.Control.HORIZONTAL_ALIGNMENT_LEFT},{label:"Right",value:nt.Control.HORIZONTAL_ALIGNMENT_RIGHT},{label:"Center",value:nt.Control.HORIZONTAL_ALIGNMENT_CENTER}],r=[{label:"Top",value:nt.Control.VERTICAL_ALIGNMENT_TOP},{label:"Bottom",value:nt.Control.VERTICAL_ALIGNMENT_BOTTOM},{label:"Center",value:nt.Control.VERTICAL_ALIGNMENT_CENTER}];return s.createElement("div",null,s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Ce,{label:"Class",value:e.getClassName()}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Name",target:e,propertyName:"name",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ce,{label:"Unique ID",value:e.uniqueId.toString()}),s.createElement(Le,{label:"Alpha",target:e,propertyName:"alpha",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),void 0!==e.color&&s.createElement(Be,{lockObject:this.props.lockObject,label:"Color",target:e,propertyName:"color",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),void 0!==e.background&&s.createElement(Be,{lockObject:this.props.lockObject,label:"Background",target:e,propertyName:"background",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),this.renderGridInformation(),s.createElement(Ee,{globalState:this.props.globalState,title:"ALIGNMENT"},s.createElement(Re,{label:"Horizontal",options:t,target:e,propertyName:"horizontalAlignment",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Vertical",options:r,target:e,propertyName:"verticalAlignment",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"POSITION"},s.createElement(Be,{lockObject:this.props.lockObject,label:"Left",target:e,propertyName:"left",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Top",target:e,propertyName:"top",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Width",target:e,propertyName:"width",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Height",target:e,propertyName:"height",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Padding left",target:e,propertyName:"paddingLeft",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Padding top",target:e,propertyName:"paddingTop",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Padding right",target:e,propertyName:"paddingRight",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Padding bottom",target:e,propertyName:"paddingBottom",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"TRANSFORMATION",closed:!0},s.createElement(Me,{lockObject:this.props.lockObject,label:"ScaleX",target:e,propertyName:"scaleX",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"ScaleY",target:e,propertyName:"scaleY",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Rotation",target:e,propertyName:"rotation",minimum:0,maximum:2*Math.PI,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Transform center X",target:e,propertyName:"transformCenterX",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Transform center Y",target:e,propertyName:"transformCenterY",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"FONT",closed:!0},s.createElement(Be,{lockObject:this.props.lockObject,label:"Family",target:e,propertyName:"fontFamily",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Size",target:e,propertyName:"fontSize",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Weight",target:e,propertyName:"fontWeight",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Style",target:e,propertyName:"fontStyle",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"SHADOWS",closed:!0},s.createElement(Be,{lockObject:this.props.lockObject,label:"Color",target:e,propertyName:"shadowColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Offset X",target:e,propertyName:"shadowOffsetX",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Offset Y",target:e,propertyName:"shadowOffsetY",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Blur",target:e,propertyName:"shadowBlur",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),Vt=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.control;return s.createElement("div",{className:"pane"},s.createElement(Gt,{globalState:this.props.globalState,lockObject:this.props.lockObject,control:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t}(s.Component),Ut=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.textBlock,t=[{label:"Left",value:nt.Control.HORIZONTAL_ALIGNMENT_LEFT},{label:"Right",value:nt.Control.HORIZONTAL_ALIGNMENT_RIGHT},{label:"Center",value:nt.Control.HORIZONTAL_ALIGNMENT_CENTER}],r=[{label:"Top",value:nt.Control.VERTICAL_ALIGNMENT_TOP},{label:"Bottom",value:nt.Control.VERTICAL_ALIGNMENT_BOTTOM},{label:"Center",value:nt.Control.VERTICAL_ALIGNMENT_CENTER}],n=[{label:"Clip",value:nt.TextWrapping.Clip},{label:"Ellipsis",value:nt.TextWrapping.Ellipsis},{label:"Word wrap",value:nt.TextWrapping.WordWrap}];return s.createElement("div",{className:"pane"},s.createElement(Gt,{globalState:this.props.globalState,lockObject:this.props.lockObject,control:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"TEXTBLOCK"},s.createElement(Be,{lockObject:this.props.lockObject,label:"Text",target:e,propertyName:"text",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Horizontal text alignment",options:t,target:e,propertyName:"textHorizontalAlignment",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Vertical text alignment",options:r,target:e,propertyName:"textVerticalAlignment",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Resize to fit",target:e,propertyName:"resizeToFit",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Wrapping",options:n,target:e,propertyName:"textWrapping",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Line spacing",target:e,propertyName:"lineSpacing",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"OUTLINE"},s.createElement(Me,{lockObject:this.props.lockObject,label:"Outline width",target:e,propertyName:"outlineWidth",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Outline color",target:e,propertyName:"outlineColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),Ht=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.inputText;return s.createElement("div",{className:"pane"},s.createElement(Gt,{globalState:this.props.globalState,lockObject:this.props.lockObject,control:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"INPUTTEXT"},s.createElement(Be,{lockObject:this.props.lockObject,label:"Text",target:e,propertyName:"text",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Prompt",target:e,propertyName:"promptMessage",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Max width",target:e,propertyName:"maxWidth",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Highlight color",target:e,propertyName:"textHighlightColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Highligher opacity",minimum:0,maximum:1,step:.01,target:e,propertyName:"highligherOpacity",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"On focus select all",target:e,propertyName:"onFocusSelectAll",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Focused background",target:e,propertyName:"focusedBackground",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Max width",target:e,propertyName:"maxWidth",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Margin",target:e,propertyName:"margin",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Auto stretch width",target:e,propertyName:"autoStretchWidth",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Thickness",target:e,propertyName:"thickness",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Placeholder text",target:e,propertyName:"placeholderText",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Placeholder color",target:e,propertyName:"placeholderColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),Bt=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.colorPicker;return s.createElement("div",{className:"pane"},s.createElement(Gt,{globalState:this.props.globalState,lockObject:this.props.lockObject,control:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"COLORPICKER"},s.createElement(Ve,{label:"Color",target:e,propertyName:"value",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),Wt=function(e){function t(t){var r=e.call(this,t)||this,n=r.props.animationGroup;return r.state={playButtonText:n.isPlaying?"Pause":"Play",currentFrame:0},r.connect(r.props.animationGroup),r._onBeforeRenderObserver=r.props.scene.onBeforeRenderObservable.add((function(){r.updateCurrentFrame(r.props.animationGroup)})),r.timelineRef=s.createRef(),r}return a(t,e),t.prototype.disconnect=function(e){this._onAnimationGroupPlayObserver&&(e.onAnimationGroupPlayObservable.remove(this._onAnimationGroupPlayObserver),this._onAnimationGroupPlayObserver=null),this._onAnimationGroupPauseObserver&&(e.onAnimationGroupPauseObservable.remove(this._onAnimationGroupPauseObserver),this._onAnimationGroupPauseObserver=null)},t.prototype.connect=function(e){var t=this;this._onAnimationGroupPlayObserver=e.onAnimationGroupPlayObservable.add((function(){t.forceUpdate()})),this._onAnimationGroupPauseObserver=e.onAnimationGroupPauseObservable.add((function(){t.forceUpdate()})),this.updateCurrentFrame(e)},t.prototype.updateCurrentFrame=function(e){if(e.targetedAnimations.length>0){var t=e.targetedAnimations[0].animation.runtimeAnimations;t.length>0?this.setState({currentFrame:t[0].currentFrame}):this.setState({currentFrame:0})}},t.prototype.shouldComponentUpdate=function(e){return this.props.animationGroup!==e.animationGroup&&(this.disconnect(this.props.animationGroup),this.connect(e.animationGroup)),!0},t.prototype.componentWillUnmount=function(){this.disconnect(this.props.animationGroup),this._onBeforeRenderObserver&&(this.props.scene.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=null)},t.prototype.playOrPause=function(){var e=this.props.animationGroup;e.isPlaying?(this.setState({playButtonText:"Play"}),e.pause()):(this.setState({playButtonText:"Pause"}),this.props.scene.animationGroups.forEach((function(e){return e.pause()})),e.play(!0))},t.prototype.onCurrentFrameChange=function(e){var t=this.props.animationGroup;t.isPlaying?t.goToFrame(e):(t.play(!0),t.goToFrame(e),t.pause()),this.setState({currentFrame:e})},t.prototype.render=function(){var e=this,t=this.props.animationGroup,r=t.isPlaying?"Pause":"Play";return s.createElement("div",{className:"pane"},s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Ce,{label:"Class",value:t.getClassName()}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Name",target:t,propertyName:"name",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"CONTROLS"},s.createElement(Ye,{label:r,onClick:function(){return e.playOrPause()}}),s.createElement(Le,{label:"Speed ratio",minimum:0,maximum:10,step:.1,target:t,propertyName:"speedRatio",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{ref:this.timelineRef,label:"Current frame",minimum:t.from,maximum:t.to,step:(t.to-t.from)/1e3,directValue:this.state.currentFrame,onInput:function(t){return e.onCurrentFrameChange(t)}})),s.createElement(Ee,{globalState:this.props.globalState,title:"INFOS"},s.createElement(Ce,{label:"Animation count",value:t.targetedAnimations.length.toString()}),s.createElement(Ce,{label:"From",value:t.from.toFixed(2)}),s.createElement(Ce,{label:"To",value:t.to.toFixed(2)}),s.createElement(Ce,{label:"Unique ID",value:t.uniqueId.toString()})))},t}(s.Component),Yt=function(){this.lock=!1},Zt=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this,t=this.props.image,r=[{label:"None",value:nt.Image.STRETCH_NONE},{label:"Fill",value:nt.Image.STRETCH_FILL},{label:"Uniform",value:nt.Image.STRETCH_UNIFORM},{label:"Extend",value:nt.Image.STRETCH_EXTEND},{label:"NinePatch",value:nt.Image.STRETCH_NINE_PATCH}];return s.createElement("div",{className:"pane"},s.createElement(Gt,{globalState:this.props.globalState,lockObject:this.props.lockObject,control:t,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"IMAGE"},s.createElement(Me,{lockObject:this.props.lockObject,label:"Source left",target:t,propertyName:"sourceLeft",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Source top",target:t,propertyName:"sourceTop",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Source width",target:t,propertyName:"sourceWidth",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Source height",target:t,propertyName:"sourceHeight",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Autoscale",target:t,propertyName:"autoScale",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Stretch",options:r,target:t,propertyName:"stretch",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onSelect:function(t){return e.setState({mode:t})}})),s.createElement(Ee,{globalState:this.props.globalState,title:"ANIMATION SHEET"},s.createElement(Me,{lockObject:this.props.lockObject,label:"Cell Id",isInteger:!0,target:t,propertyName:"cellId",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Cell width",target:t,propertyName:"cellWidth",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Cell height",target:t,propertyName:"cellHeight",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),Kt=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.slider;return s.createElement("div",{className:"pane"},s.createElement(Gt,{globalState:this.props.globalState,lockObject:this.props.lockObject,control:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"SLIDER"},s.createElement(Be,{lockObject:this.props.lockObject,label:"Border color",target:e,propertyName:"borderColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Display thumb",target:e,propertyName:"displayThumb",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Thumb circle",target:e,propertyName:"isThumbCircle",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Vertical",target:e,propertyName:"isVertical",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Thumb clamped",target:e,propertyName:"isThumbClamped",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Bar offset",target:e,propertyName:"barOffset",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Thumb width",target:e,propertyName:"thumbWidth",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Minimum",target:e,propertyName:"minimum",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Maximum",target:e,propertyName:"maximum",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Value",target:e,propertyName:"value",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),Xt=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.imageBasedSlider;return s.createElement("div",{className:"pane"},s.createElement(Gt,{globalState:this.props.globalState,lockObject:this.props.lockObject,control:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"IMAGE BASED SLIDER"},s.createElement(Pe,{label:"Display thumb",target:e,propertyName:"displayThumb",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Vertical",target:e,propertyName:"isVertical",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Thumb clamped",target:e,propertyName:"isThumbClamped",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Bar offset",target:e,propertyName:"barOffset",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Thumb width",target:e,propertyName:"thumbWidth",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Minimum",target:e,propertyName:"minimum",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Maximum",target:e,propertyName:"maximum",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Value",target:e,propertyName:"value",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),Qt=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.rectangle;return s.createElement("div",{className:"pane"},s.createElement(Gt,{globalState:this.props.globalState,lockObject:this.props.lockObject,control:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"RECTANGLE"},s.createElement(Pe,{label:"Clip children",target:e,propertyName:"clipChildren",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Thickness",target:e,propertyName:"thickness",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Corner radius",target:e,propertyName:"cornerRadius",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),qt=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.ellipse;return s.createElement("div",{className:"pane"},s.createElement(Gt,{globalState:this.props.globalState,lockObject:this.props.lockObject,control:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"ELLIPSE"},s.createElement(Pe,{label:"Clip children",target:e,propertyName:"clipChildren",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Thickness",target:e,propertyName:"thickness",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),$t=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.checkbox;return s.createElement("div",{className:"pane"},s.createElement(Gt,{globalState:this.props.globalState,lockObject:this.props.lockObject,control:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"CHECKBOX"},s.createElement(Me,{lockObject:this.props.lockObject,label:"Check size ratio",target:e,propertyName:"checkSizeRatio",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Checked",target:e,propertyName:"isChecked",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),Jt=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.radioButton;return s.createElement("div",{className:"pane"},s.createElement(Gt,{globalState:this.props.globalState,lockObject:this.props.lockObject,control:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"RADIO BUTTON"},s.createElement(Me,{lockObject:this.props.lockObject,label:"Thickness",target:e,propertyName:"thickness",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Check size ratio",target:e,propertyName:"checkSizeRatio",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Group",target:e,propertyName:"group",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Checked",target:e,propertyName:"isChecked",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),er=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.onDashChange=function(e){var t=this.props.line,r=e.split(",");t.dash=[],r.forEach((function(e){var r=parseInt(e);isNaN(r)||t.dash.push(r)}))},t.prototype.render=function(){var e=this,t=this.props.line;return s.createElement("div",{className:"pane"},s.createElement(Gt,{globalState:this.props.globalState,lockObject:this.props.lockObject,control:t,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"LINE"},s.createElement(Me,{lockObject:this.props.lockObject,label:"Line width",target:t,propertyName:"lineWidth",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"X1",target:t,propertyName:"x1",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Y1",target:t,propertyName:"y1",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"X2",target:t,propertyName:"x2",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Y2",target:t,propertyName:"y2",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Dash pattern",target:t,value:t.dash.join(","),onChange:function(t){return e.onDashChange(t)}})))},t}(s.Component),tr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.scrollViewer;return s.createElement("div",{className:"pane"},s.createElement(Gt,{globalState:this.props.globalState,lockObject:this.props.lockObject,control:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"RECTANGLE"},s.createElement(Me,{lockObject:this.props.lockObject,label:"Thickness",target:e,propertyName:"thickness",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Corner radius",target:e,propertyName:"cornerRadius",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"SCROLLVIEWER"},s.createElement(Me,{lockObject:this.props.lockObject,label:"Bar size",target:e,propertyName:"barSize",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Bar color",target:e,propertyName:"barColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Bar background",target:e,propertyName:"barBackground",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Wheel precision",target:e,propertyName:"wheelPrecision",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),rr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.renderRows=function(){for(var e=this.props.grid,t=[],r=0;r<e.rowCount;r++)t.push(e.getRowDefinition(r));return t.map((function(t,r){return s.createElement(Ce,{key:"r"+r,label:"Row "+r,value:t.toString(e.host,2),underline:r===e.rowCount-1})}))},t.prototype.renderColumns=function(){for(var e=this.props.grid,t=[],r=0;r<e.columnCount;r++)t.push(e.getColumnDefinition(r));return t.map((function(t,r){return s.createElement(Ce,{key:"c"+r,label:"Column "+r,value:t.toString(e.host,2)})}))},t.prototype.render=function(){for(var e=this.props.grid,t=[],r=0;r<e.rowCount;r++)t.push(e.getColumnDefinition(r));return s.createElement("div",{className:"pane"},s.createElement(Gt,{globalState:this.props.globalState,lockObject:this.props.lockObject,control:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"GRID"},this.renderRows(),this.renderColumns()))},t}(s.Component),nr=function(e){function t(t){var r=e.call(this,t)||this;return r._onDebugSelectionChangeObservable=new u.Observable,r}return a(t,e),t.prototype.renderTextures=function(){var e=this.props.material,t=this._onDebugSelectionChangeObservable;return s.createElement(Ee,{globalState:this.props.globalState,title:"TEXTURES"},s.createElement(qe,{label:"Base",texture:e.baseTexture,propertyName:"baseTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Metallic roughness",texture:e.metallicRoughnessTexture,propertyName:"metallicRoughnessTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Normal",texture:e.normalTexture,propertyName:"normalTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Environment",texture:e.environmentTexture,propertyName:"environmentTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Emissive",texture:e.emissiveTexture,propertyName:"emissiveTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Lightmap",texture:e.lightmapTexture,propertyName:"lightmapTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}))},t.prototype.render=function(){var e=this.props.material;return s.createElement("div",{className:"pane"},s.createElement(Ke,{globalState:this.props.globalState,lockObject:this.props.lockObject,material:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),this.renderTextures(),s.createElement(Ee,{globalState:this.props.globalState,title:"LIGHTING & COLORS"},s.createElement(Ve,{label:"Base",target:e,propertyName:"baseColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable,isLinear:!0}),s.createElement(Ve,{label:"Emissive",target:e,propertyName:"emissiveColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable,isLinear:!0})),s.createElement(Ee,{globalState:this.props.globalState,title:"LEVELS",closed:!0},s.createElement(Le,{label:"Metallic",target:e,propertyName:"metallic",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Roughness",target:e,propertyName:"roughness",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"NORMAL MAP",closed:!0},s.createElement(Pe,{label:"Invert X axis",target:e,propertyName:"invertNormalMapX",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Invert Y axis",target:e,propertyName:"invertNormalMapY",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),ar=function(e){function t(t){var r=e.call(this,t)||this;return r._onDebugSelectionChangeObservable=new u.Observable,r}return a(t,e),t.prototype.renderTextures=function(){var e=this.props.material,t=this._onDebugSelectionChangeObservable;return s.createElement(Ee,{globalState:this.props.globalState,title:"TEXTURES"},s.createElement(qe,{label:"Diffuse",texture:e.diffuseTexture,propertyName:"diffuseTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Specular glossiness",texture:e.specularGlossinessTexture,propertyName:"specularGlossinessTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Normal",texture:e.normalTexture,propertyName:"normalTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Environment",texture:e.environmentTexture,propertyName:"environmentTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Emissive",texture:e.emissiveTexture,propertyName:"emissiveTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}),s.createElement(qe,{label:"Lightmap",texture:e.lightmapTexture,propertyName:"lightmapTexture",material:e,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:t}))},t.prototype.render=function(){var e=this.props.material;return s.createElement("div",{className:"pane"},s.createElement(Ke,{globalState:this.props.globalState,lockObject:this.props.lockObject,material:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),this.renderTextures(),s.createElement(Ee,{globalState:this.props.globalState,title:"LIGHTING & COLORS"},s.createElement(Ve,{label:"Diffuse",target:e,propertyName:"diffuseColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable,isLinear:!0}),s.createElement(Ve,{label:"Specular",target:e,propertyName:"specularColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable,isLinear:!0})),s.createElement(Ee,{globalState:this.props.globalState,title:"LEVELS",closed:!0},s.createElement(Le,{label:"Glossiness",target:e,propertyName:"glossiness",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"NORMAL MAP",closed:!0},s.createElement(Pe,{label:"Invert X axis",target:e,propertyName:"invertNormalMapX",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Invert Y axis",target:e,propertyName:"invertNormalMapY",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),or=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.stackPanel;return s.createElement("div",{className:"pane"},s.createElement(Gt,{globalState:this.props.globalState,lockObject:this.props.lockObject,control:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"STACKPANEL"},s.createElement(Pe,{label:"Clip children",target:e,propertyName:"clipChildren",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Vertical",target:e,propertyName:"isVertical",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),ir=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this,t=this.props.postProcess;return s.createElement("div",null,s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Ce,{label:"Class",value:t.getClassName()}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Name",target:t,propertyName:"name",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.width&&s.createElement(Ce,{label:"Width",value:t.width.toString()}),t.height&&s.createElement(Ce,{label:"Height",value:t.height.toString()}),s.createElement(Pe,{label:"Auto clear",target:t,propertyName:"autoClear",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.clearColor&&s.createElement(Ve,{label:"Clear color",target:t,propertyName:"clearColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Pixel perfect",target:t,propertyName:"enablePixelPerfectMode",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Fullscreen viewport",target:t,propertyName:"forceFullscreenViewport",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Samples",target:t,propertyName:"samples",minimum:1,maximum:8,step:1,decimalCount:0,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ye,{label:"Dispose",onClick:function(){t.dispose(),e.props.globalState.onSelectionChangedObservable.notifyObservers(null)}})))},t}(s.Component),lr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.edit=function(){this.props.postProcess.nodeMaterialSource.edit()},t.prototype.render=function(){var e=this,t=this.props.postProcess;return s.createElement("div",{className:"pane"},s.createElement(ir,{globalState:this.props.globalState,lockObject:this.props.lockObject,postProcess:t,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.nodeMaterialSource&&s.createElement(Ee,{globalState:this.props.globalState,title:"CONFIGURATION"},s.createElement(Ye,{label:"Node Material Editor",onClick:function(){return e.edit()}})))},t}(s.Component),sr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.renderPipeline,t=e;return s.createElement("div",null,s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Ce,{label:"Name",value:e.name}),s.createElement(Ce,{label:"Class",value:e.getClassName()}),void 0!==t.samples&&s.createElement(Le,{label:"Samples",minimum:1,maximum:8,step:1,decimalCount:0,target:e,propertyName:"samples",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),pr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.renderPipeline;return s.createElement("div",{className:"pane"},s.createElement(sr,{globalState:this.props.globalState,lockObject:this.props.lockObject,renderPipeline:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t}(s.Component),cr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this,t=this.props.renderPipeline,r=t.scene.activeCamera,n=[{label:"Standard",value:u.ImageProcessingConfiguration.TONEMAPPING_STANDARD},{label:"ACES",value:u.ImageProcessingConfiguration.TONEMAPPING_ACES}],a=[{label:"Multiply",value:u.ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY},{label:"Opaque",value:u.ImageProcessingConfiguration.VIGNETTEMODE_OPAQUE}];return s.createElement("div",{className:"pane"},s.createElement(sr,{globalState:this.props.globalState,lockObject:this.props.lockObject,renderPipeline:t,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"BLOOM"},s.createElement(Pe,{label:"Enabled",target:t,onValueChanged:function(){return e.forceUpdate()},propertyName:"bloomEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.bloomEnabled&&s.createElement("div",null,s.createElement(Le,{label:"Threshold",minimum:0,maximum:1,step:.05,target:t,propertyName:"bloomThreshold",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Weight",minimum:0,maximum:1,step:.05,target:t,propertyName:"bloomWeight",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Kernel",minimum:0,maximum:128,step:1,target:t,propertyName:"bloomKernel",onPropertyChangedObservable:this.props.onPropertyChangedObservable,decimalCount:0}),s.createElement(Le,{label:"Scale",minimum:0,maximum:1,step:.25,target:t,propertyName:"bloomScale",onPropertyChangedObservable:this.props.onPropertyChangedObservable}))),s.createElement(Ee,{globalState:this.props.globalState,title:"CHROMATIC ABERRATION"},s.createElement(Pe,{label:"Enabled",target:t,onValueChanged:function(){return e.forceUpdate()},propertyName:"chromaticAberrationEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.chromaticAberrationEnabled&&s.createElement("div",null,s.createElement(Le,{label:"aberrationAmount",minimum:0,maximum:128,step:.1,target:t.chromaticAberration,propertyName:"aberrationAmount",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Radial intensity",minimum:0,maximum:1,step:.01,target:t.chromaticAberration,propertyName:"radialIntensity",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(St,{label:"Center",target:t.chromaticAberration,propertyName:"centerPosition",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(St,{label:"Direction",target:t.chromaticAberration,propertyName:"direction",onPropertyChangedObservable:this.props.onPropertyChangedObservable}))),s.createElement(Ee,{globalState:this.props.globalState,title:"DEPTH OF FIELD"},s.createElement(Pe,{label:"Enabled",target:t,onValueChanged:function(){return e.forceUpdate()},propertyName:"depthOfFieldEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.depthOfFieldEnabled&&s.createElement("div",null,s.createElement(Le,{label:"Focal length",minimum:0,maximum:r.maxZ,step:.1,target:t.depthOfField,propertyName:"focalLength",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"fStop",minimum:0,maximum:32,step:.1,target:t.depthOfField,propertyName:"fStop",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Distance",minimum:0,maximum:r.maxZ,step:.1,target:t.depthOfField,propertyName:"focusDistance",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Lens size",minimum:0,maximum:1e3,step:1,target:t.depthOfField,propertyName:"lensSize",onPropertyChangedObservable:this.props.onPropertyChangedObservable,decimalCount:0}))),s.createElement(Ee,{globalState:this.props.globalState,title:"FXAA"},s.createElement(Pe,{label:"Enabled",target:t,propertyName:"fxaaEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"GLOW LAYER"},s.createElement(Pe,{label:"Enabled",target:t,propertyName:"glowLayerEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.glowLayerEnabled&&s.createElement("div",null,s.createElement(Le,{label:"Blur kernel size",minimum:1,maximum:128,step:1,decimalCount:0,target:t.glowLayer,propertyName:"blurKernelSize",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Intensity",minimum:0,maximum:10,step:.1,target:t.glowLayer,propertyName:"intensity",onPropertyChangedObservable:this.props.onPropertyChangedObservable}))),s.createElement(Ee,{globalState:this.props.globalState,title:"GRAIN"},s.createElement(Pe,{label:"Enabled",target:t,onValueChanged:function(){return e.forceUpdate()},propertyName:"grainEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.grainEnabled&&s.createElement("div",null,s.createElement(Pe,{label:"Animated",target:t.grain,propertyName:"animated",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Intensity",minimum:0,maximum:50,step:.1,target:t.grain,propertyName:"intensity",onPropertyChangedObservable:this.props.onPropertyChangedObservable}))),s.createElement(Ee,{globalState:this.props.globalState,title:"IMAGE PROCESSING"},s.createElement(Pe,{label:"Enabled",target:t,onValueChanged:function(){return e.forceUpdate()},propertyName:"imageProcessingEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.imageProcessing&&s.createElement("div",null,s.createElement(Ye,{label:"Convert clear color to linear",onClick:function(){return t.scene.clearColor=t.scene.clearColor.toLinearSpace()}}),s.createElement(Ye,{label:"Convert clear color to gamma",onClick:function(){return t.scene.clearColor=t.scene.clearColor.toGammaSpace()}}),s.createElement(Le,{minimum:0,maximum:4,step:.1,label:"Contrast",target:t.imageProcessing,propertyName:"contrast",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{minimum:0,maximum:4,step:.1,label:"Exposure",target:t.imageProcessing,propertyName:"exposure",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Tone mapping",target:t.imageProcessing,propertyName:"toneMappingEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Tone mapping type",options:n,target:t.imageProcessing,propertyName:"toneMappingType",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onSelect:function(t){return e.setState({mode:t})}}),s.createElement(Pe,{label:"Vignette",target:t.imageProcessing,propertyName:"vignetteEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{minimum:0,maximum:4,step:.1,label:"Vignette weight",target:t.imageProcessing,propertyName:"vignetteWeight",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{minimum:0,maximum:1,step:.1,label:"Vignette stretch",target:t.imageProcessing,propertyName:"vignetteStretch",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{minimum:0,maximum:Math.PI,step:.1,label:"Vignette FOV",target:t.imageProcessing,propertyName:"vignetteCameraFov",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{minimum:0,maximum:1,step:.1,label:"Vignette center X",target:t.imageProcessing,propertyName:"vignetteCentreX",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{minimum:0,maximum:1,step:.1,label:"Vignette center Y",target:t.imageProcessing,propertyName:"vignetteCentreY",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Vignette color",target:t.imageProcessing,propertyName:"vignetteColor",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Vignette blend mode",options:a,target:t.imageProcessing,propertyName:"vignetteBlendMode",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onSelect:function(t){return e.setState({mode:t})}}))),s.createElement(Ee,{globalState:this.props.globalState,title:"SHARPEN"},s.createElement(Pe,{label:"Enabled",target:t,onValueChanged:function(){return e.forceUpdate()},propertyName:"sharpenEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.sharpenEnabled&&s.createElement("div",null,s.createElement(Le,{label:"Color amount",minimum:0,maximum:1,step:.05,target:t.sharpen,propertyName:"colorAmount",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Edge amount",minimum:0,maximum:5,step:.05,target:t.sharpen,propertyName:"edgeAmount",onPropertyChangedObservable:this.props.onPropertyChangedObservable}))))},t}(s.Component),ur=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.renderPipeline;return s.createElement("div",{className:"pane"},s.createElement(sr,{globalState:this.props.globalState,lockObject:this.props.lockObject,renderPipeline:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"SSAO"},s.createElement(Le,{label:"Strength",minimum:0,maximum:2,step:.05,target:e,propertyName:"totalStrength",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Base",minimum:0,maximum:1,step:.05,target:e,propertyName:"base",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Radius",minimum:1e-4,maximum:.001,step:1e-4,target:e,propertyName:"radius",onPropertyChangedObservable:this.props.onPropertyChangedObservable,decimalCount:4}),s.createElement(Le,{label:"Area",minimum:1e-4,maximum:.01,step:1e-4,target:e,propertyName:"area",onPropertyChangedObservable:this.props.onPropertyChangedObservable,decimalCount:4}),s.createElement(Le,{label:"Falloff",minimum:0,maximum:1e-5,step:1e-6,target:e,propertyName:"fallOff",onPropertyChangedObservable:this.props.onPropertyChangedObservable,decimalCount:6})))},t}(s.Component),dr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.renderPipeline,t=e.scene.activeCamera;return s.createElement("div",{className:"pane"},s.createElement(sr,{globalState:this.props.globalState,lockObject:this.props.lockObject,renderPipeline:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"SSAO"},s.createElement(Le,{label:"Strength",minimum:0,maximum:2,step:.05,target:e,propertyName:"totalStrength",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Base",minimum:0,maximum:1,step:.05,target:e,propertyName:"base",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Max Z",minimum:0,maximum:t.maxZ,step:1,target:e,propertyName:"maxZ",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Min Z aspect",minimum:0,maximum:.5,step:.01,target:e,propertyName:"minZAspect",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Radius",minimum:0,maximum:10,step:.05,target:e,propertyName:"radius",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),hr=function(e){function t(t){var r=e.call(this,t)||this;return r._skeletonViewersEnabled=!1,r._skeletonViewerDisplayOptions={displayMode:u.SkeletonViewer.DISPLAY_LINES,sphereBaseSize:.15,sphereScaleUnit:2,sphereFactor:.865,midStep:.235,midStepFactor:.155},r._skeletonViewers=new Array,r.checkSkeletonViewerState(r.props),r}return a(t,e),t.prototype.switchSkeletonViewers=function(){this._skeletonViewersEnabled=!this._skeletonViewersEnabled;var e=this.props.skeleton.getScene();if(this._skeletonViewersEnabled)for(var t=0,r=e.meshes;t<r.length;t++){var n=r[t];if(n.skeleton===this.props.skeleton){for(var a=!1,o=0;o<this._skeletonViewers.length;o++)if(this._skeletonViewers[o].skeleton===n.skeleton){a=!0;break}if(a)continue;var i=new u.SkeletonViewer(n.skeleton,n,e,!1,3,{displayMode:this._skeletonViewerDisplayOptions.displayMode,displayOptions:{sphereBaseSize:this._skeletonViewerDisplayOptions.sphereBaseSize,sphereScaleUnit:this._skeletonViewerDisplayOptions.sphereScaleUnit,sphereFactor:this._skeletonViewerDisplayOptions.sphereFactor,midStep:this._skeletonViewerDisplayOptions.midStep,midStepFactor:this._skeletonViewerDisplayOptions.midStepFactor}});i.isEnabled=!0,this._skeletonViewers.push(i),n.reservedDataStore||(n.reservedDataStore={}),n.reservedDataStore.skeletonViewer=i}}else{for(var l=0;l<this._skeletonViewers.length;l++)this._skeletonViewers[l].mesh.reservedDataStore.skeletonViewer=null,this._skeletonViewers[l].dispose();this._skeletonViewers=[]}},t.prototype.checkSkeletonViewerState=function(e){var t=e.skeleton.getScene();if(this._skeletonViewers=[],t){for(var r=!0,n=0,a=t.meshes;n<a.length;n++){var o=a[n];if(o.skeleton===e.skeleton&&o.reservedDataStore&&o.reservedDataStore.skeletonViewer&&(this._skeletonViewers.push(o.reservedDataStore.skeletonViewer),r))for(var i in r=!1,this._skeletonViewerDisplayOptions.displayMode=this._skeletonViewers[0].displayMode,this._skeletonViewers[0].options.displayOptions)i&&(this._skeletonViewerDisplayOptions[i]=this._skeletonViewers[0].options.displayOptions[i])}this._skeletonViewersEnabled=this._skeletonViewers.length>0}},t.prototype.changeDisplayMode=function(){if(this._skeletonViewersEnabled)for(var e=0;e<this._skeletonViewers.length;e++)this._skeletonViewers[e].changeDisplayMode(this._skeletonViewerDisplayOptions.displayMode||0)},t.prototype.changeDisplayOptions=function(e,t){if(this._skeletonViewersEnabled){for(var r=0;r<this._skeletonViewers.length;r++)this._skeletonViewers[r].changeDisplayOptions(e,t);void 0!==this._skeletonViewerDisplayOptions[e]&&(this._skeletonViewerDisplayOptions[e]=t)}},t.prototype.shouldComponentUpdate=function(e){return e.skeleton!==this.props.skeleton&&this.checkSkeletonViewerState(e),!0},t.prototype.onOverrideMeshLink=function(){if(this.props.globalState.onSelectionChangedObservable){var e=this.props.skeleton;this.props.globalState.onSelectionChangedObservable.notifyObservers(e.overrideMesh)}},t.prototype.render=function(){var e,t=this,r=this.props.skeleton,n=[{label:"Lines",value:u.SkeletonViewer.DISPLAY_LINES},{label:"Spheres",value:u.SkeletonViewer.DISPLAY_SPHERES},{label:"Sphere and Spurs",value:u.SkeletonViewer.DISPLAY_SPHERE_AND_SPURS}];return e=this._skeletonViewerDisplayOptions.displayMode>u.SkeletonViewer.DISPLAY_LINES?s.createElement(Ee,{globalState:this.props.globalState,title:"DISPLAY OPTIONS"},s.createElement(Me,{label:"sphereBaseSize",target:this._skeletonViewerDisplayOptions,propertyName:"sphereBaseSize",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onChange:function(e){t.changeDisplayOptions("sphereBaseSize",e)}}),s.createElement(Me,{label:"sphereScaleUnit",target:this._skeletonViewerDisplayOptions,propertyName:"sphereScaleUnit",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onChange:function(e){t.changeDisplayOptions("sphereScaleUnit",e)}}),s.createElement(Me,{label:"sphereFactor",target:this._skeletonViewerDisplayOptions,propertyName:"sphereFactor",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onChange:function(e){t.changeDisplayOptions("sphereFactor",e)}}),s.createElement(Me,{label:"midStep",target:this._skeletonViewerDisplayOptions,propertyName:"midStep",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onChange:function(e){t.changeDisplayOptions("midStep",e)}}),s.createElement(Me,{label:"midStepFactor",target:this._skeletonViewerDisplayOptions,propertyName:"midStepFactor",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onChange:function(e){t.changeDisplayOptions("midStepFactor",e)}})):null,s.createElement("div",{className:"pane"},s.createElement(We,{globalState:this.props.globalState,target:r,lockObject:this.props.lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Ce,{label:"ID",value:r.id}),s.createElement(Ce,{label:"Bone count",value:r.bones.length.toString()}),r.overrideMesh&&s.createElement(Ce,{label:"Override mesh",value:r.overrideMesh.name,onLink:function(){return t.onOverrideMeshLink()}}),s.createElement(Pe,{label:"Use texture to store matrices",target:r,propertyName:"useTextureToStoreBoneMatrices",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"DEBUG"},s.createElement(Pe,{label:"Enabled",isSelected:function(){return t._skeletonViewersEnabled},onSelect:function(){return t.switchSkeletonViewers()}}),s.createElement(Re,{label:"displayMode",options:n,target:this._skeletonViewerDisplayOptions,propertyName:"displayMode",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onSelect:function(){return t.changeDisplayMode()}}),e)),s.createElement(Ze,{globalState:this.props.globalState,animatable:r,scene:r.getScene(),lockObject:this.props.lockObject}))},t}(s.Component),br=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.onTransformNodeLink=function(){if(this.props.globalState.onSelectionChangedObservable){var e=this.props.bone.getTransformNode();this.props.globalState.onSelectionChangedObservable.notifyObservers(e)}},t.prototype.render=function(){var e=this,t=this.props.bone;return s.createElement("div",{className:"pane"},s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Ce,{label:"Name",value:t.name}),s.createElement(Ce,{label:"Index",value:t.getIndex().toString()}),s.createElement(Ce,{label:"Unique ID",value:t.uniqueId.toString()}),t.getParent()&&s.createElement(Ce,{label:"Parent",value:t.getParent().name,onLink:function(){return e.props.globalState.onSelectionChangedObservable.notifyObservers(t.getParent())}}),t.getTransformNode()&&s.createElement(Ce,{label:"Linked node",value:t.getTransformNode().name,onLink:function(){return e.onTransformNodeLink()}})),s.createElement(Ee,{globalState:this.props.globalState,title:"TRANSFORMATIONS"},s.createElement(Ue,{label:"Position",target:t,propertyName:"position",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),!t.rotationQuaternion&&s.createElement(Ue,{label:"Rotation",useEuler:this.props.globalState.onlyUseEulers,target:t,propertyName:"rotation",step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.rotationQuaternion&&s.createElement(He,{label:"Rotation",useEuler:this.props.globalState.onlyUseEulers,target:t,propertyName:"rotationQuaternion",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Scaling",target:t,propertyName:"scaling",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),mr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.light,t=(e.getShadowGenerator()||null)instanceof u.CascadedShadowGenerator;return s.createElement("div",{className:"pane"},s.createElement(Nt,{globalState:this.props.globalState,lockObject:this.props.lockObject,light:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"SETUP"},s.createElement(Ve,{label:"Diffuse",target:e,propertyName:"diffuse",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Specular",target:e,propertyName:"specular",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Position",target:e,propertyName:"position",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Direction",target:e,propertyName:"direction",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),!t&&s.createElement(Pe,{label:"Auto Calc Shadow ZBounds",target:e,propertyName:"autoCalcShadowZBounds",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(_t,{globalState:this.props.globalState,lockObject:this.props.lockObject,light:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t}(s.Component),gr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.light;return s.createElement("div",{className:"pane"},s.createElement(Nt,{globalState:this.props.globalState,lockObject:this.props.lockObject,light:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"SETUP"},s.createElement(Ve,{label:"Diffuse",target:e,propertyName:"diffuse",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ve,{label:"Specular",target:e,propertyName:"specular",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Position",target:e,propertyName:"position",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Direction",target:e,propertyName:"direction",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,useEuler:this.props.globalState.onlyUseEulers,label:"Angle",target:e,propertyName:"angle",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,useEuler:this.props.globalState.onlyUseEulers,label:"Inner angle",target:e,propertyName:"innerAngle",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Exponent",target:e,propertyName:"exponent",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(_t,{globalState:this.props.globalState,lockObject:this.props.lockObject,light:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t}(s.Component),fr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.renderPipeline;return s.createElement("div",{className:"pane"},s.createElement(sr,{globalState:this.props.globalState,lockObject:this.props.lockObject,renderPipeline:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"OPTIONS"},s.createElement(Le,{label:"Edge blur",minimum:0,maximum:5,step:.1,target:e,propertyName:"edgeBlur",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Edge distortion",minimum:0,maximum:5,step:.1,target:e,propertyName:"edgeDistortion",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Grain amount",minimum:0,maximum:1,step:.1,target:e,propertyName:"grainAmount",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Chromatic aberration",minimum:0,maximum:5,step:.1,target:e,propertyName:"chromaticAberration",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Darken out of focus",minimum:0,maximum:5,step:.1,target:e,propertyName:"darkenOutOfFocus",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Blur noise",target:e,propertyName:"blurNoise",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"DEPTH OF FIELD"},s.createElement(Le,{label:"Aperture",minimum:0,maximum:10,step:.1,target:e,propertyName:"dofAperture",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Distortion",minimum:0,maximum:10,step:.1,target:e,propertyName:"dofDistortion",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Pentagon bokeh",target:e,propertyName:"pentagonBokeh",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Highlight gain",minimum:0,maximum:5,step:.1,target:e,propertyName:"highlightsGain",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Highlight threshold",minimum:0,maximum:5,step:.1,target:e,propertyName:"highlightsThreshold",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),vr=function(e){function t(t){var r=e.call(this,t)||this;return r._localChange=!1,r.state={isExpanded:!1,value:r.getCurrentValue().clone()},r}return a(t,e),t.prototype.getCurrentValue=function(){return this.props.target[this.props.propertyName]},t.prototype.shouldComponentUpdate=function(e,t){var r=this.getCurrentValue();return!(r.equals(t.value)&&!this._localChange)&&(t.value=r.clone(),this._localChange=!1,!0)},t.prototype.switchExpandState=function(){this._localChange=!0,this.setState({isExpanded:!this.state.isExpanded})},t.prototype.raiseOnPropertyChanged=function(e){this.props.onChange&&this.props.onChange(this.state.value),this.props.onPropertyChangedObservable&&this.props.onPropertyChangedObservable.notifyObservers({object:this.props.target,property:this.props.propertyName,value:this.state.value,initialValue:e})},t.prototype.updateVector4=function(){var e=this.props.target[this.props.propertyName].clone();this.props.target[this.props.propertyName]=this.state.value,this.setState({value:e}),this.raiseOnPropertyChanged(e)},t.prototype.updateStateX=function(e){this._localChange=!0,this.state.value.x=e,this.updateVector4()},t.prototype.updateStateY=function(e){this._localChange=!0,this.state.value.y=e,this.updateVector4()},t.prototype.updateStateZ=function(e){this._localChange=!0,this.state.value.z=e,this.updateVector4()},t.prototype.updateStateW=function(e){this._localChange=!0,this.state.value.w=e,this.updateVector4()},t.prototype.render=function(){var e=this,t=this.state.isExpanded?s.createElement(w,{icon:ae}):s.createElement(w,{icon:le});return s.createElement("div",{className:"vector3Line"},s.createElement("div",{className:"firstLine"},s.createElement("div",{className:"label",title:this.props.label},this.props.label),s.createElement("div",{className:"vector"},"X: "+this.state.value.x.toFixed(2)+", Y: "+this.state.value.y.toFixed(2)+", Z: "+this.state.value.z.toFixed(2)+", W: "+this.state.value.w.toFixed(2)),s.createElement("div",{className:"expand hoverIcon",onClick:function(){return e.switchExpandState()},title:"Expand"},t)),s.createElement("div",{className:"secondLine"},s.createElement(Ae,{label:"x",step:this.props.step,value:this.state.value.x,onChange:function(t){return e.updateStateX(t)}}),s.createElement(Ae,{label:"y",step:this.props.step,value:this.state.value.y,onChange:function(t){return e.updateStateY(t)}}),s.createElement(Ae,{label:"z",step:this.props.step,value:this.state.value.z,onChange:function(t){return e.updateStateZ(t)}}),s.createElement(Ae,{label:"w",step:this.props.step,value:this.state.value.w,onChange:function(t){return e.updateStateW(t)}})))},t.defaultProps={step:.001},t}(s.Component),yr=r(14),Cr=function(e){function t(t){var r=e.call(this,t)||this;r._localChange=!1;var n=r.props.target[r.props.propertyName],a="Color4"===n.getClassName()?n.clone():new u.Color4(n.r,n.g,n.b,1);return r.state={isExpanded:!1,color:a},t.isLinear&&r.state.color.toGammaSpaceToRef(r.state.color),t.target._isLinearColor=t.isLinear,r}return a(t,e),t.prototype.shouldComponentUpdate=function(e,t){var r=this.props.target[this.props.propertyName],n="Color4"===r.getClassName()?r:new u.Color4(r.r,r.g,r.b,1);return this.props.isLinear&&n.toGammaSpaceRef(n),!(n.equals(t.color)&&!this._localChange)&&(t.color=n.clone(),this._localChange=!1,!0)},t.prototype.setPropertyValue=function(e){this.props.target[this.props.propertyName]=e,this.props.isLinear&&(this.props.target[this.props.propertyName]=e.toLinearSpace())},t.prototype.onChange=function(e){this._localChange=!0;var t=u.Color4.FromHexString(e);this.props.onPropertyChangedObservable&&this.props.onPropertyChangedObservable.notifyObservers({object:this.props.target,property:this.props.propertyName,value:t,initialValue:this.state.color}),this.setPropertyValue(t),this.setState({color:t}),this.props.onChange&&this.props.onChange()},t.prototype.switchExpandState=function(){this._localChange=!0,this.setState({isExpanded:!this.state.isExpanded})},t.prototype.raiseOnPropertyChanged=function(e){this.props.onPropertyChangedObservable&&this.props.onPropertyChangedObservable.notifyObservers({object:this.props.target,property:this.props.propertyName,value:this.state.color,initialValue:e})},t.prototype.updateStateR=function(e){this._localChange=!0;var t=this.state.color.clone();this.state.color.r=e,this.setPropertyValue(this.state.color),this.setState({color:this.state.color}),this.raiseOnPropertyChanged(t)},t.prototype.updateStateG=function(e){this._localChange=!0;var t=this.state.color.clone();this.state.color.g=e,this.setPropertyValue(this.state.color),this.setState({color:this.state.color}),this.raiseOnPropertyChanged(t)},t.prototype.updateStateB=function(e){this._localChange=!0;var t=this.state.color.clone();this.state.color.b=e,this.setPropertyValue(this.state.color),this.setState({color:this.state.color}),this.raiseOnPropertyChanged(t)},t.prototype.updateStateA=function(e){this._localChange=!0;var t=this.state.color.clone();this.props.target[this.props.propertyName].a=e,this.state.color.a=e,this.props.target[this.props.propertyName]=this.state.color,this.setState({color:this.state.color}),this.raiseOnPropertyChanged(t)},t.prototype.copyToClipboard=function(){var e=document.createElement("div");if(e.textContent=this.state.color.toHexString(),document.body.appendChild(e),window.getSelection){var t=document.createRange();t.selectNode(e),window.getSelection().removeAllRanges(),window.getSelection().addRange(t)}document.execCommand("copy"),e.remove()},t.prototype.render=function(){var e=this,t=this.state.isExpanded?s.createElement(w,{icon:ae}):s.createElement(w,{icon:le});return s.createElement("div",{className:"color3Line"},s.createElement("div",{className:"firstLine"},s.createElement("div",{className:"label",title:this.props.label},this.props.label),s.createElement("div",{className:"color3"},s.createElement(Fe,{value:this.state.color,onColorChanged:function(t){e.onChange(t)}})),s.createElement("div",{className:"copy hoverIcon",onClick:function(){return e.copyToClipboard()},title:"Copy to clipboard"},s.createElement("img",{src:yr,alt:""})),s.createElement("div",{className:"expand hoverIcon",onClick:function(){return e.switchExpandState()},title:"Expand"},t)),this.state.isExpanded&&s.createElement("div",{className:"secondLine"},s.createElement(Ae,{label:"r",value:this.state.color.r,onChange:function(t){return e.updateStateR(t)}}),s.createElement(Ae,{label:"g",value:this.state.color.g,onChange:function(t){return e.updateStateG(t)}}),s.createElement(Ae,{label:"b",value:this.state.color.b,onChange:function(t){return e.updateStateB(t)}}),s.createElement(Ae,{label:"a",value:this.state.color.a,onChange:function(t){return e.updateStateA(t)}})))},t}(s.Component),Er=r(51),Or=r(52),Sr=function(e){function t(t){var r=e.call(this,t)||this;return r.state={gradient:t.step.step},r}return a(t,e),t.prototype.updateColor=function(e){this.props.step.color=u.Color3.FromHexString(e),this.props.onUpdateStep(),this.forceUpdate()},t.prototype.updateStep=function(e){this.props.step.step=e,this.setState({gradient:e}),this.props.onUpdateStep()},t.prototype.onPointerUp=function(){this.props.onCheckForReOrder()},t.prototype.render=function(){var e=this,t=this.props.step;return s.createElement("div",{className:"gradient-step"},s.createElement("div",{className:"step"},"#"+this.props.lineIndex),s.createElement("div",{className:"color"},s.createElement(Fe,{value:t.color,onColorChanged:function(t){e.updateColor(t)}})),s.createElement("div",{className:"step-value"},t.step.toFixed(2)),s.createElement("div",{className:"step-slider slider"},s.createElement("input",{className:"range",type:"range",step:.01,min:0,max:1,value:t.step,onPointerUp:function(t){return e.onPointerUp()},onChange:function(t){return e.updateStep(parseFloat(t.target.value))}})),s.createElement("div",{className:"gradient-copy",onClick:function(){e.props.onCopy&&e.props.onCopy()},title:"Copy Step"},s.createElement("img",{className:"img",src:Or})),s.createElement("div",{className:"gradient-delete",onClick:function(){return e.props.onDelete()},title:"Delete Step"},s.createElement("img",{className:"img",src:Er})))},t}(s.Component),xr=function(e){function t(t){var r=e.call(this,t)||this;return r._gradientBlock=r.props.block,r}return a(t,e),t.prototype.forceRebuild=function(){this._gradientBlock.colorStepsUpdated(),this.forceUpdate()},t.prototype.deleteStep=function(e){var t=this._gradientBlock.colorSteps.indexOf(e);t>-1&&(this._gradientBlock.colorSteps.splice(t,1),this.forceRebuild())},t.prototype.copyStep=function(e){var t=this.props.block,r=new u.GradientBlockColorStep(1,e.color);t.colorSteps.push(r),t.colorStepsUpdated(),this.forceRebuild(),this.forceUpdate()},t.prototype.addNewStep=function(){var e=new u.GradientBlockColorStep(1,u.Color3.White());this._gradientBlock.colorSteps.push(e),this.forceRebuild()},t.prototype.checkForReOrder=function(){this._gradientBlock.colorSteps.sort((function(e,t){return e.step-t.step})),this.forceRebuild()},t.prototype.render=function(){var e=this;return s.createElement("div",null,s.createElement(Ye,{label:"Add new step",onClick:function(){return e.addNewStep()}}),this._gradientBlock.colorSteps.map((function(t,r){return s.createElement(Sr,{globalState:e.props.globalState,onCheckForReOrder:function(){return e.checkForReOrder()},onUpdateStep:function(){return e.forceRebuild()},key:"step-"+r,lineIndex:r,step:t,onCopy:function(){return e.copyStep(t)},onDelete:function(){return e.deleteStep(t)}})})))},t}(s.Component),Pr=function(e){function t(t){var r=e.call(this,t)||this;return r._onDebugSelectionChangeObservable=new u.Observable,r}return a(t,e),t.prototype.edit=function(){this.props.material.edit()},t.prototype.renderTextures=function(){var e=this,t=this.props.material,r=this._onDebugSelectionChangeObservable,n=t.getTextureBlocks();return n&&0!==n.length?s.createElement(Ee,{globalState:this.props.globalState,title:"TEXTURES"},n.map((function(n,a){return s.createElement(qe,{label:n.name,key:"nodematText"+a,texture:n.texture,material:t,onTextureCreated:function(e){return n.texture=e},onSelectionChangedObservable:e.props.onSelectionChangedObservable,onDebugSelectionChangeObservable:r})}))):null},t.prototype.renderInputBlock=function(e){switch(e.type){case u.NodeMaterialBlockConnectionPointTypes.Float:var t=isNaN(e.min)||isNaN(e.max)||e.min===e.max;return s.createElement("div",{key:e.name},e.isBoolean&&s.createElement(Pe,{key:e.name,label:e.name,target:e,propertyName:"value",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),!e.isBoolean&&t&&s.createElement(Me,{key:e.name,lockObject:this.props.lockObject,label:e.name,target:e,propertyName:"value",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),!e.isBoolean&&!t&&s.createElement(Le,{key:e.name,label:e.name,target:e,propertyName:"value",step:(e.max-e.min)/100,minimum:e.min,maximum:e.max,onPropertyChangedObservable:this.props.onPropertyChangedObservable}));case u.NodeMaterialBlockConnectionPointTypes.Color3:return s.createElement(Ve,{key:e.name,label:e.name,target:e,propertyName:"value",onPropertyChangedObservable:this.props.onPropertyChangedObservable});case u.NodeMaterialBlockConnectionPointTypes.Color4:return s.createElement(Cr,{key:e.name,label:e.name,target:e,propertyName:"value",onPropertyChangedObservable:this.props.onPropertyChangedObservable});case u.NodeMaterialBlockConnectionPointTypes.Vector2:return s.createElement(St,{key:e.name,label:e.name,target:e,propertyName:"value",onPropertyChangedObservable:this.props.onPropertyChangedObservable});case u.NodeMaterialBlockConnectionPointTypes.Vector3:return s.createElement(Ue,{key:e.name,label:e.name,target:e,propertyName:"value",onPropertyChangedObservable:this.props.onPropertyChangedObservable});case u.NodeMaterialBlockConnectionPointTypes.Vector4:return s.createElement(vr,{key:e.name,label:e.name,target:e,propertyName:"value",onPropertyChangedObservable:this.props.onPropertyChangedObservable})}return null},t.prototype.renderInputValues=function(){var e=this,t=this.props.material.getInputBlocks().filter((function(e){return e.visibleInInspector&&e.isUniform&&!e.isSystemValue})).sort((function(e,t){return e.name.localeCompare(t.name)})),r=[];t.forEach((function(e){e.groupInInspector&&-1===r.indexOf(e.groupInInspector)&&r.push(e.groupInInspector)})),r.sort();var n=this.props.material.attachedBlocks.filter((function(e){return e.visibleInInspector&&"GradientBlock"===e.getClassName()})).sort((function(e,t){return e.name.localeCompare(t.name)})),a=t.length>0?s.createElement(Ee,{globalState:this.props.globalState,title:"INPUTS"}," ",t.filter((function(e){return!e.groupInInspector})).map((function(t){return e.renderInputBlock(t)}))):null;return s.createElement(s.Fragment,null,a,r.map((function(r,n){return s.createElement(Ee,{key:"inputValue"+n,globalState:e.props.globalState,title:r.toUpperCase()},t.filter((function(e){return e.groupInInspector===r})).map((function(t){return e.renderInputBlock(t)})))})),n.map((function(t,r){return s.createElement(Ee,{key:t.name+r,globalState:e.props.globalState,title:t.name.toUpperCase()},s.createElement(xr,{globalState:e.props.globalState,block:t}))})))},t.prototype.render=function(){var e=this,t=this.props.material;return s.createElement("div",{className:"pane"},s.createElement(Ke,{globalState:this.props.globalState,lockObject:this.props.lockObject,material:t,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"CONFIGURATION"},s.createElement(Pe,{label:"Ignore alpha",target:t,propertyName:"ignoreAlpha",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ye,{label:"Node Material Editor",onClick:function(){return e.edit()}})),this.renderInputValues(),this.renderTextures())},t}(s.Component),wr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.onMaterialLink=function(e){this.props.onSelectionChangedObservable&&this.props.onSelectionChangedObservable.notifyObservers(e)},t.prototype.renderChildMaterial=function(){var e=this,t=this.props.material;return s.createElement(Ee,{globalState:this.props.globalState,title:"CHILDREN"},t.subMaterials.map((function(t,r){return t?s.createElement(Ce,{key:"Material #"+r,label:"Material #"+r,value:t.name,onLink:function(){return e.onMaterialLink(t)}}):null})))},t.prototype.render=function(){var e=this.props.material;return s.createElement("div",{className:"pane"},s.createElement(Ke,{globalState:this.props.globalState,lockObject:this.props.lockObject,material:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),this.renderChildMaterial())},t}(s.Component),kr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.emitter;return s.createElement(s.Fragment,null,s.createElement(Ue,{label:"Direction 1",target:e,propertyName:"direction1",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Direction 2",target:e,propertyName:"direction2",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Min emit box",target:e,propertyName:"minEmitBox",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Max emit box",target:e,propertyName:"maxEmitBox",onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t}(s.Component),Nr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.emitter;return s.createElement(s.Fragment,null,s.createElement(Le,{label:"Radius range",target:e,propertyName:"radiusRange",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Height range",target:e,propertyName:"heightRange",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Emit from spawn point only",target:e,propertyName:"emitFromSpawnPointOnly",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Direction randomizer",target:e,propertyName:"directionRandomizer",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t}(s.Component),Tr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.emitter;return s.createElement(s.Fragment,null,s.createElement(Me,{lockObject:this.props.lockObject,label:"Radius",target:e,propertyName:"radius",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Height",target:e,propertyName:"height",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Radius range",target:e,propertyName:"radiusRange",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Direction randomizer",target:e,propertyName:"directionRandomizer",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t}(s.Component),_r=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.emitter;return s.createElement(s.Fragment,null,s.createElement(Me,{lockObject:this.props.lockObject,label:"Radius",target:e,propertyName:"radius",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Radius range",target:e,propertyName:"radiusRange",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Direction randomizer",target:e,propertyName:"directionRandomizer",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t}(s.Component),Mr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.emitter;return s.createElement(s.Fragment,null,s.createElement(Ue,{label:"Direction 1",target:e,propertyName:"direction1",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Direction 2",target:e,propertyName:"direction2",onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t}(s.Component),Lr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.emitter;return s.createElement(s.Fragment,null,s.createElement(Me,{lockObject:this.props.lockObject,label:"Radius",target:e,propertyName:"radius",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Radius range",target:e,propertyName:"radiusRange",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Direction randomizer",target:e,propertyName:"directionRandomizer",minimum:0,maximum:1,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t}(s.Component),Dr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this,t=this.props.scene.meshes.filter((function(e){return!!e.name}));t.sort((function(e,t){return e.name.localeCompare(t.name)}));var r=[{label:"None",value:-1}];return t.sort((function(e,t){return e.name.localeCompare(t.name)})),r.push.apply(r,t.map((function(e,t){return{label:e.name,value:t}}))),s.createElement(s.Fragment,null,s.createElement(Re,{label:this.props.label,options:r,target:this.props.target,propertyName:this.props.property,noDirectUpdate:!0,onSelect:function(r){var n=e.props.target[e.props.property];switch(r){case-1:e.props.target[e.props.property]=null;break;default:e.props.target[e.props.property]=t[r]}e.props.onPropertyChangedObservable&&e.props.onPropertyChangedObservable.notifyObservers({object:e.props.target,property:e.props.property,value:e.props.target[e.props.property],initialValue:n}),e.forceUpdate()},extractValue:function(){if(!e.props.target[e.props.property])return-1;var r=t.indexOf(e.props.target[e.props.property]);return r>-1?r:-1}}))},t}(s.Component),Rr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.emitter;return s.createElement(s.Fragment,null,s.createElement(Dr,{globalState:this.props.globalState,label:"Source",scene:this.props.scene,onPropertyChangedObservable:this.props.onPropertyChangedObservable,target:this.props.emitter,property:"mesh"}),!e.useMeshNormalsForDirection&&s.createElement(Ue,{label:"Direction 1",target:e,propertyName:"direction1",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),!e.useMeshNormalsForDirection&&s.createElement(Ue,{label:"Direction 2",target:e,propertyName:"direction2",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Use normals for direction",target:e,propertyName:"useMeshNormalsForDirection",onPropertyChangedObservable:this.props.onPropertyChangedObservable}))},t}(s.Component),Ar=function(e){function t(t){var r,n=e.call(this,t)||this;return n.state={gradient:t.gradient.gradient,factor1:n.props.gradient.factor1.toString(),factor2:null===(r=n.props.gradient.factor2)||void 0===r?void 0:r.toString()},n}return a(t,e),t.prototype.shouldComponentUpdate=function(e,t){var r;return e.gradient!==this.props.gradient&&(t.gradient=e.gradient.gradient,t.factor1=e.gradient.factor1.toString(),t.factor2=null===(r=e.gradient.factor2)||void 0===r?void 0:r.toString()),!0},t.prototype.updateFactor1=function(e){if(!/[^0-9\.\-]/g.test(e)){var t=parseFloat(e);this.setState({factor1:e}),isNaN(t)||(this.props.gradient.factor1=t,this.props.onUpdateGradient(),this.forceUpdate())}},t.prototype.updateFactor2=function(e){if(!/[^0-9\.\-]/g.test(e)){var t=parseFloat(e);this.setState({factor2:e}),isNaN(t)||(this.props.gradient.factor2=t,this.props.onUpdateGradient(),this.forceUpdate())}},t.prototype.updateGradient=function(e){this.props.gradient.gradient=e,this.setState({gradient:e}),this.props.onUpdateGradient()},t.prototype.onPointerUp=function(){this.props.onCheckForReOrder()},t.prototype.lock=function(){this.props.lockObject&&(this.props.lockObject.lock=!0)},t.prototype.unlock=function(){this.props.lockObject&&(this.props.lockObject.lock=!1)},t.prototype.render=function(){var e=this,t=this.props.gradient;return s.createElement("div",{className:"gradient-step"},s.createElement("div",{className:"step"},"#"+this.props.lineIndex),s.createElement("div",{className:"factor1"},s.createElement("input",{type:"number",step:"0.01",className:"numeric-input",value:this.state.factor1,onBlur:function(){return e.unlock()},onFocus:function(){return e.lock()},onChange:function(t){return e.updateFactor1(t.target.value)}})),this.props.host instanceof u.ParticleSystem&&s.createElement("div",{className:"factor2"},s.createElement("input",{type:"number",step:"0.01",className:"numeric-input"+(this.state.factor1===this.state.factor2||void 0===t.factor2?" grayed":""),value:this.state.factor2,onBlur:function(){return e.unlock()},onFocus:function(){return e.lock()},onChange:function(t){return e.updateFactor2(t.target.value)}})),s.createElement("div",{className:"step-value"},t.gradient.toFixed(2)),s.createElement("div",{className:"step-slider"},s.createElement("input",{className:"range",type:"range",step:.01,min:0,max:1,value:t.gradient,onPointerUp:function(t){return e.onPointerUp()},onChange:function(t){return e.updateGradient(parseFloat(t.target.value))}})),s.createElement("div",{className:"gradient-delete hoverIcon",onClick:function(){return e.props.onDelete()}},s.createElement(w,{icon:be})))},t}(s.Component),Ir=function(e){function t(t){var r=e.call(this,t)||this;return r.state={gradient:t.gradient.gradient},r}return a(t,e),t.prototype.updateColor1=function(e){this.props.gradient instanceof u.ColorGradient?this.props.gradient.color1=u.Color4.FromHexString(e):this.props.gradient.color=u.Color3.FromHexString(e),this.props.onUpdateGradient(),this.forceUpdate()},t.prototype.updateColor2=function(e){this.props.gradient instanceof u.ColorGradient&&(this.props.gradient.color2=u.Color4.FromHexString(e)),this.props.onUpdateGradient(),this.forceUpdate()},t.prototype.updateGradient=function(e){this.props.gradient.gradient=e,this.setState({gradient:e}),this.props.onUpdateGradient()},t.prototype.onPointerUp=function(){this.props.onCheckForReOrder()},t.prototype.lock=function(){this.props.lockObject&&(this.props.lockObject.lock=!0)},t.prototype.unlock=function(){this.props.lockObject&&(this.props.lockObject.lock=!1)},t.prototype.render=function(){var e=this,t=this.props.gradient;return s.createElement("div",{className:"gradient-step"},s.createElement("div",{className:"step"},"#"+this.props.lineIndex),s.createElement("div",{className:"color1"},s.createElement(Fe,{value:t instanceof u.Color3Gradient?t.color:t.color1,onColorChanged:function(t){e.updateColor1(t)}})),this.props.host instanceof u.ParticleSystem&&t instanceof u.ColorGradient&&s.createElement("div",{className:"color2"},s.createElement(Fe,{value:t.color2?t.color2:new u.Color4,onColorChanged:function(t){e.updateColor2(t)}})),s.createElement("div",{className:"step-value"},t.gradient.toFixed(2)),s.createElement("div",{className:"step-slider"},s.createElement("input",{className:"range",type:"range",step:.01,min:0,max:1,value:t.gradient,onPointerUp:function(t){return e.onPointerUp()},onChange:function(t){return e.updateGradient(parseFloat(t.target.value))}})),s.createElement("div",{className:"gradient-delete hoverIcon",onClick:function(){return e.props.onDelete()}},s.createElement(w,{icon:be})))},t}(s.Component),jr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.onLink=function(){this.props.url&&window.open(this.props.url,"_blank")},t.prototype.render=function(){var e=this;return s.createElement("div",{className:"linkButtonLine"},s.createElement("div",{className:"link",title:this.props.label,onClick:function(){return e.onLink()}},this.props.label),s.createElement("div",{className:"link-button"},s.createElement("button",{onClick:function(){return e.props.onClick()}},this.props.buttonLabel)),this.props.icon&&s.createElement("div",{className:"link-icon hoverIcon",onClick:function(){e.props.onIconClick&&e.props.onIconClick()}},s.createElement(w,{icon:this.props.icon})))},t}(s.Component);!function(e){e[e.Factor=0]="Factor",e[e.Color3=1]="Color3",e[e.Color4=2]="Color4"}(Ct||(Ct={}));var zr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.deleteStep=function(e){var t=this.props.gradients,r=t.indexOf(e);r>-1&&(t.splice(r,1),this.updateAndSync())},t.prototype.addNewStep=function(){var e=this.props.gradients;switch(this.props.mode){case Ct.Factor:var t=new u.FactorGradient(1,1,1);e.push(t);break;case Ct.Color4:var r=new u.ColorGradient(1,new u.Color4(1,1,1,1),new u.Color4(1,1,1,1));e.push(r);break;case Ct.Color3:var n=new u.Color3Gradient(1,u.Color3.White());e.push(n)}this.props.host.forceRefreshGradients(),this.forceUpdate()},t.prototype.checkForReOrder=function(){this.props.gradients.sort((function(e,t){return e.gradient===t.gradient?0:e.gradient>t.gradient?1:-1})),this.forceUpdate()},t.prototype.updateAndSync=function(){this.props.host.forceRefreshGradients(),this.forceUpdate()},t.prototype.render=function(){var e=this,t=this.props.gradients;return s.createElement("div",null,t&&t.length>0&&s.createElement("div",{className:"gradient-container"},s.createElement(jr,{label:this.props.label,url:this.props.docLink,icon:be,onIconClick:function(){t.length=0,e.updateAndSync()},buttonLabel:"Add new step",onClick:function(){return e.addNewStep()}}),t.map((function(t,r){var n=e.props.codeRecorderPropertyName+"["+r+"]";switch(e.props.mode){case Ct.Factor:return s.createElement(Ar,{globalState:e.props.globalState,lockObject:e.props.lockObject,onCheckForReOrder:function(){return e.checkForReOrder()},onUpdateGradient:function(){return e.updateAndSync()},host:e.props.host,codeRecorderPropertyName:n,key:"step-"+r,lineIndex:r,gradient:t,onDelete:function(){return e.deleteStep(t)}});case Ct.Color4:return s.createElement(Ir,{globalState:e.props.globalState,host:e.props.host,codeRecorderPropertyName:n,lockObject:e.props.lockObject,isColor3:!1,onCheckForReOrder:function(){return e.checkForReOrder()},onUpdateGradient:function(){return e.updateAndSync()},key:"step-"+r,lineIndex:r,gradient:t,onDelete:function(){return e.deleteStep(t)}});case Ct.Color3:return s.createElement(Ir,{globalState:e.props.globalState,host:e.props.host,codeRecorderPropertyName:n,lockObject:e.props.lockObject,isColor3:!0,onCheckForReOrder:function(){return e.checkForReOrder()},onUpdateGradient:function(){return e.updateAndSync()},key:"step-"+r,lineIndex:r,gradient:t,onDelete:function(){return e.deleteStep(t)}})}}))),(!t||0===t.length)&&s.createElement(Ye,{label:"Use "+this.props.label,onClick:function(){e.props.onCreateRequired(),e.forceUpdate()}}))},t}(s.Component),Fr=function(e){function t(t){var r=e.call(this,t)||this;return r._snippetUrl="https://snippet.babylonjs.com",r}return a(t,e),t.prototype.renderEmitter=function(){var e,t=this.props.system;switch(null===(e=t.particleEmitterType)||void 0===e?void 0:e.getClassName()){case"BoxParticleEmitter":return s.createElement(kr,{globalState:this.props.globalState,emitter:t.particleEmitterType,onPropertyChangedObservable:this.props.onPropertyChangedObservable});case"ConeParticleEmitter":return s.createElement(Nr,{globalState:this.props.globalState,emitter:t.particleEmitterType,onPropertyChangedObservable:this.props.onPropertyChangedObservable});case"CylinderParticleEmitter":return s.createElement(Tr,{lockObject:this.props.lockObject,globalState:this.props.globalState,emitter:t.particleEmitterType,onPropertyChangedObservable:this.props.onPropertyChangedObservable});case"HemisphericParticleEmitter":return s.createElement(_r,{lockObject:this.props.lockObject,globalState:this.props.globalState,emitter:t.particleEmitterType,onPropertyChangedObservable:this.props.onPropertyChangedObservable});case"MeshParticleEmitter":return s.createElement(Rr,{lockObject:this.props.lockObject,scene:t.getScene(),globalState:this.props.globalState,emitter:t.particleEmitterType,onPropertyChangedObservable:this.props.onPropertyChangedObservable});case"PointParticleEmitter":return s.createElement(Mr,{lockObject:this.props.lockObject,globalState:this.props.globalState,emitter:t.particleEmitterType,onPropertyChangedObservable:this.props.onPropertyChangedObservable});case"SphereParticleEmitter":return s.createElement(Lr,{lockObject:this.props.lockObject,globalState:this.props.globalState,emitter:t.particleEmitterType,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}return null},t.prototype.raiseOnPropertyChanged=function(e,t,r){if(this.props.onPropertyChangedObservable){var n=this.props.system;this.props.onPropertyChangedObservable.notifyObservers({object:n,property:e,value:t,initialValue:r})}},t.prototype.renderControls=function(){var e=this,t=this.props.system;if(t instanceof u.GPUParticleSystem){var r=t.isStarted()&&!t.isStopped();return s.createElement(Ye,{label:r?"Stop":"Start",onClick:function(){r?(t.stop(),t.reset()):t.start(),e.forceUpdate()}})}var n=t.isStarted();return s.createElement(s.Fragment,null,!t.isStopping()&&s.createElement(Ye,{label:n?"Stop":"Start",onClick:function(){n?t.stop():t.start(),e.forceUpdate()}}),t.isStopping()&&s.createElement(Ce,{label:"System is stoppping...",ignoreValue:!0}))},t.prototype.saveToFile=function(){var e=this.props.system,t=JSON.stringify(e.serialize(!0));u.Tools.Download(new Blob([t]),"particleSystem.json")},t.prototype.loadFromFile=function(e){var t=this,r=this.props.system,n=r.getScene();n&&u.Tools.ReadFile(e,(function(e){var a=new TextDecoder("utf-8"),o=JSON.parse(a.decode(e)),i=r instanceof u.GPUParticleSystem;r.dispose(),t.props.globalState.onSelectionChangedObservable.notifyObservers(null);var l=i?u.GPUParticleSystem.Parse(o,n,""):u.ParticleSystem.Parse(o,n,"");t.props.globalState.onSelectionChangedObservable.notifyObservers(l)}),void 0,!0)},t.prototype.loadFromSnippet=function(){var e=this,t=this.props.system,r=t.getScene(),n=t instanceof u.GPUParticleSystem,a=window.prompt("Please enter the snippet ID to use");a&&r&&(t.dispose(),this.props.globalState.onSelectionChangedObservable.notifyObservers(null),u.ParticleHelper.CreateFromSnippetAsync(a,r,n).then((function(t){e.props.globalState.onSelectionChangedObservable.notifyObservers(t)})).catch((function(e){alert("Unable to load your particle system: "+e)})))},t.prototype.saveToSnippet=function(){var e=this,t=this.props.system,r=JSON.stringify(t.serialize(!0)),n=new XMLHttpRequest;n.onreadystatechange=function(){if(4==n.readyState)if(200==n.status){var r=JSON.parse(n.responseText),a=t.snippetId||"_BLANK";t.snippetId=r.id,r.version&&"0"!=r.version&&(t.snippetId+="#"+r.version),e.forceUpdate(),navigator.clipboard&&navigator.clipboard.writeText(t.snippetId);var o=window;o.Playground&&a&&o.Playground.onRequestCodeChangeObservable.notifyObservers({regex:new RegExp('ParticleHelper.CreateFromSnippetAsync\\("'+a,"g"),replace:'ParticleHelper.CreateFromSnippetAsync("'+t.snippetId}),alert("Particle system saved with ID: "+t.snippetId+" (please note that the id was also saved to your clipboard)")}else alert("Unable to save your particle system")},n.open("POST",this._snippetUrl+(t.snippetId?"/"+t.snippetId:""),!0),n.setRequestHeader("Content-Type","application/json");var a={payload:JSON.stringify({particleSystem:r}),name:"",description:"",tags:""};n.send(JSON.stringify(a))},t.prototype.render=function(){var e,t,r=this,n=this.props.system,a=[{label:"Add",value:u.ParticleSystem.BLENDMODE_ADD},{label:"Multiply",value:u.ParticleSystem.BLENDMODE_MULTIPLY},{label:"Multiply Add",value:u.ParticleSystem.BLENDMODE_MULTIPLYADD},{label:"OneOne",value:u.ParticleSystem.BLENDMODE_ONEONE},{label:"Standard",value:u.ParticleSystem.BLENDMODE_STANDARD}],o=this.props.system.getScene().meshes.filter((function(e){return!!e.name})),i=[{label:"None",value:-1},{label:"Vector3",value:0}];return o.sort((function(e,t){return e.name.localeCompare(t.name)})),i.push.apply(i,o.map((function(e,t){return{label:e.name,value:t+1}}))),s.createElement("div",{className:"pane"},s.createElement(We,{globalState:this.props.globalState,target:n,lockObject:this.props.lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Ce,{label:"ID",value:n.id}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Name",target:n,propertyName:"name",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ce,{label:"Class",value:n.getClassName()}),s.createElement(Ce,{label:"Capacity",value:n.getCapacity().toString()}),s.createElement(Ce,{label:"Active count",value:n.getActiveCount().toString()}),s.createElement(qe,{label:"Texture",texture:n.particleTexture,onSelectionChangedObservable:this.props.onSelectionChangedObservable}),s.createElement(Re,{label:"Blend mode",options:a,target:n,propertyName:"blendMode",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"World offset",target:n,propertyName:"worldOffset",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ue,{label:"Gravity",target:n,propertyName:"gravity",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Is billboard",target:n,propertyName:"isBillboardBased",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Is local",target:n,propertyName:"isLocal",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Force depth write",target:n,propertyName:"forceDepthWrite",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Update speed",target:n,propertyName:"updateSpeed",minimum:0,maximum:.1,decimalCount:3,step:.001,onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"COMMANDS"},this.renderControls(),s.createElement(Ye,{label:"Dispose",onClick:function(){r.props.globalState.onSelectionChangedObservable.notifyObservers(null),n.dispose()}})),s.createElement(Ee,{globalState:this.props.globalState,title:"FILE"},s.createElement(Qe,{label:"Load",onClick:function(e){return r.loadFromFile(e)},accept:".json"}),s.createElement(Ye,{label:"Save",onClick:function(){return r.saveToFile()}})),s.createElement(Ee,{globalState:this.props.globalState,title:"SNIPPET"},n.snippetId&&s.createElement(Ce,{label:"Snippet ID",value:n.snippetId}),s.createElement(Ye,{label:"Load from snippet server",onClick:function(){return r.loadFromSnippet()}}),s.createElement(Ye,{label:"Save to snippet server",onClick:function(){return r.saveToSnippet()}})),s.createElement(Ee,{globalState:this.props.globalState,title:"EMITTER",closed:!0},s.createElement(Re,{label:"Emitter",options:i,target:n,propertyName:"emitter",noDirectUpdate:!0,onSelect:function(e){switch(e){case-1:r.raiseOnPropertyChanged("emitter",null,n.emitter),n.emitter=null;break;case 0:r.raiseOnPropertyChanged("emitter",u.Vector3.Zero(),n.emitter),n.emitter=u.Vector3.Zero();break;default:r.raiseOnPropertyChanged("emitter",o[e-1],n.emitter),n.emitter=o[e-1]}r.forceUpdate()},extractValue:function(){if(!n.emitter)return-1;if(void 0!==n.emitter.x)return 0;var e=o.indexOf(n.emitter);return e>-1?e+1:-1}}),n.emitter&&void 0===n.emitter.x&&s.createElement(Ce,{label:"Link to emitter",value:n.emitter.name,onLink:function(){return r.props.globalState.onSelectionChangedObservable.notifyObservers(n.emitter)}}),n.emitter&&void 0!==n.emitter.x&&s.createElement(Ue,{label:"Position",target:n,propertyName:"emitter",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Type",options:[{label:"Box",value:0},{label:"Cone",value:1},{label:"Cylinder",value:2},{label:"Hemispheric",value:3},{label:"Mesh",value:4},{label:"Point",value:5},{label:"Sphere",value:6}],target:n,propertyName:"particleEmitterType",noDirectUpdate:!0,onSelect:function(e){var t=n.particleEmitterType;switch(e){case 0:n.particleEmitterType=new u.BoxParticleEmitter;break;case 1:n.particleEmitterType=new u.ConeParticleEmitter;break;case 2:n.particleEmitterType=new u.CylinderParticleEmitter;break;case 3:n.particleEmitterType=new u.HemisphericParticleEmitter;break;case 4:n.particleEmitterType=new u.MeshParticleEmitter;break;case 5:n.particleEmitterType=new u.PointParticleEmitter;break;case 6:n.particleEmitterType=new u.SphereParticleEmitter}r.raiseOnPropertyChanged("particleEmitterType",n.particleEmitterType,t),r.forceUpdate()},extractValue:function(){var e;switch(null===(e=n.particleEmitterType)||void 0===e?void 0:e.getClassName()){case"BoxParticleEmitter":return 0;case"ConeParticleEmitter":return 1;case"CylinderParticleEmitter":return 2;case"HemisphericParticleEmitter":return 3;case"MeshParticleEmitter":return 4;case"PointParticleEmitter":return 5;case"SphereParticleEmitter":return 6}return 0}}),this.renderEmitter()),s.createElement(Ee,{globalState:this.props.globalState,title:"EMISSION",closed:!0},s.createElement(Me,{lockObject:this.props.lockObject,label:"Rate",target:n,propertyName:"emitRate",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),n instanceof u.ParticleSystem&&s.createElement(zr,{globalState:this.props.globalState,gradients:n.getEmitRateGradients(),label:"Velocity gradients",docLink:"https://doc.babylonjs.com/babylon101/particles#emit-rate-over-time",onCreateRequired:function(){n.addEmitRateGradient(0,50,50)},mode:Ct.Factor,host:n,codeRecorderPropertyName:"getEmitRateGradients()",lockObject:this.props.lockObject}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Min emit power",target:n,propertyName:"minEmitPower",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Max emit power",target:n,propertyName:"maxEmitPower",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(zr,{globalState:this.props.globalState,gradients:n.getVelocityGradients(),label:"Velocity gradients",docLink:"https://doc.babylonjs.com/babylon101/particles#velocity-over-time",onCreateRequired:function(){n.addVelocityGradient(0,.1,.1)},mode:Ct.Factor,host:n,codeRecorderPropertyName:"getVelocityGradients()",lockObject:this.props.lockObject}),s.createElement(zr,{globalState:this.props.globalState,gradients:n.getLimitVelocityGradients(),label:"Limit velocity gradients",docLink:"https://doc.babylonjs.com/babylon101/particles#limit-velocity-over-time",onCreateRequired:function(){n.addLimitVelocityGradient(0,.1,.1)},mode:Ct.Factor,host:n,codeRecorderPropertyName:"getLimitVelocityGradients()",lockObject:this.props.lockObject}),s.createElement(zr,{globalState:this.props.globalState,gradients:n.getDragGradients(),label:"Drag gradients",docLink:"https://doc.babylonjs.com/babylon101/particles#drag-factor",onCreateRequired:function(){n.addDragGradient(0,.1,.1)},host:n,codeRecorderPropertyName:"getDragGradients()",mode:Ct.Factor,lockObject:this.props.lockObject})),s.createElement(Ee,{globalState:this.props.globalState,title:"SIZE",closed:!0},(!n.getSizeGradients()||0===(null===(e=n.getSizeGradients())||void 0===e?void 0:e.length))&&s.createElement(s.Fragment,null,s.createElement(Me,{lockObject:this.props.lockObject,label:"Min size",target:n,propertyName:"minSize",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Max size",target:n,propertyName:"maxSize",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Me,{lockObject:this.props.lockObject,label:"Min scale X",target:n,propertyName:"minScaleX",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Max scale X",target:n,propertyName:"maxScaleX",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Min scale Y",target:n,propertyName:"minScaleY",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Max scale Y",target:n,propertyName:"maxScaleY",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),n instanceof u.ParticleSystem&&s.createElement(zr,{globalState:this.props.globalState,gradients:n.getStartSizeGradients(),label:"Start size gradients",docLink:"https://doc.babylonjs.com/babylon101/particles#start-size-over-time",onCreateRequired:function(){n.addStartSizeGradient(0,1,1)},host:n,codeRecorderPropertyName:"getStartSizeGradients()",mode:Ct.Factor,lockObject:this.props.lockObject}),s.createElement(zr,{globalState:this.props.globalState,gradients:n.getSizeGradients(),label:"Size gradients",docLink:"https://doc.babylonjs.com/babylon101/particles#size",onCreateRequired:function(){n.addSizeGradient(0,1,1)},host:n,codeRecorderPropertyName:"getSizeGradients()",mode:Ct.Factor,lockObject:this.props.lockObject})),s.createElement(Ee,{globalState:this.props.globalState,title:"LIFETIME",closed:!0},s.createElement(Me,{lockObject:this.props.lockObject,label:"Min lifetime",target:n,propertyName:"minLifeTime",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Max lifetime",target:n,propertyName:"maxLifeTime",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Target stop duration",target:n,propertyName:"targetStopDuration",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),n instanceof u.ParticleSystem&&s.createElement(zr,{globalState:this.props.globalState,gradients:n.getLifeTimeGradients(),label:"Lifetime gradients",docLink:"https://doc.babylonjs.com/babylon101/particles#lifetime",onCreateRequired:function(){n.addLifeTimeGradient(0,1,1)},host:n,codeRecorderPropertyName:"getLifeTimeGradients()",mode:Ct.Factor,lockObject:this.props.lockObject})),s.createElement(Ee,{globalState:this.props.globalState,title:"COLORS",closed:!0},(!n.getColorGradients()||0===(null===(t=n.getColorGradients())||void 0===t?void 0:t.length))&&s.createElement(s.Fragment,null,s.createElement(Cr,{label:"Color 1",target:n,propertyName:"color1",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Cr,{label:"Color 2",target:n,propertyName:"color2",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Cr,{label:"Color dead",target:n,propertyName:"colorDead",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(zr,{globalState:this.props.globalState,gradients:n.getColorGradients(),label:"Color gradients",docLink:"https://doc.babylonjs.com/babylon101/particles#particle-colors",onCreateRequired:function(){n.addColorGradient(0,new u.Color4(0,0,0,1),new u.Color4(0,0,0,1)),n.addColorGradient(1,new u.Color4(1,1,1,1),new u.Color4(1,1,1,1))},host:n,codeRecorderPropertyName:"getColorGradients()",mode:Ct.Color4,lockObject:this.props.lockObject}),n instanceof u.ParticleSystem&&s.createElement(s.Fragment,null,s.createElement(Pe,{label:"Enable ramp grandients",target:n,propertyName:"useRampGradients"}),n.useRampGradients&&s.createElement(s.Fragment,null,s.createElement(zr,{globalState:this.props.globalState,gradients:n.getRampGradients(),label:"Ramp gradients",docLink:"https://doc.babylonjs.com/babylon101/particles#ramp-gradients",onCreateRequired:function(){n.addRampGradient(0,u.Color3.White()),n.addRampGradient(1,u.Color3.Black())},mode:Ct.Color3,host:n,codeRecorderPropertyName:"getRampGradients()",lockObject:this.props.lockObject}),s.createElement(zr,{globalState:this.props.globalState,gradients:n.getColorRemapGradients(),label:"Color remap gradients",docLink:"https://doc.babylonjs.com/babylon101/particles#ramp-gradients",onCreateRequired:function(){n.addColorRemapGradient(0,1,1)},host:n,codeRecorderPropertyName:"getColorRemapGradients()",mode:Ct.Factor,lockObject:this.props.lockObject}),s.createElement(zr,{globalState:this.props.globalState,gradients:n.getAlphaRemapGradients(),label:"Alpha remap gradients",docLink:"https://doc.babylonjs.com/babylon101/particles#ramp-gradients",onCreateRequired:function(){n.addAlphaRemapGradient(0,1,1)},host:n,codeRecorderPropertyName:"getAlphaRemapGradients()",mode:Ct.Factor,lockObject:this.props.lockObject})))),s.createElement(Ee,{globalState:this.props.globalState,title:"ROTATION",closed:!0},s.createElement(Me,{lockObject:this.props.lockObject,label:"Min angular speed",target:n,propertyName:"minAngularSpeed",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Max angular speed",target:n,propertyName:"maxAngularSpeed",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Min initial rotation",target:n,propertyName:"minInitialRotation",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Max initial rotation",target:n,propertyName:"maxInitialRotation",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(zr,{globalState:this.props.globalState,gradients:n.getAngularSpeedGradients(),label:"Angular speed gradients",docLink:"hhttps://doc.babylonjs.com/babylon101/particles#rotation",onCreateRequired:function(){n.addAngularSpeedGradient(0,.1,.1)},host:n,codeRecorderPropertyName:"getAngularSpeedGradients()",mode:Ct.Factor,lockObject:this.props.lockObject})),s.createElement(Ee,{globalState:this.props.globalState,title:"SPRITESHEET",closed:!0},s.createElement(Pe,{label:"Animation sheet enabled",target:n,propertyName:"isAnimationSheetEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{label:"First sprite index",isInteger:!0,target:n,propertyName:"startSpriteCellID",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{label:"Last sprite index",isInteger:!0,target:n,propertyName:"endSpriteCellID",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Random start cell index",target:n,propertyName:"spriteRandomStartCell",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{label:"Cell width",isInteger:!0,target:n,propertyName:"spriteCellWidth",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{label:"Cell height",isInteger:!0,target:n,propertyName:"spriteCellHeight",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Cell change speed",target:n,propertyName:"spriteCellChangeSpeed",minimum:0,maximum:10,step:.1,onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),Gr=function(e){function t(t){var r=e.call(this,t)||this;return r._snippetUrl="https://snippet.babylonjs.com",r}return a(t,e),t.prototype.addNewSprite=function(){var e,t=this.props.spriteManager,r=new u.Sprite("new sprite",t);null===(e=this.props.onSelectionChangedObservable)||void 0===e||e.notifyObservers(r)},t.prototype.disposeManager=function(){var e;this.props.spriteManager.dispose(),null===(e=this.props.onSelectionChangedObservable)||void 0===e||e.notifyObservers(null)},t.prototype.saveToFile=function(){var e=this.props.spriteManager,t=JSON.stringify(e.serialize(!0));u.Tools.Download(new Blob([t]),"spriteManager.json")},t.prototype.loadFromFile=function(e){var t=this,r=this.props.spriteManager,n=r.scene;u.Tools.ReadFile(e,(function(e){var a=new TextDecoder("utf-8"),o=JSON.parse(a.decode(e));r.dispose(),t.props.globalState.onSelectionChangedObservable.notifyObservers(null);var i=u.SpriteManager.Parse(o,n,"");t.props.globalState.onSelectionChangedObservable.notifyObservers(i)}),void 0,!0)},t.prototype.loadFromSnippet=function(){var e=this,t=this.props.spriteManager,r=t.scene,n=window.prompt("Please enter the snippet ID to use");n&&(t.dispose(),this.props.globalState.onSelectionChangedObservable.notifyObservers(null),u.SpriteManager.CreateFromSnippetAsync(n,r).then((function(t){e.props.globalState.onSelectionChangedObservable.notifyObservers(t)})).catch((function(e){alert("Unable to load your sprite manager: "+e)})))},t.prototype.saveToSnippet=function(){var e=this,t=this.props.spriteManager,r=JSON.stringify(t.serialize(!0)),n=new XMLHttpRequest;n.onreadystatechange=function(){if(4==n.readyState)if(200==n.status){var r=JSON.parse(n.responseText),a=t.snippetId||"_BLANK";t.snippetId=r.id,r.version&&"0"!=r.version&&(t.snippetId+="#"+r.version),e.forceUpdate(),navigator.clipboard&&navigator.clipboard.writeText(t.snippetId);var o=window;o.Playground&&a&&o.Playground.onRequestCodeChangeObservable.notifyObservers({regex:new RegExp('SpriteManager.CreateFromSnippetAsync\\("'+a,"g"),replace:'SpriteManager.CreateFromSnippetAsync("'+t.snippetId}),alert("Sprite manager saved with ID: "+t.snippetId+" (please note that the id was also saved to your clipboard)")}else alert("Unable to save your sprite manager")},n.open("POST",this._snippetUrl+(t.snippetId?"/"+t.snippetId:""),!0),n.setRequestHeader("Content-Type","application/json");var a={payload:JSON.stringify({spriteManager:r}),name:"",description:"",tags:""};n.send(JSON.stringify(a))},t.prototype.render=function(){var e=this,t=this.props.spriteManager,r=[{label:"Combine",value:u.Constants.ALPHA_COMBINE},{label:"One one",value:u.Constants.ALPHA_ONEONE},{label:"Add",value:u.Constants.ALPHA_ADD},{label:"Subtract",value:u.Constants.ALPHA_SUBTRACT},{label:"Multiply",value:u.Constants.ALPHA_MULTIPLY},{label:"Maximized",value:u.Constants.ALPHA_MAXIMIZED},{label:"Pre-multiplied",value:u.Constants.ALPHA_PREMULTIPLIED}];return s.createElement("div",{className:"pane"},s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Be,{lockObject:this.props.lockObject,label:"Name",target:t,propertyName:"name",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ce,{label:"Unique ID",value:t.uniqueId.toString()}),s.createElement(Ce,{label:"Capacity",value:t.capacity.toString()}),s.createElement(qe,{label:"Texture",texture:t.texture,onSelectionChangedObservable:this.props.onSelectionChangedObservable}),t.sprites.length<t.capacity&&s.createElement(Ye,{label:"Add new sprite",onClick:function(){return e.addNewSprite()}}),s.createElement(Ye,{label:"Dispose",onClick:function(){return e.disposeManager()}})),s.createElement(Ee,{globalState:this.props.globalState,title:"FILE"},s.createElement(Qe,{label:"Load",onClick:function(t){return e.loadFromFile(t)},accept:".json"}),s.createElement(Ye,{label:"Save",onClick:function(){return e.saveToFile()}})),s.createElement(Ee,{globalState:this.props.globalState,title:"SNIPPET"},t.snippetId&&s.createElement(Ce,{label:"Snippet ID",value:t.snippetId}),s.createElement(Ye,{label:"Load from snippet server",onClick:function(){return e.loadFromSnippet()}}),s.createElement(Ye,{label:"Save to snippet server",onClick:function(){return e.saveToSnippet()}})),s.createElement(Ee,{globalState:this.props.globalState,title:"PROPERTIES"},s.createElement(Pe,{label:"Pickable",target:t,propertyName:"isPickable",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Fog enabled",target:t,propertyName:"fogEnabled",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"No depth write",target:t,propertyName:"disableDepthWrite",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{label:"Rendering group ID",decimalCount:0,target:t,propertyName:"renderingGroupId",minimum:u.RenderingManager.MIN_RENDERINGGROUPS,maximum:u.RenderingManager.MAX_RENDERINGGROUPS-1,step:1,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Re,{label:"Alpha mode",options:r,target:t,propertyName:"blendMode",onPropertyChangedObservable:this.props.onPropertyChangedObservable,onSelect:function(t){return e.setState({blendMode:t})}})),s.createElement(Ee,{globalState:this.props.globalState,title:"CELLS"},s.createElement(Me,{label:"Cell width",isInteger:!0,target:t,propertyName:"cellWidth",min:0,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{label:"Cell height",isInteger:!0,target:t,propertyName:"cellHeight",min:0,onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),Vr=function(e){function t(t){var r=e.call(this,t)||this;return r.imageData=null,r.cachedCellIndex=-1,r.canvasRef=s.createRef(),r}return a(t,e),t.prototype.onManagerLink=function(){if(this.props.onSelectionChangedObservable){var e=this.props.sprite;this.props.onSelectionChangedObservable.notifyObservers(e.manager)}},t.prototype.switchPlayStopState=function(){var e=this.props.sprite;e.animationStarted?e.stopAnimation():e.playAnimation(e.fromIndex,e.toIndex,e.loopAnimation,e.delay,(function(){})),this.forceUpdate()},t.prototype.disposeSprite=function(){var e;this.props.sprite.dispose(),null===(e=this.props.onSelectionChangedObservable)||void 0===e||e.notifyObservers(null)},t.prototype.componentDidMount=function(){this.updatePreview()},t.prototype.componentDidUpdate=function(){this.updatePreview()},t.prototype.shouldComponentUpdate=function(e){return e.sprite!==this.props.sprite&&(this.imageData=null),!0},t.prototype.updatePreview=function(){var e=this,t=this.props.sprite,r=t.manager,n=r.texture,a=n.getSize();if(this.imageData){if(this.cachedCellIndex!==t.cellIndex){this.cachedCellIndex=t.cellIndex;var o=this.canvasRef.current;o.width=r.cellWidth,o.height=r.cellHeight;var i=o.getContext("2d");if(i){for(var l=i.createImageData(r.cellWidth,r.cellHeight),s=l.data,p=a.width/r.cellWidth|0,c=t.cellIndex/p|0,u=4*(t.cellIndex-c*p+c*a.width)*r.cellWidth,d=0;d<r.cellWidth;d++)for(var h=0;h<r.cellHeight;h++){var b=4*(d+h*r.cellWidth),m=4*(d+h*a.width);s[b]=this.imageData[u+m],s[b+1]=this.imageData[u+m+1],s[b+2]=this.imageData[u+m+2],s[b+3]=this.imageData[u+m+3]}i.putImageData(l,0,0)}}}else tt.GetTextureDataAsync(n,a.width,a.height,0,{R:!0,G:!0,B:!0,A:!0},this.props.globalState).then((function(t){e.imageData=t,e.forceUpdate()}))},t.prototype.render=function(){var e=this,t=this.props.sprite,r=t.manager,n=r.texture.getSize(),a=0;return a=n.width&&n.height?n.width/r.cellWidth*(n.height/r.cellHeight):Math.max(t.fromIndex,t.toIndex),s.createElement("div",{className:"pane"},s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Be,{lockObject:this.props.lockObject,label:"Name",target:t,propertyName:"name",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ce,{label:"Unique ID",value:t.uniqueId.toString()}),s.createElement(Ce,{label:"Link to manager",value:r.name,onLink:function(){return e.onManagerLink()}}),s.createElement(Pe,{label:"Visible",target:t,propertyName:"isVisible",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ye,{label:"Dispose",onClick:function(){return e.disposeSprite()}})),s.createElement(Ee,{globalState:this.props.globalState,title:"PROPERTIES"},s.createElement(Ue,{label:"Position",target:t,propertyName:"position",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Pickable",target:t,propertyName:"isPickable",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Use alpha for picking",target:t,propertyName:"useAlphaForPicking",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Cr,{label:"Color",target:t,propertyName:"color",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Le,{useEuler:this.props.globalState.onlyUseEulers,label:"Angle",target:t,propertyName:"angle",minimum:0,maximum:2*Math.PI,step:.01,onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"CELL"},s.createElement("canvas",{ref:this.canvasRef,className:"preview",style:{margin:"auto",marginTop:"4px",marginBottom:"4px",display:"grid",height:"108px"}}),s.createElement(Le,{label:"Cell index",decimalCount:0,target:t,propertyName:"cellIndex",minimum:0,maximum:a,step:1,onPropertyChangedObservable:this.props.onPropertyChangedObservable,onChange:function(){return e.forceUpdate()}}),s.createElement(Pe,{label:"Invert U axis",target:t,propertyName:"invertU",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Invert V axis",target:t,propertyName:"invertV",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"SCALE"},s.createElement(Me,{label:"Width",lockObject:this.props.lockObject,target:t,propertyName:"width",min:0,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{label:"Height",lockObject:this.props.lockObject,target:t,propertyName:"height",min:0,onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"ANIMATION"},s.createElement(Me,{label:"Start cell",isInteger:!0,lockObject:this.props.lockObject,target:t,propertyName:"fromIndex",min:0,max:a,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{label:"End cell",isInteger:!0,lockObject:this.props.lockObject,target:t,propertyName:"toIndex",min:0,max:a,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Loop",target:t,propertyName:"loopAnimation",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{label:"Delay",lockObject:this.props.lockObject,target:t,propertyName:"delay",digits:0,min:0,isInteger:!0,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ye,{label:t.animationStarted?"Stop":"Start",onClick:function(){return e.switchPlayStopState()}})))},t}(s.Component),Ur=function(e){function t(t){var r=e.call(this,t)||this;return r.playOrPause=function(){r._animationGroup&&(r._animationGroup.isPlaying?r._animationGroup.stop():r._animationGroup.start(),r.forceUpdate())},r.deleteAnimation=function(){var e;if(r._animationGroup){var t=r._animationGroup.targetedAnimations.indexOf(r.props.targetedAnimation);t>-1&&(r._animationGroup.targetedAnimations.splice(t,1),null===(e=r.props.onSelectionChangedObservable)||void 0===e||e.notifyObservers(null),r._animationGroup.isPlaying&&(r._animationGroup.stop(),r._animationGroup.start()))}},r._animationGroup=r.props.scene.animationGroups.find((function(e){return void 0!==e.targetedAnimations.find((function(e){return e===r.props.targetedAnimation}))})),r}return a(t,e),t.prototype.render=function(){var e=this,t=this.props.targetedAnimation;return s.createElement("div",{className:"pane"},s.createElement(Ee,{globalState:this.props.globalState,title:"GENERAL"},s.createElement(Ce,{label:"Class",value:t.getClassName()}),s.createElement(Be,{lockObject:this.props.lockObject,label:"Name",target:t.animation,propertyName:"name",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),t.target.name&&s.createElement(Ce,{label:"Target",value:t.target.name,onLink:function(){return e.props.globalState.onSelectionChangedObservable.notifyObservers(t)}}),s.createElement(Ye,{label:"Dispose",onClick:this.deleteAnimation})))},t}(s.Component),Hr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.camera;return s.createElement("div",{className:"pane"},s.createElement(Dt,{globalState:this.props.globalState,lockObject:this.props.lockObject,camera:e,onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Ee,{globalState:this.props.globalState,title:"TRANSFORMS"},s.createElement(Me,{lockObject:this.props.lockObject,label:"Radius",target:e,propertyName:"radius",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Rotation offset",target:e,propertyName:"rotationOffset",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Height offset",target:e,propertyName:"heightOffset",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Camera acceleration",target:e,propertyName:"cameraAcceleration",onPropertyChangedObservable:this.props.onPropertyChangedObservable})),s.createElement(Ee,{globalState:this.props.globalState,title:"LIMITS",closed:!0},s.createElement(Me,{lockObject:this.props.lockObject,label:"Lower radius limit",target:e,propertyName:"lowerRadiusLimit",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Upper radius limit",target:e,propertyName:"upperRadiusLimit",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Lower rotation offset limit",target:e,propertyName:"lowerRotationOffsetLimit",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Upper rotation offset limit",target:e,propertyName:"upperRotationOffsetLimit",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Lower height offset limit",target:e,propertyName:"lowerHeightOffsetLimit",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Upper height offset limit",target:e,propertyName:"upperHeightOffsetLimit",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Me,{lockObject:this.props.lockObject,label:"Max camera speed",target:e,propertyName:"maxCameraSpeed",onPropertyChangedObservable:this.props.onPropertyChangedObservable})))},t}(s.Component),Br=function(e){function t(t){var r=e.call(this,t)||this;return r._lockObject=new Yt,r}return a(t,e),t.prototype.timerRefresh=function(){this._lockObject.lock||this.forceUpdate()},t.prototype.componentDidMount=function(){var e=this;this._timerIntervalId=window.setInterval((function(){return e.timerRefresh()}),500)},t.prototype.componentWillUnmount=function(){window.clearInterval(this._timerIntervalId)},t.prototype.render=function(){var e=this.props.selectedEntity;if(!e)return s.createElement("div",{className:"infoMessage"},"Please select an entity in the scene explorer.");if(e.getClassName){var t=e.getClassName();if("Scene"===t){var r=e;return s.createElement(kt,{scene:r,globalState:this.props.globalState,lockObject:this._lockObject,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("Sprite"===t){var n=e;return s.createElement(Vr,{sprite:n,globalState:this.props.globalState,lockObject:this._lockObject,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("SpriteManager"===t){var a=e;return s.createElement(Gr,{spriteManager:a,globalState:this.props.globalState,lockObject:this._lockObject,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(-1!==t.indexOf("Mesh")){var o=e;if(o.getTotalVertices()>0)return s.createElement("div",null,s.createElement(jt,{globalState:this.props.globalState,mesh:o,lockObject:this._lockObject,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onPropertyChangedObservable:this.props.onPropertyChangedObservable}))}if(-1!==t.indexOf("ParticleSystem")){var i=e;return s.createElement(Fr,{globalState:this.props.globalState,system:i,lockObject:this._lockObject,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(-1!==t.indexOf("FreeCamera")||-1!==t.indexOf("UniversalCamera")||-1!==t.indexOf("WebXRCamera")||-1!==t.indexOf("DeviceOrientationCamera")){var l=e;return s.createElement(Rt,{globalState:this.props.globalState,camera:l,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(-1!==t.indexOf("ArcRotateCamera")){var p=e;return s.createElement(At,{globalState:this.props.globalState,camera:p,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(-1!==t.indexOf("FollowCamera")){var c=e;return s.createElement(Hr,{globalState:this.props.globalState,camera:c,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("HemisphericLight"===t){var u=e;return s.createElement(Tt,{globalState:this.props.globalState,light:u,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("PointLight"===t){var d=e;return s.createElement(Mt,{globalState:this.props.globalState,light:d,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("DirectionalLight"===t){d=e;return s.createElement(mr,{globalState:this.props.globalState,light:d,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("SpotLight"===t){d=e;return s.createElement(gr,{globalState:this.props.globalState,light:d,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(-1!==t.indexOf("TransformNode")||-1!==t.indexOf("Mesh")){var h=e;return s.createElement(zt,{transformNode:h,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("MultiMaterial"===t){var b=e;return s.createElement(wr,{globalState:this.props.globalState,material:b,lockObject:this._lockObject,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("StandardMaterial"===t){b=e;return s.createElement($e,{globalState:this.props.globalState,material:b,lockObject:this._lockObject,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("NodeMaterial"===t){b=e;return s.createElement(Pr,{globalState:this.props.globalState,material:b,lockObject:this._lockObject,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("PBRMaterial"===t){b=e;return s.createElement(xt,{globalState:this.props.globalState,material:b,lockObject:this._lockObject,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("PBRMetallicRoughnessMaterial"===t){b=e;return s.createElement(nr,{globalState:this.props.globalState,material:b,lockObject:this._lockObject,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("PBRSpecularGlossinessMaterial"===t){b=e;return s.createElement(ar,{globalState:this.props.globalState,material:b,lockObject:this._lockObject,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("BackgroundMaterial"===t){b=e;return s.createElement(Ft,{globalState:this.props.globalState,material:b,lockObject:this._lockObject,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("AnimationGroup"===t){var m=e;return s.createElement(Wt,{globalState:this.props.globalState,animationGroup:m,scene:this.props.scene,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("TargetedAnimation"===t){var g=e;return s.createElement(Ur,{globalState:this.props.globalState,targetedAnimation:g,scene:this.props.scene,lockObject:this._lockObject,onSelectionChangedObservable:this.props.onSelectionChangedObservable,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(-1!==t.indexOf("Material")){b=e;return s.createElement(Xe,{material:b,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(-1!==t.indexOf("DefaultRenderingPipeline")){var f=e;return s.createElement(cr,{renderPipeline:f,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(-1!==t.indexOf("LensRenderingPipeline")){f=e;return s.createElement(fr,{renderPipeline:f,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(-1!==t.indexOf("SSAORenderingPipeline")){f=e;return s.createElement(ur,{renderPipeline:f,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(-1!==t.indexOf("SSAO2RenderingPipeline")){f=e;return s.createElement(dr,{renderPipeline:f,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(-1!==t.indexOf("RenderingPipeline")){f=e;return s.createElement(pr,{renderPipeline:f,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(-1!==t.indexOf("PostProcess")){var v=e;return s.createElement(lr,{postProcess:v,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(-1!==t.indexOf("Texture")){var y=e;return s.createElement(Ot,{texture:y,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(-1!==t.indexOf("Skeleton")){var C=e;return s.createElement(hr,{skeleton:C,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(-1!==t.indexOf("Bone")){var E=e;return s.createElement(br,{bone:E,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("TextBlock"===t){var O=e;return s.createElement(Ut,{textBlock:O,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("InputText"===t){var S=e;return s.createElement(Ht,{inputText:S,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("ColorPicker"===t){var x=e;return s.createElement(Bt,{colorPicker:x,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("Image"===t){var P=e;return s.createElement(Zt,{image:P,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("Slider"===t){var w=e;return s.createElement(Kt,{slider:w,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("ImageBasedSlider"===t){var k=e;return s.createElement(Xt,{imageBasedSlider:k,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("Rectangle"===t){var N=e;return s.createElement(Qt,{rectangle:N,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("StackPanel"===t){var T=e;return s.createElement(or,{stackPanel:T,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("Grid"===t){var _=e;return s.createElement(rr,{grid:_,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("ScrollViewer"===t){var M=e;return s.createElement(tr,{scrollViewer:M,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("Ellipse"===t){var L=e;return s.createElement(qt,{ellipse:L,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("Checkbox"===t){var D=e;return s.createElement($t,{checkbox:D,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("RadioButton"===t){var R=e;return s.createElement(Jt,{radioButton:R,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if("Line"===t){var A=e;return s.createElement(er,{line:A,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}if(e._host){var I=e;return s.createElement(Vt,{control:I,globalState:this.props.globalState,lockObject:this._lockObject,onPropertyChangedObservable:this.props.onPropertyChangedObservable})}}return null},t}(ye),Wr=function(e){function t(t){var r=e.call(this,t)||this;return r._backStack=new Array,r.state={isBackVisible:!1},r}return a(t,e),t.prototype.componentDidMount=function(){var e=this;this.props.onSelectionChangedObservable&&(this._onSelectionChangeObserver=this.props.onSelectionChangedObservable.add((function(t){0!==e._backStack.length&&t===e._backStack[e._backStack.length-1]||(e._backStack.push(t),e.setState({isBackVisible:e._backStack.length>1}))})))},t.prototype.componentWillUnmount=function(){this._onSelectionChangeObserver&&this.props.onSelectionChangedObservable.remove(this._onSelectionChangeObserver)},t.prototype.goBack=function(){this._backStack.pop();var e=this._backStack[this._backStack.length-1];this.props.onSelectionChangedObservable&&this.props.onSelectionChangedObservable.notifyObservers(e),this.setState({isBackVisible:this._backStack.length>1})},t.prototype.renderLogo=function(){var e=this;return this.props.noCommands?null:this.props.handleBack?this.state.isBackVisible?s.createElement("div",{id:"back",onClick:function(){return e.goBack()}},s.createElement(w,{icon:_})):null:s.createElement("img",{id:"logo",style:{top:"0%"},src:"https://www.babylonjs.com/Assets/logo-babylonjs-social-twitter.png"})},t.prototype.render=function(){var e=this;return s.createElement("div",{id:"header"},this.renderLogo(),s.createElement("div",{id:"title"},this.props.title),s.createElement("div",{id:"commands"},!this.props.noCommands&&!this.props.noExpand&&s.createElement("div",{className:"expand",onClick:function(){return e.props.onPopup()}},s.createElement(w,{icon:fe})),!this.props.noCommands&&!this.props.noClose&&s.createElement("div",{className:"close",onClick:function(){return e.props.onClose()}},s.createElement(w,{icon:de}))))},t}(s.Component),Yr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){return this.props.icon?s.createElement("div",{className:"iconMessageLine"},s.createElement("div",{className:"icon",style:{color:this.props.color?this.props.color:""}},s.createElement(w,{icon:this.props.icon})),s.createElement("div",{className:"value",title:this.props.text},this.props.text)):s.createElement("div",{className:"messageLine"},s.createElement("div",{className:"value",title:this.props.text,style:{color:this.props.color?this.props.color:""}},this.props.text))},t}(s.Component),Zr=r(7),Kr=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._onValidationResultsUpdatedObserver=null,t}return a(t,e),t.prototype.openValidationDetails=function(){var e=this.props.globalState.validationResults,t=window.open("","_blank");t&&(t.document.title="glTF Validation Results",t.document.body.innerText=JSON.stringify(e,null,2),t.document.body.style.whiteSpace="pre",t.document.body.style.fontFamily="monospace",t.document.body.style.fontSize="14px",t.focus())},t.prototype.prepareText=function(e,t){return t?t+" "+e+"s":""+e},t.prototype.componentDidMount=function(){var e=this;this.props.globalState&&(this._onValidationResultsUpdatedObserver=this.props.globalState.onValidationResultsUpdatedObservable.add((function(){e.forceUpdate()})))},t.prototype.componentWillUnmount=function(){this.props.globalState&&this._onValidationResultsUpdatedObserver&&this.props.globalState.onValidationResultsUpdatedObservable.remove(this._onValidationResultsUpdatedObserver)},t.prototype.renderValidation=function(){var e=this,t=this.props.globalState.validationResults;if(!t)return null;var r=t.issues;return s.createElement(Ee,{globalState:this.props.globalState,title:"GLTF VALIDATION",closed:!r.numErrors&&!r.numWarnings},0!==r.numErrors&&s.createElement(Yr,{text:"Your file has some validation issues",icon:he,color:"Red"}),0===r.numErrors&&s.createElement(Yr,{text:"Your file is a valid glTF file",icon:F,color:"Green"}),s.createElement(Ce,{label:"Errors",value:r.numErrors.toString()}),s.createElement(Ce,{label:"Warnings",value:r.numWarnings.toString()}),s.createElement(Ce,{label:"Infos",value:r.numInfos.toString()}),s.createElement(Ce,{label:"Hints",value:r.numHints.toString()}),s.createElement(Ce,{label:"More details",value:"Click here",onLink:function(){return e.openValidationDetails()}}))},t.prototype.render=function(){var e=this.props.globalState.glTFLoaderExtensionDefaults,t=this.props.globalState.glTFLoaderDefaults,r=void 0!==Zr.GLTFLoaderAnimationStartMode?[{label:"None",value:Zr.GLTFLoaderAnimationStartMode.NONE},{label:"First",value:Zr.GLTFLoaderAnimationStartMode.FIRST},{label:"ALL",value:Zr.GLTFLoaderAnimationStartMode.ALL}]:[{label:"None",value:0},{label:"First",value:1},{label:"ALL",value:2}],n=void 0!==Zr.GLTFLoaderCoordinateSystemMode?[{label:"Auto",value:Zr.GLTFLoaderCoordinateSystemMode.AUTO},{label:"Right handed",value:Zr.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED}]:[{label:"Auto",value:0},{label:"Right handed",value:1}];return s.createElement("div",null,s.createElement(Ee,{globalState:this.props.globalState,title:"GLTF LOADER",closed:!0},s.createElement(Re,{label:"Animation start mode",options:r,target:t,propertyName:"animationStartMode"}),s.createElement(Pe,{label:"Capture performance counters",target:t,propertyName:"capturePerformanceCounters"}),s.createElement(Pe,{label:"Compile materials",target:t,propertyName:"compileMaterials"}),s.createElement(Pe,{label:"Compile shadow generators",target:t,propertyName:"compileShadowGenerators"}),s.createElement(Re,{label:"Coordinate system",options:n,target:t,propertyName:"coordinateSystemMode"}),s.createElement(Pe,{label:"Enable logging",target:t,propertyName:"loggingEnabled"}),s.createElement(Pe,{label:"Transparency as coverage",target:t,propertyName:"transparencyAsCoverage"}),s.createElement(Pe,{label:"Use clip plane",target:t,propertyName:"useClipPlane"}),s.createElement(Pe,{label:"Validate",target:t,propertyName:"validate"}),s.createElement(Yr,{text:"You need to reload your file to see these changes"})),s.createElement(Ee,{globalState:this.props.globalState,title:"GLTF EXTENSIONS",closed:!0},s.createElement(Pe,{label:"MSFT_lod",isSelected:function(){return e.MSFT_lod.enabled},onSelect:function(t){return e.MSFT_lod.enabled=t}}),s.createElement(Me,{label:"Maximum LODs",target:e.MSFT_lod,propertyName:"maxLODsToLoad",additionalClass:"gltf-extension-property",isInteger:!0}),s.createElement(Pe,{label:"MSFT_minecraftMesh",isSelected:function(){return e.MSFT_minecraftMesh.enabled},onSelect:function(t){return e.MSFT_minecraftMesh.enabled=t}}),s.createElement(Pe,{label:"MSFT_sRGBFactors",isSelected:function(){return e.MSFT_sRGBFactors.enabled},onSelect:function(t){return e.MSFT_sRGBFactors.enabled=t}}),s.createElement(Pe,{label:"MSFT_audio_emitter",isSelected:function(){return e.MSFT_audio_emitter.enabled},onSelect:function(t){return e.MSFT_audio_emitter.enabled=t}}),s.createElement(Pe,{label:"KHR_draco_mesh_compression",isSelected:function(){return e.KHR_draco_mesh_compression.enabled},onSelect:function(t){return e.KHR_draco_mesh_compression.enabled=t}}),s.createElement(Pe,{label:"KHR_mesh_quantization",isSelected:function(){return e.KHR_mesh_quantization.enabled},onSelect:function(t){return e.KHR_mesh_quantization.enabled=t}}),s.createElement(Pe,{label:"KHR_materials_pbrSpecularGloss...",isSelected:function(){return e.KHR_materials_pbrSpecularGlossiness.enabled},onSelect:function(t){return e.KHR_materials_pbrSpecularGlossiness.enabled=t}}),s.createElement(Pe,{label:"KHR_materials_clearcoat",isSelected:function(){return e.KHR_materials_clearcoat.enabled},onSelect:function(t){return e.KHR_materials_clearcoat.enabled=t}}),s.createElement(Pe,{label:"KHR_materials_ior",isSelected:function(){return e.KHR_materials_ior.enabled},onSelect:function(t){return e.KHR_materials_ior.enabled=t}}),s.createElement(Pe,{label:"KHR_materials_sheen",isSelected:function(){return e.KHR_materials_sheen.enabled},onSelect:function(t){return e.KHR_materials_sheen.enabled=t}}),s.createElement(Pe,{label:"KHR_materials_specular",isSelected:function(){return e.KHR_materials_specular.enabled},onSelect:function(t){return e.KHR_materials_specular.enabled=t}}),s.createElement(Pe,{label:"KHR_materials_unlit",isSelected:function(){return e.KHR_materials_unlit.enabled},onSelect:function(t){return e.KHR_materials_unlit.enabled=t}}),s.createElement(Pe,{label:"KHR_materials_variants",isSelected:function(){return e.KHR_materials_variants.enabled},onSelect:function(t){return e.KHR_materials_variants.enabled=t}}),s.createElement(Pe,{label:"KHR_materials_transmission",isSelected:function(){return e.KHR_materials_transmission.enabled},onSelect:function(t){return e.KHR_materials_transmission.enabled=t}}),s.createElement(Pe,{label:"KHR_materials_translucency",isSelected:function(){return e.KHR_materials_translucency.enabled},onSelect:function(t){return e.KHR_materials_translucency.enabled=t}}),s.createElement(Pe,{label:"KHR_lights_punctual",isSelected:function(){return e.KHR_lights_punctual.enabled},onSelect:function(t){return e.KHR_lights_punctual.enabled=t}}),s.createElement(Pe,{label:"KHR_texture_basisu",isSelected:function(){return e.KHR_texture_basisu.enabled},onSelect:function(t){return e.KHR_texture_basisu.enabled=t}}),s.createElement(Pe,{label:"KHR_texture_transform",isSelected:function(){return e.KHR_texture_transform.enabled},onSelect:function(t){return e.KHR_texture_transform.enabled=t}}),s.createElement(Pe,{label:"EXT_lights_image_based",isSelected:function(){return e.EXT_lights_image_based.enabled},onSelect:function(t){return e.EXT_lights_image_based.enabled=t}}),s.createElement(Pe,{label:"EXT_mesh_gpu_instancing",isSelected:function(){return e.EXT_mesh_gpu_instancing.enabled},onSelect:function(t){return e.EXT_mesh_gpu_instancing.enabled=t}}),s.createElement(Pe,{label:"EXT_texture_webp",isSelected:function(){return e.EXT_texture_webp.enabled},onSelect:function(t){return e.EXT_texture_webp.enabled=t}}),s.createElement(Yr,{text:"You need to reload your file to see these changes"})),t.validate&&this.props.globalState.validationResults&&this.renderValidation())},t}(s.Component),Xr=r(16),Qr=function(e){function t(r){var n=e.call(this,r)||this;return n._id=t._IDGenerator++,n.uploadInputRef=s.createRef(),n}return a(t,e),t.prototype.onChange=function(e){var t=e.target.files;t&&t.length&&this.props.onClick(e),e.target.value=""},t.prototype.render=function(){var e=this;return s.createElement("div",{className:"buttonLine"},s.createElement("label",{htmlFor:"file-upload"+this._id,className:"file-upload"},this.props.label),s.createElement("input",{ref:this.uploadInputRef,id:"file-upload"+this._id,type:"file",accept:this.props.accept,onChange:function(t){return e.onChange(t)},multiple:!0}))},t._IDGenerator=0,t}(s.Component),qr=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.onLink=function(){this.props.url?window.open(this.props.url,"_blank"):this.props.onLink&&this.props.onLink()},t.prototype.renderContent=function(){var e=this;return this.props.onLink||this.props.url?s.createElement("div",{className:"link-value",title:this.props.value,onClick:function(){return e.onLink()}},this.props.url?"doc":this.props.value||"no name"):s.createElement("div",{className:"value",title:this.props.value,style:{color:this.props.color?this.props.color:""}},this.props.value||"no name")},t.prototype.render=function(){return s.createElement("div",{className:"indented "+(this.props.underline?"textLine underline":"textLine"+(this.props.additionalClass?" "+this.props.additionalClass:""))},this.renderContent())},t}(s.Component),$r=r(53),Jr=function(e){function t(t){var r=e.call(this,t)||this;r._screenShotSize={precision:1},r._gifOptions={width:512,frequency:200},r._useWidthHeight=!1,r._isExporting=!1,r._crunchingGIF=!1,r.state={tag:"Record video"};var n=r.props.globalState.sceneImportDefaults;return void 0===n.overwriteAnimations&&(n.overwriteAnimations=!0),void 0===n.animationGroupLoadingMode&&(n.animationGroupLoadingMode=u.SceneLoaderAnimationGroupLoadingMode.Clean),r}return a(t,e),t.prototype.componentDidMount=function(){BABYLON.GLTF2Export||u.Tools.LoadScript("https://preview.babylonjs.com/serializers/babylonjs.serializers.min.js",(function(){}))},t.prototype.componentWillUnmount=function(){if(this._videoRecorder&&(this._videoRecorder.stopRecording(),this._videoRecorder.dispose(),this._videoRecorder=null),this._gifRecorder)return this._gifRecorder.render(),void(this._gifRecorder=null)},t.prototype.captureScreenshot=function(){var e=this.props.scene;e.activeCamera&&u.Tools.CreateScreenshot(e.getEngine(),e.activeCamera,this._screenShotSize)},t.prototype.captureRender=function(){var e=this.props.scene,t={height:this._screenShotSize.height,width:this._screenShotSize.width,precision:this._screenShotSize.precision};this._useWidthHeight||(this._screenShotSize.width=void 0,this._screenShotSize.height=void 0),e.activeCamera&&u.Tools.CreateScreenshotUsingRenderTarget(e.getEngine(),e.activeCamera,this._screenShotSize),this._screenShotSize=t},t.prototype.recordVideo=function(){var e=this;if(this._videoRecorder&&this._videoRecorder.isRecording)this._videoRecorder.stopRecording();else{var t=this.props.scene;this._videoRecorder||(this._videoRecorder=new u.VideoRecorder(t.getEngine())),this._videoRecorder.startRecording().then((function(){e.setState({tag:"Record video"})})),this.setState({tag:"Stop recording"})}},t.prototype.recordGIFInternal=function(){var e=this,t=URL.createObjectURL(this._gifWorkerBlob);this._gifRecorder=new $r({workers:2,quality:10,workerScript:t});var r=this.props.scene.getEngine();this._previousRenderingScale=r.getHardwareScalingLevel(),r.setHardwareScalingLevel(r.getRenderWidth()/this._gifOptions.width|0);var n=setInterval((function(){e._gifRecorder?e._gifRecorder.addFrame(r.getRenderingCanvas(),{delay:e._gifOptions.frequency}):clearInterval(n)}),this._gifOptions.frequency);this._gifRecorder.on("finished",(function(n){e._crunchingGIF=!1,u.Tools.Download(n,"record.gif"),e.forceUpdate(),URL.revokeObjectURL(t),r.setHardwareScalingLevel(e._previousRenderingScale)})),this.forceUpdate()},t.prototype.recordGIF=function(){var e=this;if(this._gifRecorder)return this._crunchingGIF=!0,this.forceUpdate(),this._gifRecorder.render(),void(this._gifRecorder=null);this._gifWorkerBlob?this.recordGIFInternal():u.Tools.LoadFileAsync("https://cdn.jsdelivr.net/gh//terikon/gif.js.optimized@0.1.6/dist/gif.worker.js").then((function(t){e._gifWorkerBlob=new Blob([t],{type:"application/javascript"}),e.recordGIFInternal()}))},t.prototype.importAnimations=function(e){var t=this.props.scene,r=this.props.globalState.sceneImportDefaults.overwriteAnimations,n=this.props.globalState.sceneImportDefaults.animationGroupLoadingMode;new u.FilesInput(t.getEngine(),t,(function(){}),(function(){}),(function(){}),(function(e){}),(function(){}),(function(e){if(e){BABYLON.SceneLoader.ImportAnimationsAsync("file:",e,t,r,n,null,(function(e){e.animationGroups.length>0&&e.animationGroups[0].play(!0)}))}}),(function(){})).loadFiles(e)},t.prototype.shouldExport=function(e){if(e instanceof u.Mesh&&e.material){var t=e.material.reflectionTexture;if(t&&t.coordinatesMode===u.Texture.SKYBOX_MODE)return!1}return!0},t.prototype.exportGLTF=function(){var e=this,t=this.props.scene;this._isExporting=!0,this.forceUpdate(),Xr.GLTF2Export.GLBAsync(t,"scene",{shouldExportNode:function(t){return e.shouldExport(t)}}).then((function(t){t.downloadFiles(),e._isExporting=!1,e.forceUpdate()})).catch((function(t){e._isExporting=!1,e.forceUpdate()}))},t.prototype.exportBabylon=function(){var e=this.props.scene,t=JSON.stringify(u.SceneSerializer.Serialize(e)),r=new Blob([t],{type:"octet/stream"});u.Tools.Download(r,"scene.babylon")},t.prototype.createEnvTexture=function(){var e=this.props.scene;u.EnvironmentTextureTools.CreateEnvTextureAsync(e.environmentTexture).then((function(e){var t=new Blob([e],{type:"octet/stream"});u.Tools.Download(t,"environment.env")})).catch((function(e){console.error(e),alert(e)}))},t.prototype.exportReplay=function(){this.props.globalState.recorder.export(),this.forceUpdate()},t.prototype.startRecording=function(){this.props.globalState.recorder.trackScene(this.props.scene),this.forceUpdate()},t.prototype.applyDelta=function(e){var t=this;u.Tools.ReadFile(e,(function(e){t.props.globalState.recorder.applyDelta(e,t.props.scene),t.forceUpdate()}))},t.prototype.render=function(){var e=this,t=this.props.scene;if(!t)return null;var r=this.props.globalState.sceneImportDefaults,n=[{label:"Clean",value:u.SceneLoaderAnimationGroupLoadingMode.Clean},{label:"Stop",value:u.SceneLoaderAnimationGroupLoadingMode.Stop},{label:"Sync",value:u.SceneLoaderAnimationGroupLoadingMode.Sync},{label:"NoSync",value:u.SceneLoaderAnimationGroupLoadingMode.NoSync}];return s.createElement("div",{className:"pane"},s.createElement(Ee,{globalState:this.props.globalState,title:"CAPTURE"},s.createElement(Ye,{label:"Screenshot",onClick:function(){return e.captureScreenshot()}}),s.createElement(Ye,{label:this.state.tag,onClick:function(){return e.recordVideo()}})),s.createElement(Ee,{globalState:this.props.globalState,title:"CAPTURE WITH RTT"},s.createElement(Ye,{label:"Capture",onClick:function(){return e.captureRender()}}),s.createElement("div",{className:"vector3Line"},s.createElement(Me,{label:"Precision",target:this._screenShotSize,propertyName:"precision",onPropertyChangedObservable:this.props.onPropertyChangedObservable}),s.createElement(Pe,{label:"Use Width/Height",onSelect:function(t){e._useWidthHeight=t,e.forceUpdate()},isSelected:function(){return e._useWidthHeight}}),this._useWidthHeight&&s.createElement("div",{className:"secondLine"},s.createElement(Ae,{label:"Width",precision:0,step:1,value:this._screenShotSize.width?this._screenShotSize.width:512,onChange:function(t){return e._screenShotSize.width=t}}),s.createElement(Ae,{label:"Height",precision:0,step:1,value:this._screenShotSize.height?this._screenShotSize.height:512,onChange:function(t){return e._screenShotSize.height=t}})))),s.createElement(Ee,{globalState:this.props.globalState,title:"GIF"},this._crunchingGIF&&s.createElement(Yr,{text:"Creating the GIF file..."}),!this._crunchingGIF&&s.createElement(Ye,{label:this._gifRecorder?"Stop":"Record",onClick:function(){return e.recordGIF()}}),!this._crunchingGIF&&!this._gifRecorder&&s.createElement(s.Fragment,null,s.createElement(Me,{label:"Resolution",isInteger:!0,target:this._gifOptions,propertyName:"width"}),s.createElement(Me,{label:"Frequency (ms)",isInteger:!0,target:this._gifOptions,propertyName:"frequency"}))),s.createElement(Ee,{globalState:this.props.globalState,title:"REPLAY"},!this.props.globalState.recorder.isRecording&&s.createElement(Ye,{label:"Start recording",onClick:function(){return e.startRecording()}}),this.props.globalState.recorder.isRecording&&s.createElement(qr,{value:"Record in progress"}),this.props.globalState.recorder.isRecording&&s.createElement(Ye,{label:"Generate delta file",onClick:function(){return e.exportReplay()}}),s.createElement(Qe,{label:"Apply delta file",onClick:function(t){return e.applyDelta(t)},accept:".json"})),s.createElement(Ee,{globalState:this.props.globalState,title:"SCENE IMPORT"},s.createElement(Qr,{label:"Import animations",accept:"gltf",onClick:function(t){return e.importAnimations(t)}}),s.createElement(Pe,{label:"Overwrite animations",target:r,propertyName:"overwriteAnimations",onSelect:function(t){r.overwriteAnimations=t,e.forceUpdate()}}),!1===r.overwriteAnimations&&s.createElement(Re,{label:"Animation merge mode",options:n,target:r,propertyName:"animationGroupLoadingMode"})),s.createElement(Ee,{globalState:this.props.globalState,title:"SCENE EXPORT"},this._isExporting&&s.createElement(Ce,{label:"Please wait..exporting",ignoreValue:!0}),!this._isExporting&&s.createElement(s.Fragment,null,s.createElement(Ye,{label:"Export to GLB",onClick:function(){return e.exportGLTF()}}),s.createElement(Ye,{label:"Export to Babylon",onClick:function(){return e.exportBabylon()}}),!t.getEngine().premultipliedAlpha&&t.environmentTexture&&t.environmentTexture._prefiltered&&t.activeCamera&&s.createElement(Ye,{label:"Generate .env texture",onClick:function(){return e.createEnvTexture()}}))),BABYLON.GLTFFileLoader&&s.createElement(Kr,{scene:t,globalState:this.props.globalState}))},t}(ye),en=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this.props.globalState;return s.createElement("div",{className:"pane"},s.createElement(Ee,{globalState:this.props.globalState,title:"UI"},s.createElement(Pe,{label:"Only display Euler values",target:e,propertyName:"onlyUseEulers"}),s.createElement(Pe,{label:"Ignore backfaces when picking",target:e,propertyName:"ignoreBackfacesForPicking"})))},t}(ye);r(54);var tn=function(e){function t(t){var r=e.call(this,t)||this;r._once=!0;var n=void 0===t.initialTab?u.DebugLayerTab.Properties:t.initialTab;if(r.props.globalState){var a=r.props.globalState.validationResults;a&&(a.issues.numErrors||a.issues.numWarnings)&&(n=u.DebugLayerTab.Tools)}return r.state={selectedEntity:null,selectedIndex:n},r}return a(t,e),t.prototype.componentDidMount=function(){var e=this;this.props.globalState&&(this._onSelectionChangeObserver=this.props.globalState.onSelectionChangedObservable.add((function(t){e.setState({selectedEntity:t,selectedIndex:u.DebugLayerTab.Properties})})),this._onTabChangedObserver=this.props.globalState.onTabChangedObservable.add((function(t){e.setState({selectedIndex:t})})))},t.prototype.componentWillUnmount=function(){this.props.globalState&&(this._onSelectionChangeObserver&&this.props.globalState.onSelectionChangedObservable.remove(this._onSelectionChangeObserver),this._onTabChangedObserver&&this.props.globalState.onTabChangedObservable.remove(this._onTabChangedObserver))},t.prototype.changeSelectedTab=function(e){this.props.globalState&&this.props.globalState.onTabChangedObservable.notifyObservers(e)},t.prototype.renderContent=function(){var e=this;return this.props.globalState&&this.props.scene?s.createElement(N,{selectedIndex:this.state.selectedIndex,onSelectedIndexChange:function(t){return e.changeSelectedTab(t)}},s.createElement(Br,{title:"Properties",icon:Q,scene:this.props.scene,selectedEntity:this.state.selectedEntity,globalState:this.props.globalState,onSelectionChangedObservable:this.props.globalState.onSelectionChangedObservable,onPropertyChangedObservable:this.props.globalState.onPropertyChangedObservable}),s.createElement(Ne,{title:"Debug",icon:I,scene:this.props.scene,globalState:this.props.globalState}),s.createElement(xe,{title:"Statistics",icon:z,scene:this.props.scene,globalState:this.props.globalState}),s.createElement(Jr,{title:"Tools",icon:ve,scene:this.props.scene,globalState:this.props.globalState}),s.createElement(en,{title:"Settings",icon:U,scene:this.props.scene,globalState:this.props.globalState})):null},t.prototype.onClose=function(){this.props.onClose&&this.props.onClose()},t.prototype.onPopup=function(){this.props.onPopup&&this.props.onPopup()},t.prototype.render=function(){var e=this;return this.props.popupMode?s.createElement("div",{id:"actionTabs"},!this.props.noHeader&&s.createElement(Wr,{title:"INSPECTOR",handleBack:!0,noClose:this.props.noClose,noExpand:this.props.noExpand,noCommands:this.props.noCommands,onClose:function(){return e.onClose()},onPopup:function(){return e.onPopup()},onSelectionChangedObservable:this.props.globalState?this.props.globalState.onSelectionChangedObservable:void 0}),this.renderContent()):(this._once&&(this._once=!1,setTimeout((function(){var e=document.getElementById("actionTabs");e&&(e.style.width="300px")}),150)),s.createElement(_e.a,{id:"actionTabs",minWidth:300,maxWidth:600,size:{height:"100%"},minHeight:"100%",enable:{top:!1,right:!1,bottom:!1,left:!0,topRight:!1,bottomRight:!1,bottomLeft:!1,topLeft:!1}},!this.props.noHeader&&s.createElement(Wr,{title:"INSPECTOR",handleBack:!0,noClose:this.props.noClose,noExpand:this.props.noExpand,noCommands:this.props.noCommands,onClose:function(){return e.onClose()},onPopup:function(){return e.onPopup()},onSelectionChangedObservable:this.props.globalState?this.props.globalState.onSelectionChangedObservable:void 0}),this.renderContent()))},t}(s.Component),rn={prefix:"far",iconName:"eye",icon:[576,512,[],"f06e","M288 144a110.94 110.94 0 0 0-31.24 5 55.4 55.4 0 0 1 7.24 27 56 56 0 0 1-56 56 55.4 55.4 0 0 1-27-7.24A111.71 111.71 0 1 0 288 144zm284.52 97.4C518.29 135.59 410.93 64 288 64S57.68 135.64 3.48 241.41a32.35 32.35 0 0 0 0 29.19C57.71 376.41 165.07 448 288 448s230.32-71.64 284.52-177.41a32.35 32.35 0 0 0 0-29.19zM288 400c-98.65 0-189.09-55-237.93-144C98.91 167 189.34 112 288 112s189.09 55 237.93 144C477.1 345 386.66 400 288 400z"]},nn={prefix:"far",iconName:"eye-slash",icon:[640,512,[],"f070","M634 471L36 3.51A16 16 0 0 0 13.51 6l-10 12.49A16 16 0 0 0 6 41l598 467.49a16 16 0 0 0 22.49-2.49l10-12.49A16 16 0 0 0 634 471zM296.79 146.47l134.79 105.38C429.36 191.91 380.48 144 320 144a112.26 112.26 0 0 0-23.21 2.47zm46.42 219.07L208.42 260.16C210.65 320.09 259.53 368 320 368a113 113 0 0 0 23.21-2.46zM320 112c98.65 0 189.09 55 237.93 144a285.53 285.53 0 0 1-44 60.2l37.74 29.5a333.7 333.7 0 0 0 52.9-75.11 32.35 32.35 0 0 0 0-29.19C550.29 135.59 442.93 64 320 64c-36.7 0-71.71 7-104.63 18.81l46.41 36.29c18.94-4.3 38.34-7.1 58.22-7.1zm0 288c-98.65 0-189.08-55-237.93-144a285.47 285.47 0 0 1 44.05-60.19l-37.74-29.5a333.6 333.6 0 0 0-52.89 75.1 32.35 32.35 0 0 0 0 29.19C89.72 376.41 197.08 448 320 448c36.7 0 71.71-7.05 104.63-18.81l-46.41-36.28C359.28 397.2 339.89 400 320 400z"]},an={prefix:"far",iconName:"lightbulb",icon:[352,512,[],"f0eb","M176 80c-52.94 0-96 43.06-96 96 0 8.84 7.16 16 16 16s16-7.16 16-16c0-35.3 28.72-64 64-64 8.84 0 16-7.16 16-16s-7.16-16-16-16zM96.06 459.17c0 3.15.93 6.22 2.68 8.84l24.51 36.84c2.97 4.46 7.97 7.14 13.32 7.14h78.85c5.36 0 10.36-2.68 13.32-7.14l24.51-36.84c1.74-2.62 2.67-5.7 2.68-8.84l.05-43.18H96.02l.04 43.18zM176 0C73.72 0 0 82.97 0 176c0 44.37 16.45 84.85 43.56 115.78 16.64 18.99 42.74 58.8 52.42 92.16v.06h48v-.12c-.01-4.77-.72-9.51-2.15-14.07-5.59-17.81-22.82-64.77-62.17-109.67-20.54-23.43-31.52-53.15-31.61-84.14-.2-73.64 59.67-128 127.95-128 70.58 0 128 57.42 128 128 0 30.97-11.24 60.85-31.65 84.14-39.11 44.61-56.42 91.47-62.1 109.46a47.507 47.507 0 0 0-2.22 14.3v.1h48v-.05c9.68-33.37 35.78-73.18 52.42-92.16C335.55 260.85 352 220.37 352 176 352 78.8 273.2 0 176 0z"]},on={prefix:"far",iconName:"square",icon:[448,512,[],"f0c8","M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zm-6 400H54c-3.3 0-6-2.7-6-6V86c0-3.3 2.7-6 6-6h340c3.3 0 6 2.7 6 6v340c0 3.3-2.7 6-6 6z"]},ln=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.onClick=function(){this.props.onClick&&this.props.onClick()},t.prototype.render=function(){var e=this;return s.createElement("div",{className:"title",onClick:function(){return e.onClick()}},s.createElement("div",{className:"titleIcon"},s.createElement(w,{icon:this.props.icon,color:this.props.color})),s.createElement("div",{className:"titleText"},this.props.label||"no name"))},t}(s.Component),sn=function(e){function t(t){var r=e.call(this,t)||this;return r.state={popupVisible:!1},r.extensionRef=s.createRef(),r}return a(t,e),t.prototype.showPopup=function(){this.setState({popupVisible:!0})},t.prototype.componentDidMount=function(){this._popup&&this._popup.focus()},t.prototype.componentDidUpdate=function(){this._popup&&this._popup.focus()},t.prototype.render=function(){var e=this;if(!this.props.extensibilityGroups)return null;for(var t=[],r=0,n=this.props.extensibilityGroups;r<n.length;r++){var a=n[r];a.predicate(this.props.target)&&t.push.apply(t,a.entries)}return 0===t.length?null:s.createElement("div",{ref:this.extensionRef,className:"extensions",onClick:function(){return e.showPopup()}},s.createElement("div",{title:"Additional options",className:"icon"},s.createElement(w,{icon:Y})),s.createElement("div",{ref:function(t){e._popup=t},tabIndex:-1,className:this.state.popupVisible?"popup show":"popup",onBlur:function(){return e.setState({popupVisible:!1})}},t.map((function(t){return s.createElement("div",{key:t.label,className:"popupMenu",onClick:function(){return t.action(e.props.target)}},t.label)}))))},t}(s.Component),pn=function(e){function t(t){var r=e.call(this,t)||this,n=r.props.mesh;return r.state={isBoundingBoxEnabled:n.showBoundingBox,isVisible:r.props.mesh.isVisible},r}return a(t,e),t.prototype.showBoundingBox=function(){this.props.mesh.showBoundingBox=!this.state.isBoundingBoxEnabled,this.setState({isBoundingBoxEnabled:!this.state.isBoundingBoxEnabled})},t.prototype.switchVisibility=function(){var e=!this.state.isVisible;this.setState({isVisible:e}),this.props.mesh.isVisible=e},t.prototype.render=function(){var e=this,t=this.props.mesh,r=this.state.isVisible?s.createElement(w,{icon:rn}):s.createElement(w,{icon:nn,className:"isNotActive"});return s.createElement("div",{className:"meshTools"},s.createElement(ln,{label:t.name,onClick:function(){return e.props.onClick()},icon:W,color:"dodgerblue"}),s.createElement("div",{className:this.state.isBoundingBoxEnabled?"bounding-box selected icon":"bounding-box icon",onClick:function(){return e.showBoundingBox()},title:"Show/Hide bounding box"},s.createElement(w,{icon:on})),s.createElement("div",{className:"visibility icon",onClick:function(){return e.switchVisibility()},title:"Show/Hide mesh"},r),s.createElement(sn,{target:t,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),cn=function(e){function t(t){var r=e.call(this,t)||this,n=r.props.camera,a=n.getScene();return r.state={isActive:a.activeCamera===n,isGizmoEnabled:n.reservedDataStore&&n.reservedDataStore.cameraGizmo},r}return a(t,e),t.prototype.setActive=function(){var e=this.props.camera;e.getScene().activeCamera=e,e.attachControl(!0),this.setState({isActive:!0})},t.prototype.componentDidMount=function(){var e=this,t=this.props.camera.getScene();this._onBeforeRenderObserver=t.onBeforeRenderObservable.add((function(){var r=e.props.camera;e.state.isActive&&t.activeCameras&&t.activeCameras.length<=1&&t.activeCamera!==r&&r.detachControl();var n=t.activeCamera===r;n!==e.state.isActive&&e.setState({isActive:n})}))},t.prototype.componentWillUnmount=function(){this._onBeforeRenderObserver&&this.props.camera.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver)},t.prototype.toggleGizmo=function(){var e=this.props.camera;e.reservedDataStore&&e.reservedDataStore.cameraGizmo?(e.getScene().reservedDataStore&&e.getScene().reservedDataStore.gizmoManager&&e.getScene().reservedDataStore.gizmoManager.attachToMesh(null),this.props.globalState.enableCameraGizmo(e,!1),this.setState({isGizmoEnabled:!1})):(this.props.globalState.enableCameraGizmo(e,!0),this.setState({isGizmoEnabled:!0}))},t.prototype.render=function(){var e=this,t=this.state.isActive?s.createElement(w,{icon:ge}):s.createElement(w,{icon:ge,className:"isNotActive"}),r=this.props.camera.getScene(),n=this.state.isGizmoEnabled||this.props.camera&&this.props.camera.reservedDataStore&&this.props.camera.reservedDataStore.cameraGizmo?s.createElement(w,{icon:K}):s.createElement(w,{icon:K,className:"isNotActive"});return s.createElement("div",{className:"cameraTools"},s.createElement(ln,{label:this.props.camera.name,onClick:function(){return e.props.onClick()},icon:j,color:"green"}),(!r.activeCameras||0===r.activeCameras.length)&&s.createElement("div",{className:"activeCamera icon",onClick:function(){return e.setActive()},title:"Set as main camera and attach to controls"},t),s.createElement("div",{className:"enableGizmo icon",onClick:function(){return e.toggleGizmo()},title:"Turn on/off the camera's gizmo"},n),s.createElement(sn,{target:this.props.camera,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),un=function(e){function t(t){var r=e.call(this,t)||this,n=r.props.light;return r.state={isEnabled:n.isEnabled(),isGizmoEnabled:n.reservedDataStore&&n.reservedDataStore.lightGizmo},r}return a(t,e),t.prototype.switchIsEnabled=function(){var e=this.props.light;e.setEnabled(!e.isEnabled()),this.setState({isEnabled:e.isEnabled()})},t.prototype.toggleGizmo=function(){var e=this.props.light;e.reservedDataStore&&e.reservedDataStore.lightGizmo?(e.getScene().reservedDataStore&&e.getScene().reservedDataStore.gizmoManager&&e.getScene().reservedDataStore.gizmoManager.attachToMesh(null),this.props.globalState.enableLightGizmo(e,!1),this.setState({isGizmoEnabled:!1})):(this.props.globalState.enableLightGizmo(e,!0),this.setState({isGizmoEnabled:!0}))},t.prototype.render=function(){var e=this,t=this.state.isEnabled?s.createElement(w,{icon:an}):s.createElement(w,{icon:an,className:"isNotActive"}),r=this.state.isGizmoEnabled||this.props.light&&this.props.light.reservedDataStore&&this.props.light.reservedDataStore.lightGizmo?s.createElement(w,{icon:K}):s.createElement(w,{icon:K,className:"isNotActive"});return s.createElement("div",{className:"lightTools"},s.createElement(ln,{label:this.props.light.name,onClick:function(){return e.props.onClick()},icon:re,color:"yellow"}),s.createElement("div",{className:"visibility icon",onClick:function(){return e.switchIsEnabled()},title:"Turn on/off the light"},t),s.createElement("div",{className:"enableGizmo icon",onClick:function(){return e.toggleGizmo()},title:"Turn on/off the light's gizmo"},r),s.createElement(sn,{target:this.props.light,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),dn=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this,t="NodeMaterial"===this.props.material.getClassName()?s.createElement("div",{className:"icon",onClick:function(){e.props.material.edit()},title:"Node Material Editor",color:"white"},s.createElement(w,{icon:ie})):null;return s.createElement("div",{className:"materialTools"},s.createElement(ln,{label:this.props.material.name,onClick:function(){return e.props.onClick()},icon:A,color:"orange"}),s.createElement(sn,{target:this.props.material,extensibilityGroups:this.props.extensibilityGroups}),t)},t}(s.Component),hn=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this;return s.createElement("div",{className:"textureTools"},s.createElement(ln,{label:this.props.texture.name,onClick:function(){return e.props.onClick()},icon:ee,color:"mediumpurple"}),s.createElement(sn,{target:this.props.texture,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),bn=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this,t=this.props.transformNode;return s.createElement("div",{className:"transformNodeTools"},s.createElement(ln,{label:t.name,onClick:function(){return e.props.onClick()},icon:V,color:"cornflowerblue"}),s.createElement(sn,{target:t,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),mn=function(e){function t(t){var r=e.call(this,t)||this,n=r.props.control;return r.state={isActive:n.isHighlighted,isVisible:n.isVisible},r}return a(t,e),t.prototype.highlight=function(){var e=this.props.control;e.isHighlighted=!e.isHighlighted,this.setState({isActive:e.isHighlighted})},t.prototype.switchVisibility=function(){var e=!this.state.isVisible;this.setState({isVisible:e}),this.props.control.isVisible=e},t.prototype.render=function(){var e=this,t=this.props.control,r=(t.name||"No name")+" ["+t.getClassName()+"]",n=this.state.isActive?s.createElement(w,{icon:J}):s.createElement(w,{icon:J,className:"isNotActive"}),a=this.state.isVisible?s.createElement(w,{icon:K}):s.createElement(w,{icon:X,className:"isNotActive"});return s.createElement("div",{className:"controlTools"},s.createElement(ln,{label:r,onClick:function(){return e.props.onClick()},icon:oe,color:"greenyellow"}),s.createElement("div",{className:"highlight icon",onClick:function(){return e.highlight()},title:"Highlight this control"},n),s.createElement("div",{className:"visibility icon",onClick:function(){return e.switchVisibility()},title:"Show/Hide control"},a),s.createElement(sn,{target:t,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),gn=function(e){function t(t){var r=e.call(this,t)||this;return r.state={isInPickingMode:!1},r}return a(t,e),t.prototype.componentWillUnmount=function(){var e=this.props.texture;this._onControlPickedObserver&&(e.onControlPickedObservable.remove(this._onControlPickedObserver),this._onControlPickedObserver=null)},t.prototype.onPickingMode=function(){var e=this,t=this.props.texture;this._onControlPickedObserver&&(t.onControlPickedObservable.remove(this._onControlPickedObserver),this._onControlPickedObserver=null),this.state.isInPickingMode||(this._onControlPickedObserver=t.onControlPickedObservable.add((function(t){e.props.onSelectionChangedObservable&&("ScrollViewerWindow"===t.getClassName()&&(t=t.getAscendantOfClass("ScrollViewer")),e.props.onSelectionChangedObservable.notifyObservers(t))}))),this.setState({isInPickingMode:!this.state.isInPickingMode})},t.prototype.render=function(){var e=this;return s.createElement("div",{className:"adtextureTools"},s.createElement(ln,{label:this.props.texture.name,onClick:function(){return e.props.onClick()},icon:ee,color:"mediumpurple"}),s.createElement("div",{className:this.state.isInPickingMode?"pickingMode selected icon":"pickingMode icon",onClick:function(){return e.onPickingMode()},title:"Turn picking mode on/off"},s.createElement(w,{icon:B})),s.createElement(sn,{target:this.props.texture,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),fn=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this,t=this.props.animationGroup;return s.createElement("div",{className:"animationGroupTools"},s.createElement(ln,{label:t.name,onClick:function(){return e.props.onClick()},icon:te,color:"cornflowerblue"}),s.createElement(sn,{target:t,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),vn=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this;return s.createElement("div",{className:"postProcessTools"},s.createElement(ln,{label:this.props.postProcess.name,onClick:function(){return e.props.onClick()},icon:ne,color:"red"}),s.createElement(sn,{target:this.props.postProcess,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),yn=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this;return s.createElement("div",{className:"postProcessTools"},s.createElement(ln,{label:this.props.renderPipeline.name,onClick:function(){return e.props.onClick()},icon:ne,color:"orangered"}),s.createElement(sn,{target:this.props.renderPipeline,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),Cn=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this,t=this.props.skeleton;return s.createElement("div",{className:"skeletonTools"},s.createElement(ln,{label:t.name||"no name",onClick:function(){return e.props.onClick()},icon:ce,color:"gray"}),s.createElement(sn,{target:t,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),En=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this,t=this.props.bone;return s.createElement("div",{className:"skeletonTools"},s.createElement(ln,{label:t.name||"no name",onClick:function(){return e.props.onClick()},icon:D,color:"lightgray"}),s.createElement(sn,{target:t,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),On=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this;return s.createElement("div",{className:"particleSystemTools"},s.createElement(ln,{label:this.props.system.name||"Particle system",onClick:function(){return e.props.onClick()},icon:R,color:"crimson"}),s.createElement(sn,{target:this.props.system,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),Sn=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this;return s.createElement("div",{className:"spriteManagerTools"},s.createElement(ln,{label:this.props.spriteManager.name||"No name",onClick:function(){return e.props.onClick()},icon:T,color:"blanchedalmond"}),s.createElement(sn,{target:this.props.spriteManager,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),xn=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this;return s.createElement("div",{className:"spriteTools"},s.createElement(ln,{label:this.props.sprite.name||"No name",onClick:function(){return e.props.onClick()},icon:$,color:"blanchedalmond"}),s.createElement(sn,{target:this.props.sprite,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),Pn=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this,t=this.props.targetedAnimation;return s.createElement("div",{className:"targetedAnimationTools"},s.createElement(ln,{label:t.animation.name,onClick:function(){return e.props.onClick()},icon:q,color:"cornflowerblue"}),s.createElement(sn,{target:t,extensibilityGroups:this.props.extensibilityGroups}))},t}(s.Component),wn=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.onClick=function(){this.props.onClick&&this.props.onClick()},t.prototype.render=function(){var e=this,t=this.props.entity;if(t&&t.getClassName){var r=t.getClassName();if(-1!==r.indexOf("Mesh")){var n=t;return n.isAnInstance||n.getTotalVertices()>0?s.createElement(pn,{globalState:this.props.globalState,extensibilityGroups:this.props.extensibilityGroups,mesh:n,onClick:function(){return e.onClick()}}):s.createElement(bn,{extensibilityGroups:this.props.extensibilityGroups,transformNode:t,onClick:function(){return e.onClick()}})}if(-1!==r.indexOf("SpriteManager"))return s.createElement(Sn,{extensibilityGroups:this.props.extensibilityGroups,spriteManager:t,onClick:function(){return e.onClick()}});if(-1!==r.indexOf("Sprite"))return s.createElement(xn,{extensibilityGroups:this.props.extensibilityGroups,sprite:t,onClick:function(){return e.onClick()}});if(-1!==r.indexOf("Skeleton"))return s.createElement(Cn,{extensibilityGroups:this.props.extensibilityGroups,skeleton:t,onClick:function(){return e.onClick()}});if(-1!==r.indexOf("Bone"))return s.createElement(En,{extensibilityGroups:this.props.extensibilityGroups,bone:t,onClick:function(){return e.onClick()}});if(-1!==r.indexOf("TransformNode"))return s.createElement(bn,{extensibilityGroups:this.props.extensibilityGroups,transformNode:t,onClick:function(){return e.onClick()}});if(-1!==r.indexOf("Camera"))return s.createElement(cn,{globalState:this.props.globalState,extensibilityGroups:this.props.extensibilityGroups,camera:t,onClick:function(){return e.onClick()}});if(-1!==r.indexOf("Light",r.length-5))return s.createElement(un,{globalState:this.props.globalState,extensibilityGroups:this.props.extensibilityGroups,light:t,onClick:function(){return e.onClick()}});if(-1!==r.indexOf("Material"))return s.createElement(dn,{extensibilityGroups:this.props.extensibilityGroups,material:t,onClick:function(){return e.onClick()}});if(-1!==r.indexOf("ParticleSystem"))return s.createElement(On,{extensibilityGroups:this.props.extensibilityGroups,system:t,onClick:function(){return e.onClick()}});if("AdvancedDynamicTexture"===r)return s.createElement(gn,{onSelectionChangedObservable:this.props.globalState.onSelectionChangedObservable,extensibilityGroups:this.props.extensibilityGroups,texture:t,onClick:function(){return e.onClick()}});if("AnimationGroup"===r)return s.createElement(fn,{extensibilityGroups:this.props.extensibilityGroups,animationGroup:t,onClick:function(){return e.onClick()}});if("TargetedAnimation"===r)return s.createElement(Pn,{extensibilityGroups:this.props.extensibilityGroups,targetedAnimation:t,onClick:function(){return e.onClick()}});if(-1!==r.indexOf("Texture"))return s.createElement(hn,{extensibilityGroups:this.props.extensibilityGroups,texture:t,onClick:function(){return e.onClick()}});if(-1!==r.indexOf("RenderingPipeline"))return s.createElement(yn,{extensibilityGroups:this.props.extensibilityGroups,renderPipeline:t,onClick:function(){return e.onClick()}});if(-1!==r.indexOf("PostProcess"))return s.createElement(vn,{extensibilityGroups:this.props.extensibilityGroups,postProcess:t,onClick:function(){return e.onClick()}});if(t._host)return s.createElement(mn,{extensibilityGroups:this.props.extensibilityGroups,control:t,onClick:function(){return e.onClick()}})}return s.createElement("div",{className:"meshTools"},s.createElement(ln,{label:t.name,onClick:function(){return e.onClick()},icon:se,color:"cornflowerblue"}))},t}(s.Component),kn=function(){function e(){}return e.LookForItem=function(t,r){if(t===r)return!0;var n=t.getChildren?t.getChildren():t.children;if(n&&"MultiMaterial"!==t.getClassName())for(var a=0,o=n;a<o.length;a++){var i=o[a];if(e.LookForItem(i,r))return!0}return!1},e._RecursiveRemoveHiddenMeshesAndHoistChildren=function(t){for(var r=[],n=0,a=t;n<a.length;n++){var o=a[n];o.reservedDataStore&&o.reservedDataStore.hidden&&o.getChildMeshes?e._RecursiveRemoveHiddenMeshesAndHoistChildren(o.getChildMeshes()).forEach((function(e){r.push(e)})):o.reservedDataStore&&o.reservedDataStore.hidden||r.push(o)}return r},e.SortAndFilter=function(t,r){if(!r)return[];var n=e._RecursiveRemoveHiddenMeshesAndHoistChildren(r);return t&&t.reservedDataStore&&t.reservedDataStore.detachedChildren&&n.push.apply(n,t.reservedDataStore.detachedChildren),n.sort((function(e,t){var r=(e.name||"").toLowerCase(),n=(t.name||"").toLowerCase();return r===n?0:r>n?1:-1}))},e}(),Nn=function(e){function t(t){var r=e.call(this,t)||this;return r._wasSelected=!1,r.state={isSelected:r.props.entity===r.props.selectedEntity,isExpanded:r.props.mustExpand||kn.LookForItem(r.props.entity,r.props.selectedEntity)},r}return a(t,e),t.prototype.switchExpandedState=function(){this.setState({isExpanded:!this.state.isExpanded})},t.prototype.shouldComponentUpdate=function(e,t){if(!t.isExpanded&&this.state.isExpanded)return!0;if(e.selectedEntity){if(e.entity===e.selectedEntity)return t.isSelected=!0,!0;if(t.isSelected=!1,kn.LookForItem(e.entity,e.selectedEntity))return t.isExpanded=!0,!0}return!0},t.prototype.scrollIntoView=function(){var e=c.findDOMNode(this);e&&e.scrollIntoView(!1)},t.prototype.componentDidMount=function(){this.state.isSelected&&this.scrollIntoView()},t.prototype.componentDidUpdate=function(){this.state.isSelected&&!this._wasSelected&&this.scrollIntoView(),this._wasSelected=!1},t.prototype.onSelect=function(){if(this.props.globalState.onSelectionChangedObservable){this._wasSelected=!0;var e=this.props.entity;this.props.globalState.onSelectionChangedObservable.notifyObservers(e)}},t.prototype.renderChildren=function(){var e=this,r=this.props.entity;return(r.getChildren||r.children)&&this.state.isExpanded?kn.SortAndFilter(r,r.getChildren?r.getChildren():r.children).map((function(r,n){return s.createElement(t,{globalState:e.props.globalState,mustExpand:e.props.mustExpand,extensibilityGroups:e.props.extensibilityGroups,selectedEntity:e.props.selectedEntity,key:n,offset:e.props.offset+2,entity:r,filter:e.props.filter})})):null},t.prototype.render=function(){var e=this,t={paddingLeft:10*(this.props.offset+.5)+"px"},r=this.props.entity,n=this.state.isExpanded?s.createElement(w,{icon:ae}):s.createElement(w,{icon:le}),a=("MultiMaterial"===r.getClassName()?[]:kn.SortAndFilter(r,r.getChildren?r.getChildren():r.children)).length>0;if(r.reservedDataStore||(r.reservedDataStore={}),r.reservedDataStore.setExpandedState=function(t){e.setState({isExpanded:t})},r.reservedDataStore.isExpanded=this.state.isExpanded,this.props.filter){var o=this.props.filter.toLowerCase();if(!r.name||-1===r.name.toLowerCase().indexOf(o)){if(!a)return null;if(r.getDescendants&&0===r.getDescendants(!1,(function(e){return e.name&&-1!==e.name.toLowerCase().indexOf(o)})).length)return null}}return s.createElement("div",null,s.createElement("div",{className:this.state.isSelected?"itemContainer selected":"itemContainer",style:t},a&&s.createElement("div",{className:"arrow icon",onClick:function(){return e.switchExpandedState()}},n),s.createElement(wn,{globalState:this.props.globalState,extensibilityGroups:this.props.extensibilityGroups,label:r.name,entity:r,onClick:function(){return e.onSelect()}})),this.renderChildren())},t}(s.Component),Tn=r(6),_n=r.n(Tn),Mn=r(4),Ln=r.n(Mn);function Dn(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return"function"==typeof e&&e.apply(void 0,r)}function Rn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var An="react-contextmenu",In="react-contextmenu--visible",jn="react-contextmenu-wrapper",zn="react-contextmenu-item",Fn="react-contextmenu-item--active",Gn="react-contextmenu-item--disabled",Vn="react-contextmenu-item--divider",Un="react-contextmenu-item--selected",Hn="react-contextmenu-submenu",Bn={},Wn=Boolean("undefined"!=typeof window&&window.document&&window.document.createElement),Yn="REACT_CONTEXTMENU_SHOW",Zn="REACT_CONTEXTMENU_HIDE";function Kn(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:window,n=void 0;"function"==typeof window.CustomEvent?n=new window.CustomEvent(e,{detail:t}):(n=document.createEvent("CustomEvent")).initCustomEvent(e,!1,!0,t),r&&(r.dispatchEvent(n),Ln()(Bn,t))}function Xn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1];Kn(Yn,Ln()({},e,{type:Yn}),t)}function Qn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1];Kn(Zn,Ln()({},e,{type:Zn}),t)}var qn=new function e(){var t=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.handleShowEvent=function(e){for(var r in t.callbacks)Rn(t.callbacks,r)&&t.callbacks[r].show(e)},this.handleHideEvent=function(e){for(var r in t.callbacks)Rn(t.callbacks,r)&&t.callbacks[r].hide(e)},this.register=function(e,r){var n=Math.random().toString(36).substring(7);return t.callbacks[n]={show:e,hide:r},n},this.unregister=function(e){e&&t.callbacks[e]&&delete t.callbacks[e]},this.callbacks={},Wn&&(window.addEventListener(Yn,this.handleShowEvent),window.addEventListener(Zn,this.handleHideEvent))},$n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Jn=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}();function ea(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ta(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function ra(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}var na=function(e){function t(){var e,r,n;ta(this,t);for(var a=arguments.length,o=Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=n=ra(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(o))),n.handleClick=function(e){0!==e.button&&1!==e.button&&e.preventDefault(),n.props.disabled||n.props.divider||(Dn(n.props.onClick,e,Ln()({},n.props.data,Bn.data),Bn.target),n.props.preventClose||Qn())},ra(n,r)}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),Jn(t,[{key:"render",value:function(){var e,t=this,r=this.props,n=r.attributes,a=r.children,o=r.className,i=r.disabled,l=r.divider,s=r.selected,c=_n()(o,zn,n.className,(ea(e={},_n()(Gn,n.disabledClassName),i),ea(e,_n()(Vn,n.dividerClassName),l),ea(e,_n()(Un,n.selectedClassName),s),e));return p.a.createElement("div",$n({},n,{className:c,role:"menuitem",tabIndex:"-1","aria-disabled":i?"true":"false","aria-orientation":l?"horizontal":null,ref:function(e){t.ref=e},onMouseMove:this.props.onMouseMove,onMouseLeave:this.props.onMouseLeave,onTouchEnd:this.handleClick,onClick:this.handleClick}),l?null:a)}}]),t}(s.Component);na.propTypes={attributes:b.a.object,children:b.a.node,className:b.a.string,data:b.a.object,disabled:b.a.bool,divider:b.a.bool,onClick:b.a.func,onMouseLeave:b.a.func,onMouseMove:b.a.func,preventClose:b.a.bool,selected:b.a.bool},na.defaultProps={attributes:{},children:null,className:"",data:{},disabled:!1,divider:!1,onClick:function(){return null},onMouseMove:function(){return null},onMouseLeave:function(){return null},preventClose:!1,selected:!1};var aa=na;var oa=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return ia.call(r),r.seletedItemRef=null,r.state={selectedItem:null,forceSubMenuOpen:!1},r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),t}(s.Component);oa.propTypes={children:b.a.node.isRequired};var ia=function(){var e=this;this.handleKeyNavigation=function(t){if(!1!==e.state.isVisible)switch(t.keyCode){case 37:case 27:t.preventDefault(),e.hideMenu(t);break;case 38:t.preventDefault(),e.selectChildren(!0);break;case 40:t.preventDefault(),e.selectChildren(!1);break;case 39:e.tryToOpenSubMenu(t);break;case 13:t.preventDefault(),e.tryToOpenSubMenu(t);var r=e.seletedItemRef&&e.seletedItemRef.props&&e.seletedItemRef.props.disabled;e.seletedItemRef&&e.seletedItemRef.ref instanceof HTMLElement&&!r?e.seletedItemRef.ref.click():e.hideMenu(t)}},this.handleForceClose=function(){e.setState({forceSubMenuOpen:!1})},this.tryToOpenSubMenu=function(t){e.state.selectedItem&&e.state.selectedItem.type===e.getSubMenuType()&&(t.preventDefault(),e.setState({forceSubMenuOpen:!0}))},this.selectChildren=function(t){var r=e.state.selectedItem,n=[],a=0,o={};if(p.a.Children.forEach(e.props.children,(function t(r,i){r&&([aa,e.getSubMenuType()].indexOf(r.type)<0?p.a.Children.forEach(r.props.children,t):r.props.divider||(r.props.disabled&&(++a,o[i]=!0),n.push(r)))})),a!==n.length){var i=function(e){var r=e;do{t?--r:++r,r<0?r=n.length-1:r>=n.length&&(r=0)}while(r!==e&&o[r]);return r===e?null:r}(n.indexOf(r));null!==i&&e.setState({selectedItem:n[i],forceSubMenuOpen:!1})}},this.onChildMouseMove=function(t){e.state.selectedItem!==t&&e.setState({selectedItem:t,forceSubMenuOpen:!1})},this.onChildMouseLeave=function(){e.setState({selectedItem:null,forceSubMenuOpen:!1})},this.renderChildren=function(t){return p.a.Children.map(t,(function(t){var r={};return p.a.isValidElement(t)?[aa,e.getSubMenuType()].indexOf(t.type)<0?(r.children=e.renderChildren(t.props.children),p.a.cloneElement(t,r)):(r.onMouseLeave=e.onChildMouseLeave.bind(e),t.type===e.getSubMenuType()&&(r.forceOpen=e.state.forceSubMenuOpen&&e.state.selectedItem===t,r.forceClose=e.handleForceClose,r.parentKeyNavigationHandler=e.handleKeyNavigation),t.props.divider||e.state.selectedItem!==t?(r.onMouseMove=function(){return e.onChildMouseMove(t)},p.a.cloneElement(t,r)):(r.selected=!0,r.ref=function(t){e.seletedItemRef=t},p.a.cloneElement(t,r))):t}))}},la=oa,sa=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},pa=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}();function ca(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var ua=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.getMenuPosition=function(){var e=window,t=e.innerWidth,n=e.innerHeight,a=r.subMenu.getBoundingClientRect(),o={};return a.bottom>n?o.bottom=0:o.top=0,a.right<t?o.left="100%":o.right="100%",o},r.getRTLMenuPosition=function(){var e=window.innerHeight,t=r.subMenu.getBoundingClientRect(),n={};return t.bottom>e?n.bottom=0:n.top=0,t.left<0?n.left="100%":n.right="100%",n},r.hideSubMenu=function(e){e.detail&&e.detail.id&&r.menu&&e.detail.id!==r.menu.id||(r.props.forceOpen&&r.props.forceClose(),r.setState({visible:!1,selectedItem:null}),r.unregisterHandlers())},r.handleClick=function(e){e.preventDefault(),r.props.disabled||(Dn(r.props.onClick,e,Ln()({},r.props.data,Bn.data),Bn.target),r.props.onClick&&!r.props.preventCloseOnClick&&Qn())},r.handleMouseEnter=function(){r.closetimer&&clearTimeout(r.closetimer),r.props.disabled||r.state.visible||(r.opentimer=setTimeout((function(){return r.setState({visible:!0,selectedItem:null})}),r.props.hoverDelay))},r.handleMouseLeave=function(){r.opentimer&&clearTimeout(r.opentimer),r.state.visible&&(r.closetimer=setTimeout((function(){return r.setState({visible:!1,selectedItem:null})}),r.props.hoverDelay))},r.menuRef=function(e){r.menu=e},r.subMenuRef=function(e){r.subMenu=e},r.registerHandlers=function(){document.removeEventListener("keydown",r.props.parentKeyNavigationHandler),document.addEventListener("keydown",r.handleKeyNavigation)},r.unregisterHandlers=function(e){document.removeEventListener("keydown",r.handleKeyNavigation),e||document.addEventListener("keydown",r.props.parentKeyNavigationHandler)},r.state=Ln()({},r.state,{visible:!1}),r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),pa(t,[{key:"componentDidMount",value:function(){this.listenId=qn.register((function(){}),this.hideSubMenu)}},{key:"getSubMenuType",value:function(){return t}},{key:"shouldComponentUpdate",value:function(e,t){return this.isVisibilityChange=!(this.state.visible===t.visible&&this.props.forceOpen===e.forceOpen||this.state.visible&&e.forceOpen||this.props.forceOpen&&t.visible),!0}},{key:"componentDidUpdate",value:function(){var e=this;if(this.isVisibilityChange)if(this.props.forceOpen||this.state.visible){(window.requestAnimationFrame||setTimeout)((function(){var t=e.props.rtl?e.getRTLMenuPosition():e.getMenuPosition();e.subMenu.style.removeProperty("top"),e.subMenu.style.removeProperty("bottom"),e.subMenu.style.removeProperty("left"),e.subMenu.style.removeProperty("right"),Rn(t,"top")&&(e.subMenu.style.top=t.top),Rn(t,"left")&&(e.subMenu.style.left=t.left),Rn(t,"bottom")&&(e.subMenu.style.bottom=t.bottom),Rn(t,"right")&&(e.subMenu.style.right=t.right),e.subMenu.classList.add(In),e.registerHandlers(),e.setState({selectedItem:null})}))}else{this.subMenu.addEventListener("transitionend",(function t(){e.subMenu.removeEventListener("transitionend",t),e.subMenu.style.removeProperty("bottom"),e.subMenu.style.removeProperty("right"),e.subMenu.style.top=0,e.subMenu.style.left="100%",e.unregisterHandlers()})),this.subMenu.classList.remove(In)}}},{key:"componentWillUnmount",value:function(){this.listenId&&qn.unregister(this.listenId),this.opentimer&&clearTimeout(this.opentimer),this.closetimer&&clearTimeout(this.closetimer),this.unregisterHandlers(!0)}},{key:"render",value:function(){var e,t=this.props,r=t.children,n=t.attributes,a=t.disabled,o=t.title,i=t.selected,l=this.state.visible,s={ref:this.menuRef,onMouseEnter:this.handleMouseEnter,onMouseLeave:this.handleMouseLeave,className:_n()(zn,Hn,n.listClassName),style:{position:"relative"}},c={className:_n()(zn,n.className,(e={},ca(e,_n()(Gn,n.disabledClassName),a),ca(e,_n()(Fn,n.visibleClassName),l),ca(e,_n()(Un,n.selectedClassName),i),e)),onMouseMove:this.props.onMouseMove,onMouseOut:this.props.onMouseOut,onClick:this.handleClick},u={ref:this.subMenuRef,style:{position:"absolute",transition:"opacity 1ms",top:0,left:"100%"},className:_n()(An,this.props.className)};return p.a.createElement("nav",sa({},s,{role:"menuitem",tabIndex:"-1","aria-haspopup":"true"}),p.a.createElement("div",sa({},n,c),o),p.a.createElement("nav",sa({},u,{role:"menu",tabIndex:"-1"}),this.renderChildren(r)))}}]),t}(la);ua.propTypes={children:b.a.node.isRequired,attributes:b.a.object,title:b.a.node.isRequired,className:b.a.string,disabled:b.a.bool,hoverDelay:b.a.number,rtl:b.a.bool,selected:b.a.bool,onMouseMove:b.a.func,onMouseOut:b.a.func,forceOpen:b.a.bool,forceClose:b.a.func,parentKeyNavigationHandler:b.a.func},ua.defaultProps={disabled:!1,hoverDelay:500,attributes:{},className:"",rtl:!1,selected:!1,onMouseMove:function(){return null},onMouseOut:function(){return null},forceOpen:!1,forceClose:function(){return null},parentKeyNavigationHandler:function(){return null}};var da=ua,ha=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}();var ba=function(e){function t(e){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);var r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.registerHandlers=function(){document.addEventListener("mousedown",r.handleOutsideClick),document.addEventListener("touchstart",r.handleOutsideClick),r.props.preventHideOnScroll||document.addEventListener("scroll",r.handleHide),r.props.preventHideOnContextMenu||document.addEventListener("contextmenu",r.handleHide),document.addEventListener("keydown",r.handleKeyNavigation),r.props.preventHideOnResize||window.addEventListener("resize",r.handleHide)},r.unregisterHandlers=function(){document.removeEventListener("mousedown",r.handleOutsideClick),document.removeEventListener("touchstart",r.handleOutsideClick),document.removeEventListener("scroll",r.handleHide),document.removeEventListener("contextmenu",r.handleHide),document.removeEventListener("keydown",r.handleKeyNavigation),window.removeEventListener("resize",r.handleHide)},r.handleShow=function(e){if(e.detail.id===r.props.id&&!r.state.isVisible){var t=e.detail.position,n=t.x,a=t.y;r.setState({isVisible:!0,x:n,y:a}),r.registerHandlers(),Dn(r.props.onShow,e)}},r.handleHide=function(e){!r.state.isVisible||e.detail&&e.detail.id&&e.detail.id!==r.props.id||(r.unregisterHandlers(),r.setState({isVisible:!1,selectedItem:null,forceSubMenuOpen:!1}),Dn(r.props.onHide,e))},r.handleOutsideClick=function(e){r.menu.contains(e.target)||Qn()},r.handleMouseLeave=function(e){e.preventDefault(),Dn(r.props.onMouseLeave,e,Ln()({},r.props.data,Bn.data),Bn.target),r.props.hideOnLeave&&Qn()},r.handleContextMenu=function(e){e.preventDefault(),r.handleHide(e)},r.hideMenu=function(e){27!==e.keyCode&&13!==e.keyCode||Qn()},r.getMenuPosition=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n={top:t,left:e};if(!r.menu)return n;var a=window,o=a.innerWidth,i=a.innerHeight,l=r.menu.getBoundingClientRect();return t+l.height>i&&(n.top-=l.height),e+l.width>o&&(n.left-=l.width),n.top<0&&(n.top=l.height<i?(i-l.height)/2:0),n.left<0&&(n.left=l.width<o?(o-l.width)/2:0),n},r.getRTLMenuPosition=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n={top:t,left:e};if(!r.menu)return n;var a=window,o=a.innerWidth,i=a.innerHeight,l=r.menu.getBoundingClientRect();return n.left=e-l.width,t+l.height>i&&(n.top-=l.height),n.left<0&&(n.left+=l.width),n.top<0&&(n.top=l.height<i?(i-l.height)/2:0),n.left+l.width>o&&(n.left=l.width<o?(o-l.width)/2:0),n},r.menuRef=function(e){r.menu=e},r.state=Ln()({},r.state,{x:0,y:0,isVisible:!1}),r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),ha(t,[{key:"getSubMenuType",value:function(){return da}},{key:"componentDidMount",value:function(){this.listenId=qn.register(this.handleShow,this.handleHide)}},{key:"componentDidUpdate",value:function(){var e=this,t=window.requestAnimationFrame||setTimeout;this.state.isVisible?t((function(){var r=e.state,n=r.x,a=r.y,o=e.props.rtl?e.getRTLMenuPosition(n,a):e.getMenuPosition(n,a),i=o.top,l=o.left;t((function(){e.menu&&(e.menu.style.top=i+"px",e.menu.style.left=l+"px",e.menu.style.opacity=1,e.menu.style.pointerEvents="auto")}))})):t((function(){e.menu&&(e.menu.style.opacity=0,e.menu.style.pointerEvents="none")}))}},{key:"componentWillUnmount",value:function(){this.listenId&&qn.unregister(this.listenId),this.unregisterHandlers()}},{key:"render",value:function(){var e,t,r,n=this.props,a=n.children,o=n.className,i=n.style,l=this.state.isVisible,s=Ln()({},i,{position:"fixed",opacity:0,pointerEvents:"none"}),c=_n()(An,o,(r=l,(t=In)in(e={})?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e));return p.a.createElement("nav",{role:"menu",tabIndex:"-1",ref:this.menuRef,style:s,className:c,onContextMenu:this.handleContextMenu,onMouseLeave:this.handleMouseLeave},this.renderChildren(a))}}]),t}(la);ba.propTypes={id:b.a.string.isRequired,children:b.a.node.isRequired,data:b.a.object,className:b.a.string,hideOnLeave:b.a.bool,rtl:b.a.bool,onHide:b.a.func,onMouseLeave:b.a.func,onShow:b.a.func,preventHideOnContextMenu:b.a.bool,preventHideOnResize:b.a.bool,preventHideOnScroll:b.a.bool,style:b.a.object},ba.defaultProps={className:"",data:{},hideOnLeave:!1,rtl:!1,onHide:function(){return null},onMouseLeave:function(){return null},onShow:function(){return null},preventHideOnContextMenu:!1,preventHideOnResize:!1,preventHideOnScroll:!1,style:{}};var ma=ba,ga=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}();function fa(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function va(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}var ya=function(e){function t(){var e,r,n;fa(this,t);for(var a=arguments.length,o=Array(a),i=0;i<a;i++)o[i]=arguments[i];return r=n=va(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(o))),n.touchHandled=!1,n.handleMouseDown=function(e){n.props.holdToDisplay>=0&&0===e.button&&(e.persist(),e.stopPropagation(),n.mouseDownTimeoutId=setTimeout((function(){return n.handleContextClick(e)}),n.props.holdToDisplay)),Dn(n.props.attributes.onMouseDown,e)},n.handleMouseUp=function(e){0===e.button&&clearTimeout(n.mouseDownTimeoutId),Dn(n.props.attributes.onMouseUp,e)},n.handleMouseOut=function(e){0===e.button&&clearTimeout(n.mouseDownTimeoutId),Dn(n.props.attributes.onMouseOut,e)},n.handleTouchstart=function(e){n.touchHandled=!1,n.props.holdToDisplay>=0&&(e.persist(),e.stopPropagation(),n.touchstartTimeoutId=setTimeout((function(){n.handleContextClick(e),n.touchHandled=!0}),n.props.holdToDisplay)),Dn(n.props.attributes.onTouchStart,e)},n.handleTouchEnd=function(e){n.touchHandled&&e.preventDefault(),clearTimeout(n.touchstartTimeoutId),Dn(n.props.attributes.onTouchEnd,e)},n.handleContextMenu=function(e){e.button===n.props.mouseButton&&n.handleContextClick(e),Dn(n.props.attributes.onContextMenu,e)},n.handleMouseClick=function(e){e.button===n.props.mouseButton&&n.handleContextClick(e),Dn(n.props.attributes.onClick,e)},n.handleContextClick=function(e){if(!(n.props.disable||n.props.disableIfShiftIsPressed&&e.shiftKey)){e.preventDefault(),e.stopPropagation();var t=e.clientX||e.touches&&e.touches[0].pageX,r=e.clientY||e.touches&&e.touches[0].pageY;n.props.posX&&(t-=n.props.posX),n.props.posY&&(r-=n.props.posY),Qn();var a=Dn(n.props.collect,n.props),o={position:{x:t,y:r},target:n.elem,id:n.props.id};a&&"function"==typeof a.then?a.then((function(t){o.data=Ln()({},t,{target:e.target}),Xn(o)})):(o.data=Ln()({},a,{target:e.target}),Xn(o))}},n.elemRef=function(e){n.elem=e},va(n,r)}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}(t,e),ga(t,[{key:"render",value:function(){var e=this.props,t=e.renderTag,r=e.attributes,n=e.children,a=Ln()({},r,{className:_n()(jn,r.className),onContextMenu:this.handleContextMenu,onClick:this.handleMouseClick,onMouseDown:this.handleMouseDown,onMouseUp:this.handleMouseUp,onTouchStart:this.handleTouchstart,onTouchEnd:this.handleTouchEnd,onMouseOut:this.handleMouseOut,ref:this.elemRef});return p.a.createElement(t,a,n)}}]),t}(s.Component);ya.propTypes={id:b.a.string.isRequired,children:b.a.node.isRequired,attributes:b.a.object,collect:b.a.func,disable:b.a.bool,holdToDisplay:b.a.number,posX:b.a.number,posY:b.a.number,renderTag:b.a.elementType,mouseButton:b.a.number,disableIfShiftIsPressed:b.a.bool},ya.defaultProps={attributes:{},collect:function(){return null},disable:!1,holdToDisplay:1e3,renderTag:"div",posX:0,posY:0,mouseButton:2,disableIfShiftIsPressed:!1};var Ca=ya;Object.assign,function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}}();[].concat(function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}(Object.keys(Ca.propTypes)),["children"]);var Ea=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.expandAll=function(){this.props.onExpandAll(!this.props.isExpanded)},t.prototype.render=function(){var e=this,t=this.props.isExpanded?s.createElement(w,{icon:ae}):s.createElement(w,{icon:le}),r=this.props.isExpanded?s.createElement(w,{icon:H}):s.createElement(w,{icon:Z});return s.createElement("div",{className:"expandableHeader"},s.createElement("div",{className:"text"},s.createElement("div",{className:"arrow icon",onClick:function(){return e.props.onClick()}},t),s.createElement("div",{className:"text-value"},this.props.label)),s.createElement("div",{className:"expandAll icon",onClick:function(){return e.expandAll()},title:this.props.isExpanded?"Collapse all":"Expand all"},r))},t}(s.Component),Oa=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){return s.createElement("div",{className:"expandableHeader"},s.createElement("div",{className:"text"},s.createElement("div",{className:"arrow icon"},s.createElement(w,{icon:L})),s.createElement("div",{className:"text-value"},this.props.label)))},t}(s.Component),Sa=function(e){function t(t){var r=e.call(this,t)||this;return r.state={isExpanded:!1,mustExpand:!1},r}return a(t,e),t.prototype.switchExpandedState=function(){this.setState({isExpanded:!this.state.isExpanded,mustExpand:!1})},t.prototype.shouldComponentUpdate=function(e,t){if(!t.isExpanded&&this.state.isExpanded)return!0;var r=e.items;if(r&&r.length&&e.selectedEntity)for(var n=0,a=r;n<a.length;n++){var o=a[n];if(kn.LookForItem(o,e.selectedEntity))return t.isExpanded=!0,!0}return!0},t.prototype.expandAll=function(e){this.setState({isExpanded:e,mustExpand:e})},t.prototype.renderContextMenu=function(){return this.props.contextMenuItems?s.createElement(ma,{id:"contextmenu#"+t._ContextMenuUniqueIdGenerator++,className:"context-menu"},this.props.contextMenuItems.map((function(e){return s.createElement(aa,{onClick:function(){return e.action()},key:e.label},e.label)}))):(t._ContextMenuUniqueIdGenerator++,null)},t.prototype.render=function(){var e=this,r=this.props.items,n={paddingLeft:10*(this.props.offset+.5)+"px"};if(!r){if(!this.props.forceSubitems)return s.createElement("div",{className:"groupContainer",style:n},s.createElement("div",null,this.props.label));r=[]}if(!r.length)return s.createElement("div",{className:"groupContainer",style:n},s.createElement(Ca,{id:"contextmenu#"+t._ContextMenuUniqueIdGenerator},this.renderContextMenu(),s.createElement(Oa,{label:this.props.label})));if(!this.state.isExpanded)return s.createElement("div",{className:"groupContainer",style:n},s.createElement(Ca,{id:"contextmenu#"+t._ContextMenuUniqueIdGenerator},this.renderContextMenu(),s.createElement(Ea,{isExpanded:!1,label:this.props.label,onClick:function(){return e.switchExpandedState()},onExpandAll:function(t){return e.expandAll(t)}})));var a=kn.SortAndFilter(null,r);return s.createElement("div",null,s.createElement("div",{className:"groupContainer",style:n},s.createElement(Ca,{id:"contextmenu#"+t._ContextMenuUniqueIdGenerator},this.renderContextMenu(),s.createElement(Ea,{isExpanded:this.state.isExpanded,label:this.props.label,onClick:function(){return e.switchExpandedState()},onExpandAll:function(t){return e.expandAll(t)}}))),a.map((function(t){return s.createElement(Nn,{mustExpand:e.state.mustExpand,extensibilityGroups:e.props.extensibilityGroups,key:void 0!==t.uniqueId&&null!==t.uniqueId?t.uniqueId:t.name,offset:e.props.offset+1,selectedEntity:e.props.selectedEntity,entity:t,globalState:e.props.globalState,filter:e.props.filter})})))},t._ContextMenuUniqueIdGenerator=0,t}(s.Component),xa=function(){},Pa=function(e){function t(t){var r=e.call(this,t)||this;r._posDragEnd=null,r._scaleDragEnd=null,r._rotateDragEnd=null;var n=r.props.scene,a=0;if(n.reservedDataStore&&n.reservedDataStore.gizmoManager){var o=n.reservedDataStore.gizmoManager;o.positionGizmoEnabled?a=1:o.rotationGizmoEnabled?a=2:o.scaleGizmoEnabled?a=3:o.boundingBoxGizmoEnabled&&(a=4)}return r.state={isSelected:!1,isInPickingMode:!1,gizmoMode:a},r}return a(t,e),t.prototype.shouldComponentUpdate=function(e,t){if(e.selectedEntity){if(e.scene===e.selectedEntity)return t.isSelected=!0,!0;t.isSelected=!1}return!0},t.prototype.componentDidMount=function(){var e=this;if(this.props.onSelectionChangedObservable){var t=this.props.scene;this._onSelectionChangeObserver=this.props.onSelectionChangedObservable.add((function(r){if(e._selectedEntity=r,r&&t.reservedDataStore&&t.reservedDataStore.gizmoManager){var n=t.reservedDataStore.gizmoManager,a=r.getClassName();"TransformNode"===a||-1!==a.indexOf("Mesh")?n.attachToMesh(r):-1!==a.indexOf("Light")?(e._selectedEntity.reservedDataStore&&e._selectedEntity.reservedDataStore.lightGizmo||(e.props.globalState.enableLightGizmo(e._selectedEntity,!0),e.forceUpdate()),n.attachToNode(e._selectedEntity.reservedDataStore.lightGizmo.attachedNode)):-1!==a.indexOf("Camera")?(e._selectedEntity.reservedDataStore&&e._selectedEntity.reservedDataStore.cameraGizmo||(e.props.globalState.enableCameraGizmo(e._selectedEntity,!0),e.forceUpdate()),n.attachToNode(e._selectedEntity.reservedDataStore.cameraGizmo.attachedNode)):-1!==a.indexOf("Bone")?n.attachToMesh(e._selectedEntity._linkedTransformNode?e._selectedEntity._linkedTransformNode:e._selectedEntity):n.attachToNode(null)}}))}},t.prototype.componentWillUnmount=function(){var e=this.props.scene;this._onPointerObserver&&(e.onPointerObservable.remove(this._onPointerObserver),this._onPointerObserver=null),this._gizmoLayerOnPointerObserver&&(e.onPointerObservable.remove(this._gizmoLayerOnPointerObserver),this._gizmoLayerOnPointerObserver=null),this._onSelectionChangeObserver&&this.props.onSelectionChangedObservable&&this.props.onSelectionChangedObservable.remove(this._onSelectionChangeObserver)},t.prototype.onSelect=function(){if(this.props.onSelectionChangedObservable){var e=this.props.scene;this.props.onSelectionChangedObservable.notifyObservers(e)}},t.prototype.onPickingMode=function(){var e=this,t=this.props.scene;this._onPointerObserver&&(t.onPointerObservable.remove(this._onPointerObserver),this._onPointerObserver=null),this.state.isInPickingMode||(this._onPointerObserver=t.onPointerObservable.add((function(){var r=t.unTranslatedPointer,n=t.pick(r.x,r.y,(function(e){return e.isEnabled()&&e.isVisible&&e.getTotalVertices()>0}),!1,void 0,(function(t,r,n,a){if(!e.props.globalState.ignoreBackfacesForPicking)return!0;var o=u.TmpVectors.Vector3[0],i=u.TmpVectors.Vector3[1],l=u.TmpVectors.Vector3[2];return r.subtractToRef(t,o),n.subtractToRef(r,i),l=u.Vector3.Cross(o,i),u.Vector3.Dot(l,a.direction)<0}));if(e.props.globalState.lightGizmos.length>0){var a=e.props.globalState.lightGizmos[0].gizmoLayer.utilityLayerScene.pick(r.x,r.y,(function(t){for(var r=0,n=e.props.globalState.lightGizmos;r<n.length;r++){if(n[r].attachedNode==t)return!0}return!1}));if(a&&a.hit&&e.props.onSelectionChangedObservable)return void e.props.onSelectionChangedObservable.notifyObservers(a.pickedMesh)}if(e.props.globalState.cameraGizmos.length>0){var o=e.props.globalState.cameraGizmos[0].gizmoLayer.utilityLayerScene.pick(r.x,r.y,(function(t){for(var r=0,n=e.props.globalState.cameraGizmos;r<n.length;r++){if(n[r].attachedNode==t)return!0}return!1}));if(o&&o.hit&&e.props.onSelectionChangedObservable)return void e.props.onSelectionChangedObservable.notifyObservers(o.pickedMesh)}n&&n.hit&&e.props.onSelectionChangedObservable&&e.props.onSelectionChangedObservable.notifyObservers(n.pickedMesh)}),u.PointerEventTypes.POINTERTAP)),this.setState({isInPickingMode:!this.state.isInPickingMode})},t.prototype.setGizmoMode=function(e){var t=this,r=this.props.scene;r.reservedDataStore||(r.reservedDataStore={}),this._gizmoLayerOnPointerObserver&&(r.onPointerObservable.remove(this._gizmoLayerOnPointerObserver),this._gizmoLayerOnPointerObserver=null),r.reservedDataStore.gizmoManager||(r.reservedDataStore.gizmoManager=new u.GizmoManager(r));var n=r.reservedDataStore.gizmoManager;if(this._gizmoLayerOnPointerObserver=u.UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene.onPointerObservable.add((function(e){if(e.type==u.PointerEventTypes.POINTERDOWN&&e.pickInfo&&e.pickInfo.pickedMesh){for(var r=e.pickInfo.pickedMesh;r&&null!=r.parent;)r=r.parent;for(var a=0,o=t.props.globalState.lightGizmos;a<o.length;a++){var i=o[a];i._rootMesh==r&&n.attachToNode(i.attachedNode)}}})),n.boundingBoxGizmoEnabled=!1,n.positionGizmoEnabled=!1,n.rotationGizmoEnabled=!1,n.scaleGizmoEnabled=!1,this.state.gizmoMode===e)e=0,n.dispose(),r.reservedDataStore.gizmoManager=null;else{switch(e){case 1:n.positionGizmoEnabled=!0,this._posDragEnd||(this._posDragEnd=n.gizmos.positionGizmo.onDragEndObservable.add((function(){if(n.gizmos.positionGizmo&&n.gizmos.positionGizmo.attachedNode){var e=n.gizmos.positionGizmo.attachedNode.reservedDataStore?n.gizmos.positionGizmo.attachedNode.reservedDataStore.lightGizmo:null,r=e&&e.light?e.light:n.gizmos.positionGizmo.attachedNode;if(r.position){(a=new xa).object=r,a.property="position",a.value=r.position,t.props.globalState.onPropertyChangedObservable.notifyObservers(a)}else{var a,o=n.gizmos.positionGizmo.attachedNode.reservedDataStore?n.gizmos.positionGizmo.attachedNode.reservedDataStore.cameraGizmo:null,i=o&&o.camera?o.camera:n.gizmos.positionGizmo.attachedNode;if(i.position)(a=new xa).object=i,a.property="position",a.value=i.position,t.props.globalState.onPropertyChangedObservable.notifyObservers(a)}}})));break;case 2:n.rotationGizmoEnabled=!0,this._rotateDragEnd||(this._rotateDragEnd=n.gizmos.rotationGizmo.onDragEndObservable.add((function(){if(n.gizmos.rotationGizmo&&n.gizmos.rotationGizmo.attachedNode){var e=n.gizmos.rotationGizmo.attachedNode.reservedDataStore?n.gizmos.rotationGizmo.attachedNode.reservedDataStore.lightGizmo:null,r=e&&e.light?e.light:n.gizmos.rotationGizmo.attachedNode,a=n.gizmos.rotationGizmo.attachedNode.reservedDataStore?n.gizmos.rotationGizmo.attachedNode.reservedDataStore.cameraGizmo:null,o=a&&a.camera?a.camera:n.gizmos.rotationGizmo.attachedNode;if(r.rotationQuaternion)(i=new xa).object=r,i.property="rotationQuaternion",i.value=r.rotationQuaternion,t.props.globalState.onPropertyChangedObservable.notifyObservers(i);else if(r.rotation){(i=new xa).object=r,i.property="rotation",i.value=r.rotation,t.props.globalState.onPropertyChangedObservable.notifyObservers(i)}else if(r.direction){(i=new xa).object=r,i.property="direction",i.value=r.direction,t.props.globalState.onPropertyChangedObservable.notifyObservers(i)}else if(o.rotationQuaternion){(i=new xa).object=o,i.property="rotationQuaternion",i.value=o.rotationQuaternion,t.props.globalState.onPropertyChangedObservable.notifyObservers(i)}else if(o.rotation){var i;(i=new xa).object=o,i.property="rotation",i.value=o.rotation,t.props.globalState.onPropertyChangedObservable.notifyObservers(i)}}})));break;case 3:n.scaleGizmoEnabled=!0,this._scaleDragEnd||(this._scaleDragEnd=n.gizmos.scaleGizmo.onDragEndObservable.add((function(){if(n.gizmos.scaleGizmo&&n.gizmos.scaleGizmo.attachedMesh){var e=n.gizmos.scaleGizmo.attachedMesh.reservedDataStore?n.gizmos.scaleGizmo.attachedMesh.reservedDataStore.lightGizmo:null,r=e&&e.light?e.light:n.gizmos.scaleGizmo.attachedMesh;if(r.scaling){var a=new xa;a.object=r,a.property="scaling",a.value=r.scaling,t.props.globalState.onPropertyChangedObservable.notifyObservers(a)}}})));break;case 4:n.boundingBoxGizmoEnabled=!0,n.gizmos.boundingBoxGizmo&&(n.gizmos.boundingBoxGizmo.fixedDragMeshScreenSize=!0)}if(this._selectedEntity&&this._selectedEntity.getClassName){var a=this._selectedEntity.getClassName();"TransformNode"===a||-1!==a.indexOf("Mesh")?n.attachToMesh(this._selectedEntity):-1!==a.indexOf("Light")?(this._selectedEntity.reservedDataStore&&this._selectedEntity.reservedDataStore.lightGizmo||(this.props.globalState.enableLightGizmo(this._selectedEntity,!0),this.forceUpdate()),n.attachToNode(this._selectedEntity.reservedDataStore.lightGizmo.attachedNode)):-1!==a.indexOf("Camera")?(this._selectedEntity.reservedDataStore&&this._selectedEntity.reservedDataStore.cameraGizmo||(this.props.globalState.enableCameraGizmo(this._selectedEntity,!0),this.forceUpdate()),n.attachToNode(this._selectedEntity.reservedDataStore.cameraGizmo.attachedNode)):-1!==a.indexOf("Bone")&&n.attachToMesh(this._selectedEntity._linkedTransformNode?this._selectedEntity._linkedTransformNode:this._selectedEntity)}}this.setState({gizmoMode:e})},t.prototype.render=function(){var e=this;return s.createElement("div",{className:this.state.isSelected?"itemContainer selected":"itemContainer"},s.createElement("div",{className:"sceneNode"},s.createElement("div",{className:"sceneTitle",onClick:function(){return e.onSelect()}},s.createElement(w,{icon:ee})," Scene"),s.createElement("div",{className:1===this.state.gizmoMode?"translation selected icon":"translation icon",onClick:function(){return e.setGizmoMode(1)},title:"Enable/Disable position mode"},s.createElement(w,{icon:M})),s.createElement("div",{className:2===this.state.gizmoMode?"rotation selected icon":"rotation icon",onClick:function(){return e.setGizmoMode(2)},title:"Enable/Disable rotation mode"},s.createElement(w,{icon:pe})),s.createElement("div",{className:3===this.state.gizmoMode?"scaling selected icon":"scaling icon",onClick:function(){return e.setGizmoMode(3)},title:"Enable/Disable scaling mode"},s.createElement(w,{icon:H})),s.createElement("div",{className:4===this.state.gizmoMode?"bounding selected icon":"bounding icon",onClick:function(){return e.setGizmoMode(4)},title:"Enable/Disable bounding box mode"},s.createElement(w,{icon:me})),s.createElement("div",{className:"separator"}),s.createElement("div",{className:this.state.isInPickingMode?"pickingMode selected icon":"pickingMode icon",onClick:function(){return e.onPickingMode()},title:"Turn picking mode on/off"},s.createElement(w,{icon:B})),s.createElement("div",{className:"refresh icon",onClick:function(){return e.props.onRefresh()},title:"Refresh the explorer"},s.createElement(w,{icon:ue})),s.createElement(sn,{target:this.props.scene,extensibilityGroups:this.props.extensibilityGroups})))},t}(s.Component);r(56);var wa=function(e){function t(t){return e.call(this,t)||this}return a(t,e),t.prototype.render=function(){var e=this;return s.createElement("div",{className:"filter"},s.createElement("input",{type:"text",placeholder:"Filter",onChange:function(t){return e.props.onFilter(t.target.value)}}))},t}(s.Component),ka=function(e){function t(t){var r=e.call(this,t)||this;return r._once=!0,r._hooked=!1,r.state={filter:null,selectedEntity:null,scene:r.props.scene},r.sceneMutationFunc=r.processMutation.bind(r),r.sceneExplorerRef=s.createRef(),r._onNewSceneObserver=r.props.globalState.onNewSceneObservable.add((function(e){r.setState({scene:e})})),r}return a(t,e),t.prototype.processMutation=function(){var e=this;this.props.globalState.blockMutationUpdates||setTimeout((function(){return e.forceUpdate()}))},t.prototype.componentDidMount=function(){var e=this;this._onSelectionChangeObserver=this.props.globalState.onSelectionChangedObservable.add((function(t){e.state.selectedEntity!==t&&e.setState({selectedEntity:t})})),this._onSelectionRenamedObserver=this.props.globalState.onSelectionRenamedObservable.add((function(){e.forceUpdate()}))},t.prototype.componentWillUnmount=function(){this._onSelectionChangeObserver&&this.props.globalState.onSelectionChangedObservable.remove(this._onSelectionChangeObserver),this._onSelectionRenamedObserver&&this.props.globalState.onSelectionRenamedObservable.remove(this._onSelectionRenamedObserver),this._onNewSceneAddedObserver&&u.EngineStore.LastCreatedEngine.onNewSceneAddedObservable.remove(this._onNewSceneAddedObserver),this._onNewSceneObserver&&this.props.globalState.onNewSceneObservable.remove(this._onNewSceneObserver);var e=this.state.scene;e.onNewSkeletonAddedObservable.removeCallback(this.sceneMutationFunc),e.onNewCameraAddedObservable.removeCallback(this.sceneMutationFunc),e.onNewLightAddedObservable.removeCallback(this.sceneMutationFunc),e.onNewMaterialAddedObservable.removeCallback(this.sceneMutationFunc),e.onNewMeshAddedObservable.removeCallback(this.sceneMutationFunc),e.onNewTextureAddedObservable.removeCallback(this.sceneMutationFunc),e.onNewTransformNodeAddedObservable.removeCallback(this.sceneMutationFunc),e.onSkeletonRemovedObservable.removeCallback(this.sceneMutationFunc),e.onMeshRemovedObservable.removeCallback(this.sceneMutationFunc),e.onCameraRemovedObservable.removeCallback(this.sceneMutationFunc),e.onLightRemovedObservable.removeCallback(this.sceneMutationFunc),e.onMaterialRemovedObservable.removeCallback(this.sceneMutationFunc),e.onTransformNodeRemovedObservable.removeCallback(this.sceneMutationFunc),e.onTextureRemovedObservable.removeCallback(this.sceneMutationFunc)},t.prototype.filterContent=function(e){this.setState({filter:e})},t.prototype.findSiblings=function(e,t,r,n,a){if(!t)return!1;var o=kn.SortAndFilter(e,t);if(!t||0===o.length)return!1;for(var i=0,l=o;i<l.length;i++){var s=l[i];if(s===r){if(a.found=!0,!n)return a.previousOne&&this.props.globalState.onSelectionChangedObservable.notifyObservers(a.previousOne),!0}else{if(a.found)return this.props.globalState.onSelectionChangedObservable.notifyObservers(s),!0;a.previousOne=s}if(s.getChildren&&s.reservedDataStore&&s.reservedDataStore.isExpanded&&this.findSiblings(s,s.getChildren(),r,n,a))return!0}return!1},t.prototype.processKeys=function(e){if(this.state.selectedEntity){var t=this.state.scene,r=!1,n=!1;if(38===e.keyCode)r=!0;else if(40===e.keyCode)n=!0,r=!0;else{var a;if(13===e.keyCode||39===e.keyCode)return(a=this.state.selectedEntity.reservedDataStore)&&a.setExpandedState&&a.setExpandedState(!0),void e.preventDefault();if(37===e.keyCode)return(a=this.state.selectedEntity.reservedDataStore)&&a.setExpandedState&&a.setExpandedState(!1),void e.preventDefault();46===e.keyCode&&this.state.selectedEntity.dispose()}if(r){e.preventDefault();var o={};this.findSiblings(null,t.rootNodes,this.state.selectedEntity,n,o)||this.findSiblings(null,t.materials,this.state.selectedEntity,n,o)||this.findSiblings(null,t.textures,this.state.selectedEntity,n,o)}}},t.prototype.renderContent=function(){var e=this,t=this.state.scene;if(!t)return this._onNewSceneAddedObserver=u.EngineStore.LastCreatedEngine.onNewSceneAddedObservable.addOnce((function(t){return e.setState({scene:t})})),null;this._hooked||(this._hooked=!0,t.onNewSkeletonAddedObservable.add(this.sceneMutationFunc),t.onNewCameraAddedObservable.add(this.sceneMutationFunc),t.onNewLightAddedObservable.add(this.sceneMutationFunc),t.onNewMaterialAddedObservable.add(this.sceneMutationFunc),t.onNewMeshAddedObservable.add(this.sceneMutationFunc),t.onNewTextureAddedObservable.add(this.sceneMutationFunc),t.onNewTransformNodeAddedObservable.add(this.sceneMutationFunc),t.onSkeletonRemovedObservable.add(this.sceneMutationFunc),t.onMeshRemovedObservable.add(this.sceneMutationFunc),t.onCameraRemovedObservable.add(this.sceneMutationFunc),t.onLightRemovedObservable.add(this.sceneMutationFunc),t.onMaterialRemovedObservable.add(this.sceneMutationFunc),t.onTransformNodeRemovedObservable.add(this.sceneMutationFunc),t.onTextureRemovedObservable.add(this.sceneMutationFunc));var r=t.textures.filter((function(e){return"AdvancedDynamicTexture"===e.getClassName()})),n=t.textures.filter((function(e){return"AdvancedDynamicTexture"!==e.getClassName()})),a=t.postProcesses,o=t.postProcessRenderPipelineManager.supportedPipelines,i=[];t.activeCamera&&(o.some((function(e){return"DefaultRenderingPipeline"===e.getClassName()}))||i.push({label:"Add new Default Rendering Pipeline",action:function(){var r=new u.DefaultRenderingPipeline("Default rendering pipeline",!0,t,t.cameras);e.props.globalState.onSelectionChangedObservable.notifyObservers(r)}}),o.some((function(e){return"SSAORenderingPipeline"===e.getClassName()}))||i.push({label:"Add new SSAO Rendering Pipeline",action:function(){var r=new u.SSAORenderingPipeline("SSAO rendering pipeline",t,1,t.cameras);e.props.globalState.onSelectionChangedObservable.notifyObservers(r)}}),t.getEngine().webGLVersion>1&&!o.some((function(e){return"SSAORenderingPipeline"===e.getClassName()}))&&i.push({label:"Add new SSAO2 Rendering Pipeline",action:function(){var r=new u.SSAO2RenderingPipeline("SSAO2 rendering pipeline",t,1,t.cameras);e.props.globalState.onSelectionChangedObservable.notifyObservers(r)}}));var l=[];l.push({label:"Add new point light",action:function(){var r=new u.PointLight("point light",u.Vector3.Zero(),t);e.props.globalState.onSelectionChangedObservable.notifyObservers(r)}}),l.push({label:"Add new directional light",action:function(){var r=new u.DirectionalLight("directional light",new u.Vector3(-1,-1,-.5),t);e.props.globalState.onSelectionChangedObservable.notifyObservers(r)}}),l.push({label:"Add new free camera",action:function(){var r=new u.FreeCamera("free camera",t.activeCamera?t.activeCamera.globalPosition:new u.Vector3(0,0,-5),t);t.activeCamera&&(r.minZ=t.activeCamera.minZ,r.maxZ=t.activeCamera.maxZ,t.activeCamera.getTarget&&r.setTarget(t.activeCamera.getTarget())),e.props.globalState.onSelectionChangedObservable.notifyObservers(r)}});var p=[];p.push({label:"Add new standard material",action:function(){var r=new u.StandardMaterial("Standard material",t);e.props.globalState.onSelectionChangedObservable.notifyObservers(r)}}),p.push({label:"Add new PBR material",action:function(){var r=new u.PBRMaterial("PBR material",t);e.props.globalState.onSelectionChangedObservable.notifyObservers(r)}}),p.push({label:"Add new node material",action:function(){var r=new u.NodeMaterial("node material",t);r.setToDefault(),r.build(),e.props.globalState.onSelectionChangedObservable.notifyObservers(r)}});var c=[];c.push.apply(c,t.materials),t.multiMaterials&&t.multiMaterials.length&&c.push.apply(c,t.multiMaterials);var d=[];d.push({label:"Add new sprite manager",action:function(){var r=new u.SpriteManager("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t);e.props.globalState.onSelectionChangedObservable.notifyObservers(r)}});var h=[];return h.push({label:"Add new CPU particle system",action:function(){var r=u.ParticleHelper.CreateDefault(u.Vector3.Zero(),1e4,t);r.name="CPU particle system",r.start(),e.props.globalState.onSelectionChangedObservable.notifyObservers(r)}}),u.GPUParticleSystem.IsSupported&&h.push({label:"Add new GPU particle system",action:function(){var r=u.ParticleHelper.CreateDefault(u.Vector3.Zero(),1e4,t,!0);r.name="GPU particle system",r.start(),e.props.globalState.onSelectionChangedObservable.notifyObservers(r)}}),s.createElement("div",{id:"tree",onContextMenu:function(e){return e.preventDefault()}},s.createElement(wa,{onFilter:function(t){return e.filterContent(t)}}),s.createElement(Pa,{globalState:this.props.globalState,extensibilityGroups:this.props.extensibilityGroups,selectedEntity:this.state.selectedEntity,scene:t,onRefresh:function(){return e.forceUpdate()},onSelectionChangedObservable:this.props.globalState.onSelectionChangedObservable}),s.createElement(Sa,{globalState:this.props.globalState,contextMenuItems:l,extensibilityGroups:this.props.extensibilityGroups,selectedEntity:this.state.selectedEntity,items:t.rootNodes,label:"Nodes",offset:1,filter:this.state.filter}),t.skeletons.length>0&&s.createElement(Sa,{globalState:this.props.globalState,extensibilityGroups:this.props.extensibilityGroups,selectedEntity:this.state.selectedEntity,items:t.skeletons,label:"Skeletons",offset:1,filter:this.state.filter}),s.createElement(Sa,{globalState:this.props.globalState,extensibilityGroups:this.props.extensibilityGroups,selectedEntity:this.state.selectedEntity,items:c,contextMenuItems:p,label:"Materials",offset:1,filter:this.state.filter}),s.createElement(Sa,{globalState:this.props.globalState,extensibilityGroups:this.props.extensibilityGroups,selectedEntity:this.state.selectedEntity,items:n,label:"Textures",offset:1,filter:this.state.filter}),a.length>0&&s.createElement(Sa,{globalState:this.props.globalState,extensibilityGroups:this.props.extensibilityGroups,selectedEntity:this.state.selectedEntity,items:a,label:"Post-processes",offset:1,filter:this.state.filter}),s.createElement(Sa,{globalState:this.props.globalState,extensibilityGroups:this.props.extensibilityGroups,contextMenuItems:i,selectedEntity:this.state.selectedEntity,items:o,label:"Rendering pipelines",offset:1,filter:this.state.filter}),s.createElement(Sa,{globalState:this.props.globalState,contextMenuItems:h,extensibilityGroups:this.props.extensibilityGroups,selectedEntity:this.state.selectedEntity,items:t.particleSystems,label:"Particle systems",offset:1,filter:this.state.filter}),s.createElement(Sa,{globalState:this.props.globalState,contextMenuItems:d,forceSubitems:!0,extensibilityGroups:this.props.extensibilityGroups,selectedEntity:this.state.selectedEntity,items:t.spriteManagers,label:"Sprite managers",offset:1,filter:this.state.filter}),r&&r.length>0&&s.createElement(Sa,{globalState:this.props.globalState,extensibilityGroups:this.props.extensibilityGroups,selectedEntity:this.state.selectedEntity,items:r,label:"GUI",offset:1,filter:this.state.filter}),t.animationGroups.length>0&&s.createElement(Sa,{globalState:this.props.globalState,extensibilityGroups:this.props.extensibilityGroups,selectedEntity:this.state.selectedEntity,items:t.animationGroups,label:"Animation groups",offset:1,filter:this.state.filter}))},t.prototype.onClose=function(){this.props.onClose&&this.props.onClose()},t.prototype.onPopup=function(){this.props.onPopup&&this.props.onPopup()},t.prototype.render=function(){var e=this;return this.props.popupMode?s.createElement("div",{id:"sceneExplorer",tabIndex:0,onKeyDown:function(t){return e.processKeys(t)}},!this.props.noHeader&&s.createElement(Wr,{title:"SCENE EXPLORER",noClose:this.props.noClose,noExpand:this.props.noExpand,noCommands:this.props.noCommands,onClose:function(){return e.onClose()},onPopup:function(){return e.onPopup()}}),this.renderContent()):(this._once&&(this._once=!1,setTimeout((function(){var e=document.getElementById("sceneExplorer");e&&(e.style.width="300px")}),150)),s.createElement(_e.a,{tabIndex:-1,id:"sceneExplorer",ref:this.sceneExplorerRef,size:{height:"100%"},minWidth:300,maxWidth:600,minHeight:"100%",enable:{top:!1,right:!0,bottom:!1,left:!1,topRight:!1,bottomRight:!1,bottomLeft:!1,topLeft:!1},onKeyDown:function(t){return e.processKeys(t)}},!this.props.noHeader&&s.createElement(Wr,{title:"SCENE EXPLORER",noClose:this.props.noClose,noExpand:this.props.noExpand,noCommands:this.props.noCommands,onClose:function(){return e.onClose()},onPopup:function(){return e.onPopup()}}),this.renderContent()))},t}(s.Component),Na=r(58).default;r(59);var Ta=function(e){function t(t){var r=e.call(this,t)||this;return r._once=!0,r.splitRef=s.createRef(),r.topPartRef=s.createRef(),r.bottomPartRef=s.createRef(),r}return a(t,e),t.prototype.componentDidMount=function(){this.splitRef.current&&Na([this.topPartRef.current,this.bottomPartRef.current],{direction:"vertical",minSize:[200,200],gutterSize:4})},t.prototype.renderContent=function(){return this.props.popupMode?s.createElement("div",{id:"split",className:"splitPopup"},s.createElement("div",{id:"topPart"},s.createElement(ka,{scene:this.props.scene,extensibilityGroups:this.props.extensibilityGroups,popupMode:!0,globalState:this.props.globalState,noHeader:!0})),s.createElement("div",{id:"separator"}),s.createElement("div",{id:"bottomPart",style:{marginTop:"4px",overflow:"hidden"}},s.createElement(tn,{scene:this.props.scene,popupMode:!0,globalState:this.props.globalState,noHeader:!0,initialTab:this.props.initialTab}))):s.createElement("div",{ref:this.splitRef,id:"split",className:"noPopup"},s.createElement("div",{id:"topPart",ref:this.topPartRef},s.createElement(ka,{scene:this.props.scene,extensibilityGroups:this.props.extensibilityGroups,globalState:this.props.globalState,popupMode:!0,noHeader:!0})),s.createElement("div",{id:"bottomPart",ref:this.bottomPartRef,style:{marginTop:"4px",overflow:"hidden"}},s.createElement(tn,{scene:this.props.scene,globalState:this.props.globalState,popupMode:!0,noHeader:!0,initialTab:this.props.initialTab})))},t.prototype.render=function(){var e=this;return this.props.popupMode?s.createElement("div",{id:"embed"},s.createElement(Wr,{title:"INSPECTOR",noClose:this.props.noClose,noExpand:this.props.noExpand,handleBack:!0,onClose:function(){return e.props.onClose()},onPopup:function(){return e.props.onPopup()},onSelectionChangedObservable:this.props.globalState.onSelectionChangedObservable}),this.renderContent()):(this._once&&(this._once=!1,setTimeout((function(){var e=document.getElementById("embed");e&&(e.style.width="300px")}),150)),s.createElement(_e.a,{id:"embed",minWidth:300,maxWidth:600,size:{height:"100%"},minHeight:"100%",enable:{top:!1,right:!1,bottom:!1,left:!0,topRight:!1,bottomRight:!1,bottomLeft:!1,topLeft:!1}},s.createElement(Wr,{title:"INSPECTOR",noClose:this.props.noClose,noExpand:this.props.noExpand,handleBack:!0,onClose:function(){return e.props.onClose()},onPopup:function(){return e.props.onPopup()},onSelectionChangedObservable:this.props.globalState.onSelectionChangedObservable}),this.renderContent()))},t}(s.Component),_a=function(){function e(){this._sceneRecorder=new u.SceneRecorder,this._isRecording=!1}return Object.defineProperty(e.prototype,"isRecording",{get:function(){return this._isRecording},enumerable:!1,configurable:!0}),e.prototype.cancel=function(){this._isRecording=!1},e.prototype.trackScene=function(e){this._sceneRecorder.track(e),this._isRecording=!0},e.prototype.applyDelta=function(e,t){u.SceneRecorder.ApplyDelta(e,t),this._isRecording=!1},e.prototype.export=function(){var e=JSON.stringify(this._sceneRecorder.getDelta());u.Tools.Download(new Blob([e]),"diff.json"),this._isRecording=!1},e}(),Ma=function(){function e(){this.onInspectorClosedObservable=new u.Observable,this.onTabChangedObservable=new u.Observable,this.onSelectionRenamedObservable=new u.Observable,this.onNewSceneObservable=new u.Observable,this.sceneImportDefaults={},this.validationResults=null,this.onValidationResultsUpdatedObservable=new u.Observable,this.glTFLoaderExtensionDefaults={MSFT_lod:{enabled:!0,maxLODsToLoad:10},MSFT_minecraftMesh:{enabled:!0},MSFT_sRGBFactors:{enabled:!0},MSFT_audio_emitter:{enabled:!0},KHR_draco_mesh_compression:{enabled:!0},KHR_mesh_quantization:{enabled:!0},KHR_materials_pbrSpecularGlossiness:{enabled:!0},KHR_materials_clearcoat:{enabled:!0},KHR_materials_ior:{enabled:!0},KHR_materials_sheen:{enabled:!0},KHR_materials_specular:{enabled:!0},KHR_materials_unlit:{enabled:!0},KHR_materials_variants:{enabled:!0},KHR_materials_transmission:{enabled:!0},KHR_materials_translucency:{enabled:!0},KHR_lights_punctual:{enabled:!0},KHR_texture_basisu:{enabled:!0},KHR_texture_transform:{enabled:!0},EXT_lights_image_based:{enabled:!0},EXT_mesh_gpu_instancing:{enabled:!0},EXT_texture_webp:{enabled:!0}},this.glTFLoaderDefaults={animationStartMode:void 0!==Zr.GLTFLoaderAnimationStartMode?Zr.GLTFLoaderAnimationStartMode.FIRST:1,capturePerformanceCounters:!1,compileMaterials:!1,compileShadowGenerators:!1,coordinateSystemMode:void 0!==Zr.GLTFLoaderCoordinateSystemMode?Zr.GLTFLoaderCoordinateSystemMode.AUTO:0,loggingEnabled:!1,transparencyAsCoverage:!1,useClipPlane:!1,validate:!0},this.glTFLoaderExtensions={},this.blockMutationUpdates=!1,this.selectedLineContainerTitles=[],this.selectedLineContainerTitlesNoFocus=[],this.recorder=new _a,this._onlyUseEulers=null,this._ignoreBackfacesForPicking=null,this.lightGizmos=[],this.cameraGizmos=[]}return Object.defineProperty(e.prototype,"onlyUseEulers",{get:function(){return null===this._onlyUseEulers&&(this._onlyUseEulers=u.DataStorage.ReadBoolean("settings_onlyUseEulers",!0)),this._onlyUseEulers},set:function(e){this._onlyUseEulers=e,u.DataStorage.WriteBoolean("settings_onlyUseEulers",e)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"ignoreBackfacesForPicking",{get:function(){return null===this._ignoreBackfacesForPicking&&(this._ignoreBackfacesForPicking=u.DataStorage.ReadBoolean("settings_ignoreBackfacesForPicking",!1)),this._ignoreBackfacesForPicking},set:function(e){this._ignoreBackfacesForPicking=e,u.DataStorage.WriteBoolean("settings_ignoreBackfacesForPicking",e)},enumerable:!1,configurable:!0}),e.prototype.init=function(e){var t=this;this.onPropertyChangedObservable=e,this.onNewSceneObservable.add((function(e){t.recorder.cancel()}))},e.prototype.prepareGLTFPlugin=function(e){var t=this;this.glTFLoaderExtensions={};var r=this.glTFLoaderDefaults;if(void 0!==r)for(var n in r)e[n]=r[n];e.onExtensionLoadedObservable.add((function(e){var r=t.glTFLoaderExtensionDefaults[e.name];if(void 0!==r)for(var n in r)e[n]=r[n];t.glTFLoaderExtensions[e.name]=e})),this.validationResults&&(this.validationResults=null,this.onValidationResultsUpdatedObservable.notifyObservers(null)),e.onValidatedObservable.add((function(e){t.validationResults=e,t.onValidationResultsUpdatedObservable.notifyObservers(e),(e.issues.numErrors||e.issues.numWarnings)&&(t.selectedLineContainerTitlesNoFocus.push("GLTF VALIDATION"),t.onTabChangedObservable.notifyObservers(3))}))},e.prototype.enableLightGizmo=function(e,t){void 0===t&&(t=!0),t?(e.reservedDataStore||(e.reservedDataStore={}),e.reservedDataStore.lightGizmo||(e.reservedDataStore.lightGizmo=new u.LightGizmo,this.lightGizmos.push(e.reservedDataStore.lightGizmo),e.reservedDataStore.lightGizmo.light=e,e.reservedDataStore.lightGizmo.material.reservedDataStore={hidden:!0})):e.reservedDataStore&&e.reservedDataStore.lightGizmo&&(this.lightGizmos.splice(this.lightGizmos.indexOf(e.reservedDataStore.lightGizmo),1),e.reservedDataStore.lightGizmo.dispose(),e.reservedDataStore.lightGizmo=null)},e.prototype.enableCameraGizmo=function(e,t){void 0===t&&(t=!0),t?(e.reservedDataStore||(e.reservedDataStore={}),e.reservedDataStore.cameraGizmo||(e.reservedDataStore.cameraGizmo=new u.CameraGizmo,this.cameraGizmos.push(e.reservedDataStore.cameraGizmo),e.reservedDataStore.cameraGizmo.camera=e,e.reservedDataStore.cameraGizmo.material.reservedDataStore={hidden:!0})):e.reservedDataStore&&e.reservedDataStore.cameraGizmo&&(this.cameraGizmos.splice(this.cameraGizmos.indexOf(e.reservedDataStore.cameraGizmo),1),e.reservedDataStore.cameraGizmo.dispose(),e.reservedDataStore.cameraGizmo=null)},e}(),La=function(){function e(){}return e.MarkLineContainerTitleForHighlighting=function(e){this._GlobalState.selectedLineContainerTitles=[],this._GlobalState.selectedLineContainerTitles.push(e)},e.MarkMultipleLineContainerTitlesForHighlighting=function(e){var t;this._GlobalState.selectedLineContainerTitles=[],(t=this._GlobalState.selectedLineContainerTitles).push.apply(t,e)},e._CopyStyles=function(e,t){for(var r=0;r<e.styleSheets.length;r++){var n=e.styleSheets[r];try{if(n.cssRules){for(var a=e.createElement("style"),o=0,i=n.cssRules;o<i.length;o++){var l=i[o];a.appendChild(e.createTextNode(l.cssText))}t.head.appendChild(a)}else if(n.href){var s=e.createElement("link");s.rel="stylesheet",s.href=n.href,t.head.appendChild(s)}}catch(e){}}},e._CreateSceneExplorer=function(t,r,n){var a=this;if(r.original&&(r={original:!1,popup:r.popup,overlay:r.overlay,showExplorer:r.showExplorer,showInspector:r.showInspector,embedMode:r.embedMode,handleResize:r.handleResize,enablePopup:r.enablePopup,enableClose:r.enableClose,explorerExtensibility:r.explorerExtensibility}),n&&(this._SceneExplorerHost=n.ownerDocument.createElement("div"),this._SceneExplorerHost.id="scene-explorer-host",this._SceneExplorerHost.style.width=r.explorerWidth||"auto",r.popup?n.appendChild(this._SceneExplorerHost):n.insertBefore(this._SceneExplorerHost,this._NewCanvasContainer),r.overlay||(this._SceneExplorerHost.style.position="relative")),this._SceneExplorerHost){this._OpenedPane++;var o=s.createElement(ka,{scene:t,globalState:this._GlobalState,extensibilityGroups:r.explorerExtensibility,noClose:!r.enableClose,noExpand:!r.enablePopup,popupMode:r.popup,onPopup:function(){c.unmountComponentAtNode(a._SceneExplorerHost),a._RemoveElementFromDOM(a._SceneExplorerHost),r.popup&&a._SceneExplorerWindow.close(),r.popup=!r.popup,r.showExplorer=!0,r.showInspector=!1,r.explorerWidth=r.popup?"100%":"300px",e.Show(t,r)},onClose:function(){c.unmountComponentAtNode(a._SceneExplorerHost),e._OpenedPane--,a._RemoveElementFromDOM(a._SceneExplorerHost),a._Cleanup(),r.popup&&a._SceneExplorerWindow.close()}});c.render(o,this._SceneExplorerHost)}},e._CreateActionTabs=function(t,r,n){var a=this;if(r.original=!1,n){var o=n.ownerDocument.createElement("div");o.id="inspector-host",o.style.width=r.inspectorWidth||"auto",n.appendChild(o),this._ActionTabsHost=o,r.overlay||(this._ActionTabsHost.style.position="relative")}if(this._ActionTabsHost){this._OpenedPane++;var i=s.createElement(tn,{globalState:this._GlobalState,scene:t,noClose:!r.enableClose,noExpand:!r.enablePopup,popupMode:r.popup,onPopup:function(){c.unmountComponentAtNode(a._ActionTabsHost),a._RemoveElementFromDOM(a._ActionTabsHost),r.popup&&a._ActionTabsWindow.close(),r.popup=!r.popup,r.showExplorer=!1,r.showInspector=!0,r.inspectorWidth=r.popup?"100%":"300px",e.Show(t,r)},onClose:function(){c.unmountComponentAtNode(a._ActionTabsHost),e._OpenedPane--,a._Cleanup(),a._RemoveElementFromDOM(a._ActionTabsHost),r.popup&&a._ActionTabsWindow.close()},initialTab:r.initialTab});c.render(i,this._ActionTabsHost)}},e._CreateEmbedHost=function(t,r,n,a){var o=this;if(n){var i=n.ownerDocument.createElement("div");i.id="embed-host",i.style.width=r.embedHostWidth||"auto",n.appendChild(i),this._EmbedHost=i,r.overlay||(this._EmbedHost.style.position="relative")}if(this._EmbedHost){this._OpenedPane++;var l=s.createElement(Ta,{globalState:this._GlobalState,scene:t,extensibilityGroups:r.explorerExtensibility,noExpand:!r.enablePopup,noClose:!r.enableClose,popupMode:r.popup,onPopup:function(){c.unmountComponentAtNode(o._EmbedHost),r.popup&&o._EmbedHostWindow.close(),o._RemoveElementFromDOM(o._EmbedHost),r.popup=!r.popup,r.embedMode=!0,r.showExplorer=!0,r.showInspector=!0,r.embedHostWidth=r.popup?"100%":"auto",e.Show(t,r)},onClose:function(){c.unmountComponentAtNode(o._EmbedHost),o._OpenedPane=0,o._Cleanup(),o._RemoveElementFromDOM(o._EmbedHost),r.popup&&o._EmbedHostWindow.close()},initialTab:r.initialTab});c.render(l,this._EmbedHost)}},e._CreatePopup=function(e,t,r,n,a){var o=this;void 0===r&&(r=300),void 0===n&&(n=800);var i={width:r,height:n,top:(window.innerHeight-r)/2+window.screenY,left:(window.innerWidth-n)/2+window.screenX},l=Object.keys(i).map((function(e){return e+"="+i[e]})).join(","),s=window.open("",e,l);if(!s)return null;var p=s.document,c=p.createElement("link");c.rel="stylesheet",c.href="https://use.typekit.net/cta4xsb.css",p.head.appendChild(c),p.title=e,p.body.style.width="100%",p.body.style.height="100%",p.body.style.margin="0",p.body.style.padding="0";var u=p.createElement("div");return u.style.width="100%",u.style.height="100%",u.style.margin="0",u.style.padding="0",s.document.body.appendChild(u),this._CopyStyles(window.document,p),a&&setTimeout((function(){o._CopyStyles(window.document,p)}),0),this[t]=s,u},Object.defineProperty(e,"IsVisible",{get:function(){return this._OpenedPane>0},enumerable:!1,configurable:!0}),e.EarlyAttachToLoader=function(){var e=this;this._GlobalState.onPluginActivatedObserver||(this._GlobalState.onPluginActivatedObserver=u.SceneLoader.OnPluginActivatedObservable.add((function(t){var r=t;"gltf"===r.name&&e._GlobalState.prepareGLTFPlugin(r)})))},e.Show=function(t,r){var n=o({original:!0,popup:!1,overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,enableClose:!0,handleResize:!0,enablePopup:!0},r);this._GlobalState.onPropertyChangedObservable||this._GlobalState.init(this.OnPropertyChangedObservable),this._GlobalState.onSelectionChangedObservable||(this._GlobalState.onSelectionChangedObservable=this.OnSelectionChangeObservable),this.IsVisible&&n.original&&this.Hide(),t||(t=u.EngineStore.LastCreatedScene),this._Scene=t;var a=t?t.getEngine().getInputElement():u.EngineStore.LastCreatedEngine.getInputElement();if(n.embedMode&&n.showExplorer&&n.showInspector)if(n.popup)this._CreateEmbedHost(t,n,this._CreatePopup("INSPECTOR","_EmbedHostWindow"),e.OnSelectionChangeObservable);else{if(!a)return;var i=n.globalRoot?n.globalRoot:a.parentElement;n.overlay||this._NewCanvasContainer?!n.overlay&&this._NewCanvasContainer&&this._NewCanvasContainer.parentElement&&(i=this._NewCanvasContainer.parentElement):this._CreateCanvasContainer(i),this._NewCanvasContainer&&n.handleResize&&t&&(this._OnBeforeRenderObserver=t.onBeforeRenderObservable.add((function(){t.getEngine().resize()}))),this._CreateEmbedHost(t,n,i,e.OnSelectionChangeObservable)}else if(n.popup)n.showExplorer&&(this._SceneExplorerHost&&(this._SceneExplorerHost.style.width="0"),this._CreateSceneExplorer(t,n,this._CreatePopup("SCENE EXPLORER","_SceneExplorerWindow"))),n.showInspector&&(this._ActionTabsHost&&(this._ActionTabsHost.style.width="0"),this._CreateActionTabs(t,n,this._CreatePopup("INSPECTOR","_ActionTabsWindow")));else{i=n.globalRoot?n.globalRoot:a.parentElement;n.overlay||this._NewCanvasContainer?!n.overlay&&this._NewCanvasContainer&&this._NewCanvasContainer.parentElement&&(i=this._NewCanvasContainer.parentElement):this._CreateCanvasContainer(i),this._NewCanvasContainer&&n.handleResize&&t&&(this._OnBeforeRenderObserver=t.onBeforeRenderObservable.add((function(){t.getEngine().resize()}))),n.showExplorer&&this._CreateSceneExplorer(t,n,i),n.showInspector&&this._CreateActionTabs(t,n,i)}},e._SetNewScene=function(e){this._Scene=e,this._GlobalState.onNewSceneObservable.notifyObservers(e)},e._CreateCanvasContainer=function(e){for(this._NewCanvasContainer=e.ownerDocument.createElement("div"),this._NewCanvasContainer.style.display=e.style.display,e.style.display="flex";e.childElementCount>0;){var t=e.childNodes[0];e.removeChild(t),this._NewCanvasContainer.appendChild(t)}e.appendChild(this._NewCanvasContainer),this._NewCanvasContainer.style.width="100%",this._NewCanvasContainer.style.height="100%"},e._DestroyCanvasContainer=function(){if(this._NewCanvasContainer){for(var e=this._NewCanvasContainer.parentElement;this._NewCanvasContainer.childElementCount>0;){var t=this._NewCanvasContainer.childNodes[0];this._NewCanvasContainer.removeChild(t),e.appendChild(t)}e.removeChild(this._NewCanvasContainer),e.style.display=this._NewCanvasContainer.style.display,this._NewCanvasContainer=null}},e._Cleanup=function(){var t=this;0===e._OpenedPane&&(this._GlobalState.lightGizmos.forEach((function(e){e.light&&t._GlobalState.enableLightGizmo(e.light,!1)})),this._GlobalState.cameraGizmos.forEach((function(e){e.camera&&t._GlobalState.enableCameraGizmo(e.camera,!1)})),this._Scene&&this._Scene.reservedDataStore&&this._Scene.reservedDataStore.gizmoManager&&(this._Scene.reservedDataStore.gizmoManager.dispose(),this._Scene.reservedDataStore.gizmoManager=null),this._NewCanvasContainer&&this._DestroyCanvasContainer(),this._OnBeforeRenderObserver&&this._Scene&&(this._Scene.onBeforeRenderObservable.remove(this._OnBeforeRenderObserver),this._OnBeforeRenderObserver=null,this._Scene.getEngine().resize()),this._GlobalState.onInspectorClosedObservable.notifyObservers(this._Scene))},e._RemoveElementFromDOM=function(e){e&&e.parentElement&&e.parentElement.removeChild(e)},e.Hide=function(){this._ActionTabsHost&&(c.unmountComponentAtNode(this._ActionTabsHost),this._RemoveElementFromDOM(this._ActionTabsHost),this._ActionTabsHost=null),this._SceneExplorerHost&&(c.unmountComponentAtNode(this._SceneExplorerHost),this._SceneExplorerHost.parentElement&&this._SceneExplorerHost.parentElement.removeChild(this._SceneExplorerHost),this._SceneExplorerHost=null),this._EmbedHost&&(c.unmountComponentAtNode(this._EmbedHost),this._EmbedHost.parentElement&&this._EmbedHost.parentElement.removeChild(this._EmbedHost),this._EmbedHost=null),e._OpenedPane=0,this._Cleanup(),this._GlobalState.onPluginActivatedObserver||(u.SceneLoader.OnPluginActivatedObservable.remove(this._GlobalState.onPluginActivatedObserver),this._GlobalState.onPluginActivatedObserver=null)},e._OpenedPane=0,e.OnSelectionChangeObservable=new u.Observable,e.OnPropertyChangedObservable=new u.Observable,e._GlobalState=new Ma,e}();La.EarlyAttachToLoader()},function(e,t,r){"use strict";(function(e,n){ /*! * Font Awesome Free 5.15.0 by @fontawesome - https://fontawesome.com * License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) */ function a(e){return(a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function l(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{},n=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(n=n.concat(Object.getOwnPropertySymbols(r).filter((function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable})))),n.forEach((function(t){i(e,t,r[t])}))}return e}function s(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=[],n=!0,a=!1,o=void 0;try{for(var i,l=e[Symbol.iterator]();!(n=(i=l.next()).done)&&(r.push(i.value),!t||r.length!==t);n=!0);}catch(e){a=!0,o=e}finally{try{n||null==l.return||l.return()}finally{if(a)throw o}}return r}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}r.d(t,"a",(function(){return xe})),r.d(t,"b",(function(){return Se}));var p=function(){},c={},u={},d={mark:p,measure:p};try{"undefined"!=typeof window&&(c=window),"undefined"!=typeof document&&(u=document),"undefined"!=typeof MutationObserver&&MutationObserver,"undefined"!=typeof performance&&(d=performance)}catch(e){}var h=(c.navigator||{}).userAgent,b=void 0===h?"":h,m=c,g=u,f=d,v=(m.document,!!g.documentElement&&!!g.head&&"function"==typeof g.addEventListener&&"function"==typeof g.createElement),y=(~b.indexOf("MSIE")||b.indexOf("Trident/"),function(){try{}catch(e){return!1}}(),[1,2,3,4,5,6,7,8,9,10]),C=y.concat([11,12,13,14,15,16,17,18,19,20]),E={GROUP:"group",SWAP_OPACITY:"swap-opacity",PRIMARY:"primary",SECONDARY:"secondary"},O=(["xs","sm","lg","fw","ul","li","border","pull-left","pull-right","spin","pulse","rotate-90","rotate-180","rotate-270","flip-horizontal","flip-vertical","flip-both","stack","stack-1x","stack-2x","inverse","layers","layers-text","layers-counter",E.GROUP,E.SWAP_OPACITY,E.PRIMARY,E.SECONDARY].concat(y.map((function(e){return"".concat(e,"x")}))).concat(C.map((function(e){return"w-".concat(e)}))),m.FontAwesomeConfig||{});if(g&&"function"==typeof g.querySelector){[["data-family-prefix","familyPrefix"],["data-replacement-class","replacementClass"],["data-auto-replace-svg","autoReplaceSvg"],["data-auto-add-css","autoAddCss"],["data-auto-a11y","autoA11y"],["data-search-pseudo-elements","searchPseudoElements"],["data-observe-mutations","observeMutations"],["data-mutate-approach","mutateApproach"],["data-keep-original-source","keepOriginalSource"],["data-measure-performance","measurePerformance"],["data-show-missing-icons","showMissingIcons"]].forEach((function(e){var t=s(e,2),r=t[0],n=t[1],a=function(e){return""===e||"false"!==e&&("true"===e||e)}(function(e){var t=g.querySelector("script["+e+"]");if(t)return t.getAttribute(e)}(r));null!=a&&(O[n]=a)}))}var S=l({},{familyPrefix:"fa",replacementClass:"svg-inline--fa",autoReplaceSvg:!0,autoAddCss:!0,autoA11y:!0,searchPseudoElements:!1,observeMutations:!0,mutateApproach:"async",keepOriginalSource:!0,measurePerformance:!1,showMissingIcons:!0},O);S.autoReplaceSvg||(S.observeMutations=!1);var x=l({},S);m.FontAwesomeConfig=x;var P=m||{};P.___FONT_AWESOME___||(P.___FONT_AWESOME___={}),P.___FONT_AWESOME___.styles||(P.___FONT_AWESOME___.styles={}),P.___FONT_AWESOME___.hooks||(P.___FONT_AWESOME___.hooks={}),P.___FONT_AWESOME___.shims||(P.___FONT_AWESOME___.shims=[]);var w=P.___FONT_AWESOME___,k=[];v&&((g.documentElement.doScroll?/^loaded|^c/:/^loaded|^i|^c/).test(g.readyState)||g.addEventListener("DOMContentLoaded",(function e(){g.removeEventListener("DOMContentLoaded",e),1,k.map((function(e){return e()}))})));var N,T=function(){},_=void 0!==e&&void 0!==e.process&&"function"==typeof e.process.emit,M=void 0===n?setTimeout:n,L=[];function D(){for(var e=0;e<L.length;e++)L[e][0](L[e][1]);L=[],N=!1}function R(e,t){L.push([e,t]),N||(N=!0,M(D,0))}function A(e){var t=e.owner,r=t._state,n=t._data,a=e[r],o=e.then;if("function"==typeof a){r="fulfilled";try{n=a(n)}catch(e){F(o,e)}}I(o,n)||("fulfilled"===r&&j(o,n),"rejected"===r&&F(o,n))}function I(e,t){var r;try{if(e===t)throw new TypeError("A promises callback cannot return that same promise.");if(t&&("function"==typeof t||"object"===a(t))){var n=t.then;if("function"==typeof n)return n.call(t,(function(n){r||(r=!0,t===n?z(e,n):j(e,n))}),(function(t){r||(r=!0,F(e,t))})),!0}}catch(t){return r||F(e,t),!0}return!1}function j(e,t){e!==t&&I(e,t)||z(e,t)}function z(e,t){"pending"===e._state&&(e._state="settled",e._data=t,R(V,e))}function F(e,t){"pending"===e._state&&(e._state="settled",e._data=t,R(U,e))}function G(e){e._then=e._then.forEach(A)}function V(e){e._state="fulfilled",G(e)}function U(t){t._state="rejected",G(t),!t._handled&&_&&e.process.emit("unhandledRejection",t._data,t)}function H(t){e.process.emit("rejectionHandled",t)}function B(e){if("function"!=typeof e)throw new TypeError("Promise resolver "+e+" is not a function");if(this instanceof B==!1)throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._then=[],function(e,t){function r(e){F(t,e)}try{e((function(e){j(t,e)}),r)}catch(e){r(e)}}(e,this)}B.prototype={constructor:B,_state:"pending",_then:null,_data:void 0,_handled:!1,then:function(e,t){var r={owner:this,then:new this.constructor(T),fulfilled:e,rejected:t};return!t&&!e||this._handled||(this._handled=!0,"rejected"===this._state&&_&&R(H,this)),"fulfilled"===this._state||"rejected"===this._state?R(A,r):this._then.push(r),r.then},catch:function(e){return this.then(null,e)}},B.all=function(e){if(!Array.isArray(e))throw new TypeError("You must pass an array to Promise.all().");return new B((function(t,r){var n=[],a=0;function o(e){return a++,function(r){n[e]=r,--a||t(n)}}for(var i,l=0;l<e.length;l++)(i=e[l])&&"function"==typeof i.then?i.then(o(l),r):n[l]=i;a||t(n)}))},B.race=function(e){if(!Array.isArray(e))throw new TypeError("You must pass an array to Promise.race().");return new B((function(t,r){for(var n,a=0;a<e.length;a++)(n=e[a])&&"function"==typeof n.then?n.then(t,r):t(n)}))},B.resolve=function(e){return e&&"object"===a(e)&&e.constructor===B?e:new B((function(t){t(e)}))},B.reject=function(e){return new B((function(t,r){r(e)}))};var W={size:16,x:0,y:0,rotate:0,flipX:!1,flipY:!1};function Y(e){if(e&&v){var t=g.createElement("style");t.setAttribute("type","text/css"),t.innerHTML=e;for(var r=g.head.childNodes,n=null,a=r.length-1;a>-1;a--){var o=r[a],i=(o.tagName||"").toUpperCase();["STYLE","LINK"].indexOf(i)>-1&&(n=o)}return g.head.insertBefore(t,n),e}}function Z(){for(var e=12,t="";e-- >0;)t+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[62*Math.random()|0];return t}function K(e){return"".concat(e).replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function X(e){return Object.keys(e||{}).reduce((function(t,r){return t+"".concat(r,": ").concat(e[r],";")}),"")}function Q(e){return e.size!==W.size||e.x!==W.x||e.y!==W.y||e.rotate!==W.rotate||e.flipX||e.flipY}function q(e){var t=e.transform,r=e.containerWidth,n=e.iconWidth,a={transform:"translate(".concat(r/2," 256)")},o="translate(".concat(32*t.x,", ").concat(32*t.y,") "),i="scale(".concat(t.size/16*(t.flipX?-1:1),", ").concat(t.size/16*(t.flipY?-1:1),") "),l="rotate(".concat(t.rotate," 0 0)");return{outer:a,inner:{transform:"".concat(o," ").concat(i," ").concat(l)},path:{transform:"translate(".concat(n/2*-1," -256)")}}}var $={x:0,y:0,width:"100%",height:"100%"};function J(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e.attributes&&(e.attributes.fill||t)&&(e.attributes.fill="black"),e}function ee(e){var t=e.icons,r=t.main,n=t.mask,a=e.prefix,o=e.iconName,i=e.transform,s=e.symbol,p=e.title,c=e.maskId,u=e.titleId,d=e.extra,h=e.watchable,b=void 0!==h&&h,m=n.found?n:r,g=m.width,f=m.height,v="fak"===a,y=v?"":"fa-w-".concat(Math.ceil(g/f*16)),C=[x.replacementClass,o?"".concat(x.familyPrefix,"-").concat(o):"",y].filter((function(e){return-1===d.classes.indexOf(e)})).filter((function(e){return""!==e||!!e})).concat(d.classes).join(" "),E={children:[],attributes:l({},d.attributes,{"data-prefix":a,"data-icon":o,class:C,role:d.attributes.role||"img",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 ".concat(g," ").concat(f)})},O=v&&!~d.classes.indexOf("fa-fw")?{width:"".concat(g/f*16*.0625,"em")}:{};b&&(E.attributes["data-fa-i2svg"]=""),p&&E.children.push({tag:"title",attributes:{id:E.attributes["aria-labelledby"]||"title-".concat(u||Z())},children:[p]});var S=l({},E,{prefix:a,iconName:o,main:r,mask:n,maskId:c,transform:i,symbol:s,styles:l({},O,d.styles)}),P=n.found&&r.found?function(e){var t,r=e.children,n=e.attributes,a=e.main,o=e.mask,i=e.maskId,s=e.transform,p=a.width,c=a.icon,u=o.width,d=o.icon,h=q({transform:s,containerWidth:u,iconWidth:p}),b={tag:"rect",attributes:l({},$,{fill:"white"})},m=c.children?{children:c.children.map(J)}:{},g={tag:"g",attributes:l({},h.inner),children:[J(l({tag:c.tag,attributes:l({},c.attributes,h.path)},m))]},f={tag:"g",attributes:l({},h.outer),children:[g]},v="mask-".concat(i||Z()),y="clip-".concat(i||Z()),C={tag:"mask",attributes:l({},$,{id:v,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse"}),children:[b,f]},E={tag:"defs",children:[{tag:"clipPath",attributes:{id:y},children:(t=d,"g"===t.tag?t.children:[t])},C]};return r.push(E,{tag:"rect",attributes:l({fill:"currentColor","clip-path":"url(#".concat(y,")"),mask:"url(#".concat(v,")")},$)}),{children:r,attributes:n}}(S):function(e){var t=e.children,r=e.attributes,n=e.main,a=e.transform,o=X(e.styles);if(o.length>0&&(r.style=o),Q(a)){var i=q({transform:a,containerWidth:n.width,iconWidth:n.width});t.push({tag:"g",attributes:l({},i.outer),children:[{tag:"g",attributes:l({},i.inner),children:[{tag:n.icon.tag,children:n.icon.children,attributes:l({},n.icon.attributes,i.path)}]}]})}else t.push(n.icon);return{children:t,attributes:r}}(S),w=P.children,k=P.attributes;return S.children=w,S.attributes=k,s?function(e){var t=e.prefix,r=e.iconName,n=e.children,a=e.attributes,o=e.symbol;return[{tag:"svg",attributes:{style:"display: none;"},children:[{tag:"symbol",attributes:l({},a,{id:!0===o?"".concat(t,"-").concat(x.familyPrefix,"-").concat(r):o}),children:n}]}]}(S):function(e){var t=e.children,r=e.main,n=e.mask,a=e.attributes,o=e.styles,i=e.transform;if(Q(i)&&r.found&&!n.found){var s={x:r.width/r.height/2,y:.5};a.style=X(l({},o,{"transform-origin":"".concat(s.x+i.x/16,"em ").concat(s.y+i.y/16,"em")}))}return[{tag:"svg",attributes:a,children:t}]}(S)}var te=function(){},re=(x.measurePerformance&&f&&f.mark&&f.measure,function(e,t,r,n){var a,o,i,l=Object.keys(e),s=l.length,p=void 0!==n?function(e,t){return function(r,n,a,o){return e.call(t,r,n,a,o)}}(t,n):t;for(void 0===r?(a=1,i=e[l[0]]):(a=0,i=r);a<s;a++)i=p(i,e[o=l[a]],o,e);return i});function ne(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.skipHooks,a=void 0!==n&&n,o=Object.keys(t).reduce((function(e,r){var n=t[r];return!!n.icon?e[n.iconName]=n.icon:e[r]=n,e}),{});"function"!=typeof w.hooks.addPack||a?w.styles[e]=l({},w.styles[e]||{},o):w.hooks.addPack(e,o),"fas"===e&&ne("fa",t)}var ae=w.styles,oe=w.shims,ie=function(){var e=function(e){return re(ae,(function(t,r,n){return t[n]=re(r,e,{}),t}),{})};e((function(e,t,r){return t[3]&&(e[t[3]]=r),e})),e((function(e,t,r){var n=t[2];return e[r]=r,n.forEach((function(t){e[t]=r})),e}));var t="far"in ae;re(oe,(function(e,r){var n=r[0],a=r[1],o=r[2];return"far"!==a||t||(a="fas"),e[n]={prefix:a,iconName:o},e}),{})};ie();w.styles;function le(e,t,r){if(e&&e[t]&&e[t][r])return{prefix:t,iconName:r,icon:e[t][r]}}function se(e){var t=e.tag,r=e.attributes,n=void 0===r?{}:r,a=e.children,o=void 0===a?[]:a;return"string"==typeof e?K(e):"<".concat(t," ").concat(function(e){return Object.keys(e||{}).reduce((function(t,r){return t+"".concat(r,'="').concat(K(e[r]),'" ')}),"").trim()}(n),">").concat(o.map(se).join(""),"</").concat(t,">")}var pe=function(e){var t={size:16,x:0,y:0,flipX:!1,flipY:!1,rotate:0};return e?e.toLowerCase().split(" ").reduce((function(e,t){var r=t.toLowerCase().split("-"),n=r[0],a=r.slice(1).join("-");if(n&&"h"===a)return e.flipX=!0,e;if(n&&"v"===a)return e.flipY=!0,e;if(a=parseFloat(a),isNaN(a))return e;switch(n){case"grow":e.size=e.size+a;break;case"shrink":e.size=e.size-a;break;case"left":e.x=e.x-a;break;case"right":e.x=e.x+a;break;case"up":e.y=e.y-a;break;case"down":e.y=e.y+a;break;case"rotate":e.rotate=e.rotate+a}return e}),t):t};function ce(e){this.name="MissingIcon",this.message=e||"Icon unavailable",this.stack=(new Error).stack}ce.prototype=Object.create(Error.prototype),ce.prototype.constructor=ce;var ue={fill:"currentColor"},de={attributeType:"XML",repeatCount:"indefinite",dur:"2s"},he={tag:"path",attributes:l({},ue,{d:"M156.5,447.7l-12.6,29.5c-18.7-9.5-35.9-21.2-51.5-34.9l22.7-22.7C127.6,430.5,141.5,440,156.5,447.7z M40.6,272H8.5 c1.4,21.2,5.4,41.7,11.7,61.1L50,321.2C45.1,305.5,41.8,289,40.6,272z M40.6,240c1.4-18.8,5.2-37,11.1-54.1l-29.5-12.6 C14.7,194.3,10,216.7,8.5,240H40.6z M64.3,156.5c7.8-14.9,17.2-28.8,28.1-41.5L69.7,92.3c-13.7,15.6-25.5,32.8-34.9,51.5 L64.3,156.5z M397,419.6c-13.9,12-29.4,22.3-46.1,30.4l11.9,29.8c20.7-9.9,39.8-22.6,56.9-37.6L397,419.6z M115,92.4 c13.9-12,29.4-22.3,46.1-30.4l-11.9-29.8c-20.7,9.9-39.8,22.6-56.8,37.6L115,92.4z M447.7,355.5c-7.8,14.9-17.2,28.8-28.1,41.5 l22.7,22.7c13.7-15.6,25.5-32.9,34.9-51.5L447.7,355.5z M471.4,272c-1.4,18.8-5.2,37-11.1,54.1l29.5,12.6 c7.5-21.1,12.2-43.5,13.6-66.8H471.4z M321.2,462c-15.7,5-32.2,8.2-49.2,9.4v32.1c21.2-1.4,41.7-5.4,61.1-11.7L321.2,462z M240,471.4c-18.8-1.4-37-5.2-54.1-11.1l-12.6,29.5c21.1,7.5,43.5,12.2,66.8,13.6V471.4z M462,190.8c5,15.7,8.2,32.2,9.4,49.2h32.1 c-1.4-21.2-5.4-41.7-11.7-61.1L462,190.8z M92.4,397c-12-13.9-22.3-29.4-30.4-46.1l-29.8,11.9c9.9,20.7,22.6,39.8,37.6,56.9 L92.4,397z M272,40.6c18.8,1.4,36.9,5.2,54.1,11.1l12.6-29.5C317.7,14.7,295.3,10,272,8.5V40.6z M190.8,50 c15.7-5,32.2-8.2,49.2-9.4V8.5c-21.2,1.4-41.7,5.4-61.1,11.7L190.8,50z M442.3,92.3L419.6,115c12,13.9,22.3,29.4,30.5,46.1 l29.8-11.9C470,128.5,457.3,109.4,442.3,92.3z M397,92.4l22.7-22.7c-15.6-13.7-32.8-25.5-51.5-34.9l-12.6,29.5 C370.4,72.1,384.4,81.5,397,92.4z"})},be=l({},de,{attributeName:"opacity"});l({},ue,{cx:"256",cy:"364",r:"28"}),l({},de,{attributeName:"r",values:"28;14;28;28;14;28;"}),l({},be,{values:"1;0;1;1;0;1;"}),l({},ue,{opacity:"1",d:"M263.7,312h-16c-6.6,0-12-5.4-12-12c0-71,77.4-63.9,77.4-107.8c0-20-17.8-40.2-57.4-40.2c-29.1,0-44.3,9.6-59.2,28.7 c-3.9,5-11.1,6-16.2,2.4l-13.1-9.2c-5.6-3.9-6.9-11.8-2.6-17.2c21.2-27.2,46.4-44.7,91.2-44.7c52.3,0,97.4,29.8,97.4,80.2 c0,67.6-77.4,63.5-77.4,107.8C275.7,306.6,270.3,312,263.7,312z"}),l({},be,{values:"1;0;0;0;0;1;"}),l({},ue,{opacity:"0",d:"M232.5,134.5l7,168c0.3,6.4,5.6,11.5,12,11.5h9c6.4,0,11.7-5.1,12-11.5l7-168c0.3-6.8-5.2-12.5-12-12.5h-23 C237.7,122,232.2,127.7,232.5,134.5z"}),l({},be,{values:"0;0;1;1;0;0;"}),w.styles;function me(e){var t=e[0],r=e[1],n=s(e.slice(4),1)[0];return{found:!0,width:t,height:r,icon:Array.isArray(n)?{tag:"g",attributes:{class:"".concat(x.familyPrefix,"-").concat(E.GROUP)},children:[{tag:"path",attributes:{class:"".concat(x.familyPrefix,"-").concat(E.SECONDARY),fill:"currentColor",d:n[0]}},{tag:"path",attributes:{class:"".concat(x.familyPrefix,"-").concat(E.PRIMARY),fill:"currentColor",d:n[1]}}]}:{tag:"path",attributes:{fill:"currentColor",d:n}}}}w.styles;function ge(){var e="svg-inline--fa",t=x.familyPrefix,r=x.replacementClass,n='svg:not(:root).svg-inline--fa {\n overflow: visible;\n}\n\n.svg-inline--fa {\n display: inline-block;\n font-size: inherit;\n height: 1em;\n overflow: visible;\n vertical-align: -0.125em;\n}\n.svg-inline--fa.fa-lg {\n vertical-align: -0.225em;\n}\n.svg-inline--fa.fa-w-1 {\n width: 0.0625em;\n}\n.svg-inline--fa.fa-w-2 {\n width: 0.125em;\n}\n.svg-inline--fa.fa-w-3 {\n width: 0.1875em;\n}\n.svg-inline--fa.fa-w-4 {\n width: 0.25em;\n}\n.svg-inline--fa.fa-w-5 {\n width: 0.3125em;\n}\n.svg-inline--fa.fa-w-6 {\n width: 0.375em;\n}\n.svg-inline--fa.fa-w-7 {\n width: 0.4375em;\n}\n.svg-inline--fa.fa-w-8 {\n width: 0.5em;\n}\n.svg-inline--fa.fa-w-9 {\n width: 0.5625em;\n}\n.svg-inline--fa.fa-w-10 {\n width: 0.625em;\n}\n.svg-inline--fa.fa-w-11 {\n width: 0.6875em;\n}\n.svg-inline--fa.fa-w-12 {\n width: 0.75em;\n}\n.svg-inline--fa.fa-w-13 {\n width: 0.8125em;\n}\n.svg-inline--fa.fa-w-14 {\n width: 0.875em;\n}\n.svg-inline--fa.fa-w-15 {\n width: 0.9375em;\n}\n.svg-inline--fa.fa-w-16 {\n width: 1em;\n}\n.svg-inline--fa.fa-w-17 {\n width: 1.0625em;\n}\n.svg-inline--fa.fa-w-18 {\n width: 1.125em;\n}\n.svg-inline--fa.fa-w-19 {\n width: 1.1875em;\n}\n.svg-inline--fa.fa-w-20 {\n width: 1.25em;\n}\n.svg-inline--fa.fa-pull-left {\n margin-right: 0.3em;\n width: auto;\n}\n.svg-inline--fa.fa-pull-right {\n margin-left: 0.3em;\n width: auto;\n}\n.svg-inline--fa.fa-border {\n height: 1.5em;\n}\n.svg-inline--fa.fa-li {\n width: 2em;\n}\n.svg-inline--fa.fa-fw {\n width: 1.25em;\n}\n\n.fa-layers svg.svg-inline--fa {\n bottom: 0;\n left: 0;\n margin: auto;\n position: absolute;\n right: 0;\n top: 0;\n}\n\n.fa-layers {\n display: inline-block;\n height: 1em;\n position: relative;\n text-align: center;\n vertical-align: -0.125em;\n width: 1em;\n}\n.fa-layers svg.svg-inline--fa {\n -webkit-transform-origin: center center;\n transform-origin: center center;\n}\n\n.fa-layers-counter, .fa-layers-text {\n display: inline-block;\n position: absolute;\n text-align: center;\n}\n\n.fa-layers-text {\n left: 50%;\n top: 50%;\n -webkit-transform: translate(-50%, -50%);\n transform: translate(-50%, -50%);\n -webkit-transform-origin: center center;\n transform-origin: center center;\n}\n\n.fa-layers-counter {\n background-color: #ff253a;\n border-radius: 1em;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n color: #fff;\n height: 1.5em;\n line-height: 1;\n max-width: 5em;\n min-width: 1.5em;\n overflow: hidden;\n padding: 0.25em;\n right: 0;\n text-overflow: ellipsis;\n top: 0;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: top right;\n transform-origin: top right;\n}\n\n.fa-layers-bottom-right {\n bottom: 0;\n right: 0;\n top: auto;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: bottom right;\n transform-origin: bottom right;\n}\n\n.fa-layers-bottom-left {\n bottom: 0;\n left: 0;\n right: auto;\n top: auto;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: bottom left;\n transform-origin: bottom left;\n}\n\n.fa-layers-top-right {\n right: 0;\n top: 0;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: top right;\n transform-origin: top right;\n}\n\n.fa-layers-top-left {\n left: 0;\n right: auto;\n top: 0;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: top left;\n transform-origin: top left;\n}\n\n.fa-lg {\n font-size: 1.3333333333em;\n line-height: 0.75em;\n vertical-align: -0.0667em;\n}\n\n.fa-xs {\n font-size: 0.75em;\n}\n\n.fa-sm {\n font-size: 0.875em;\n}\n\n.fa-1x {\n font-size: 1em;\n}\n\n.fa-2x {\n font-size: 2em;\n}\n\n.fa-3x {\n font-size: 3em;\n}\n\n.fa-4x {\n font-size: 4em;\n}\n\n.fa-5x {\n font-size: 5em;\n}\n\n.fa-6x {\n font-size: 6em;\n}\n\n.fa-7x {\n font-size: 7em;\n}\n\n.fa-8x {\n font-size: 8em;\n}\n\n.fa-9x {\n font-size: 9em;\n}\n\n.fa-10x {\n font-size: 10em;\n}\n\n.fa-fw {\n text-align: center;\n width: 1.25em;\n}\n\n.fa-ul {\n list-style-type: none;\n margin-left: 2.5em;\n padding-left: 0;\n}\n.fa-ul > li {\n position: relative;\n}\n\n.fa-li {\n left: -2em;\n position: absolute;\n text-align: center;\n width: 2em;\n line-height: inherit;\n}\n\n.fa-border {\n border: solid 0.08em #eee;\n border-radius: 0.1em;\n padding: 0.2em 0.25em 0.15em;\n}\n\n.fa-pull-left {\n float: left;\n}\n\n.fa-pull-right {\n float: right;\n}\n\n.fa.fa-pull-left,\n.fas.fa-pull-left,\n.far.fa-pull-left,\n.fal.fa-pull-left,\n.fab.fa-pull-left {\n margin-right: 0.3em;\n}\n.fa.fa-pull-right,\n.fas.fa-pull-right,\n.far.fa-pull-right,\n.fal.fa-pull-right,\n.fab.fa-pull-right {\n margin-left: 0.3em;\n}\n\n.fa-spin {\n -webkit-animation: fa-spin 2s infinite linear;\n animation: fa-spin 2s infinite linear;\n}\n\n.fa-pulse {\n -webkit-animation: fa-spin 1s infinite steps(8);\n animation: fa-spin 1s infinite steps(8);\n}\n\n@-webkit-keyframes fa-spin {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n\n@keyframes fa-spin {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n.fa-rotate-90 {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";\n -webkit-transform: rotate(90deg);\n transform: rotate(90deg);\n}\n\n.fa-rotate-180 {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";\n -webkit-transform: rotate(180deg);\n transform: rotate(180deg);\n}\n\n.fa-rotate-270 {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";\n -webkit-transform: rotate(270deg);\n transform: rotate(270deg);\n}\n\n.fa-flip-horizontal {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";\n -webkit-transform: scale(-1, 1);\n transform: scale(-1, 1);\n}\n\n.fa-flip-vertical {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";\n -webkit-transform: scale(1, -1);\n transform: scale(1, -1);\n}\n\n.fa-flip-both, .fa-flip-horizontal.fa-flip-vertical {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";\n -webkit-transform: scale(-1, -1);\n transform: scale(-1, -1);\n}\n\n:root .fa-rotate-90,\n:root .fa-rotate-180,\n:root .fa-rotate-270,\n:root .fa-flip-horizontal,\n:root .fa-flip-vertical,\n:root .fa-flip-both {\n -webkit-filter: none;\n filter: none;\n}\n\n.fa-stack {\n display: inline-block;\n height: 2em;\n position: relative;\n width: 2.5em;\n}\n\n.fa-stack-1x,\n.fa-stack-2x {\n bottom: 0;\n left: 0;\n margin: auto;\n position: absolute;\n right: 0;\n top: 0;\n}\n\n.svg-inline--fa.fa-stack-1x {\n height: 1em;\n width: 1.25em;\n}\n.svg-inline--fa.fa-stack-2x {\n height: 2em;\n width: 2.5em;\n}\n\n.fa-inverse {\n color: #fff;\n}\n\n.sr-only {\n border: 0;\n clip: rect(0, 0, 0, 0);\n height: 1px;\n margin: -1px;\n overflow: hidden;\n padding: 0;\n position: absolute;\n width: 1px;\n}\n\n.sr-only-focusable:active, .sr-only-focusable:focus {\n clip: auto;\n height: auto;\n margin: 0;\n overflow: visible;\n position: static;\n width: auto;\n}\n\n.svg-inline--fa .fa-primary {\n fill: var(--fa-primary-color, currentColor);\n opacity: 1;\n opacity: var(--fa-primary-opacity, 1);\n}\n\n.svg-inline--fa .fa-secondary {\n fill: var(--fa-secondary-color, currentColor);\n opacity: 0.4;\n opacity: var(--fa-secondary-opacity, 0.4);\n}\n\n.svg-inline--fa.fa-swap-opacity .fa-primary {\n opacity: 0.4;\n opacity: var(--fa-secondary-opacity, 0.4);\n}\n\n.svg-inline--fa.fa-swap-opacity .fa-secondary {\n opacity: 1;\n opacity: var(--fa-primary-opacity, 1);\n}\n\n.svg-inline--fa mask .fa-primary,\n.svg-inline--fa mask .fa-secondary {\n fill: black;\n}\n\n.fad.fa-inverse {\n color: #fff;\n}';if("fa"!==t||r!==e){var a=new RegExp("\\.".concat("fa","\\-"),"g"),o=new RegExp("\\--".concat("fa","\\-"),"g"),i=new RegExp("\\.".concat(e),"g");n=n.replace(a,".".concat(t,"-")).replace(o,"--".concat(t,"-")).replace(i,".".concat(r))}return n}function fe(){x.autoAddCss&&!Oe&&(Y(ge()),Oe=!0)}function ve(e,t){return Object.defineProperty(e,"abstract",{get:t}),Object.defineProperty(e,"html",{get:function(){return e.abstract.map((function(e){return se(e)}))}}),Object.defineProperty(e,"node",{get:function(){if(v){var t=g.createElement("div");return t.innerHTML=e.html,t.children}}}),e}function ye(e){var t=e.prefix,r=void 0===t?"fa":t,n=e.iconName;if(n)return le(Ee.definitions,r,n)||le(w.styles,r,n)}var Ce,Ee=new(function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.definitions={}}var t,r,n;return t=e,(r=[{key:"add",value:function(){for(var e=this,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];var a=r.reduce(this._pullDefinitions,{});Object.keys(a).forEach((function(t){e.definitions[t]=l({},e.definitions[t]||{},a[t]),ne(t,a[t]),ie()}))}},{key:"reset",value:function(){this.definitions={}}},{key:"_pullDefinitions",value:function(e,t){var r=t.prefix&&t.iconName&&t.icon?{0:t}:t;return Object.keys(r).map((function(t){var n=r[t],a=n.prefix,o=n.iconName,i=n.icon;e[a]||(e[a]={}),e[a][o]=i})),e}}])&&o(t.prototype,r),n&&o(t,n),e}()),Oe=!1,Se={transform:function(e){return pe(e)}},xe=(Ce=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=t.transform,n=void 0===r?W:r,a=t.symbol,o=void 0!==a&&a,i=t.mask,s=void 0===i?null:i,p=t.maskId,c=void 0===p?null:p,u=t.title,d=void 0===u?null:u,h=t.titleId,b=void 0===h?null:h,m=t.classes,g=void 0===m?[]:m,f=t.attributes,v=void 0===f?{}:f,y=t.styles,C=void 0===y?{}:y;if(e){var E=e.prefix,O=e.iconName,S=e.icon;return ve(l({type:"icon"},e),(function(){return fe(),x.autoA11y&&(d?v["aria-labelledby"]="".concat(x.replacementClass,"-title-").concat(b||Z()):(v["aria-hidden"]="true",v.focusable="false")),ee({icons:{main:me(S),mask:s?me(s.icon):{found:!1,width:null,height:null,icon:{}}},prefix:E,iconName:O,transform:l({},W,n),symbol:o,title:d,maskId:c,titleId:b,extra:{attributes:v,styles:C,classes:g}})}))}},function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=(e||{}).icon?e:ye(e||{}),n=t.mask;return n&&(n=(n||{}).icon?n:ye(n||{})),Ce(r,l({},t,{mask:n}))})}).call(this,r(11),r(22).setImmediate)},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 40 40'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%23fff;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3Ecopy%3C/title%3E%3Cg id='UI_Elements' data-name='UI Elements'%3E%3Cpath class='cls-1' d='M24,14.89H22.76l-3-3H12.43V26.59h4.26v3h11.5V19Zm.3,1.71,2.14,2.13H24.34Zm-10.91,9V12.93h5.93l2,2H16.69v10.7Zm4.26,3V15.89h5.65v3.84h3.85v8.83Z'/%3E%3C/g%3E%3C/svg%3E"},function(e,t){e.exports=n},function(e,t){e.exports=a},function(e,t,r){"use strict";r.r(t),function(e){var n=r(12);r.d(t,"Inspector",(function(){return n.a}));var a=void 0!==e?e:"undefined"!=typeof window?window:void 0;void 0!==a&&(a.BABYLON=a.BABYLON||{},a.BABYLON.Inspector=n.a)}.call(this,r(11))},function(e,t,r){"use strict"; /** @license React v16.13.1 * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var n=r(4),a="function"==typeof Symbol&&Symbol.for,o=a?Symbol.for("react.element"):60103,i=a?Symbol.for("react.portal"):60106,l=a?Symbol.for("react.fragment"):60107,s=a?Symbol.for("react.strict_mode"):60108,p=a?Symbol.for("react.profiler"):60114,c=a?Symbol.for("react.provider"):60109,u=a?Symbol.for("react.context"):60110,d=a?Symbol.for("react.forward_ref"):60112,h=a?Symbol.for("react.suspense"):60113,b=a?Symbol.for("react.memo"):60115,m=a?Symbol.for("react.lazy"):60116,g="function"==typeof Symbol&&Symbol.iterator;function f(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r<arguments.length;r++)t+="&args[]="+encodeURIComponent(arguments[r]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y={};function C(e,t,r){this.props=e,this.context=t,this.refs=y,this.updater=r||v}function E(){}function O(e,t,r){this.props=e,this.context=t,this.refs=y,this.updater=r||v}C.prototype.isReactComponent={},C.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error(f(85));this.updater.enqueueSetState(this,e,t,"setState")},C.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},E.prototype=C.prototype;var S=O.prototype=new E;S.constructor=O,n(S,C.prototype),S.isPureReactComponent=!0;var x={current:null},P=Object.prototype.hasOwnProperty,w={key:!0,ref:!0,__self:!0,__source:!0};function k(e,t,r){var n,a={},i=null,l=null;if(null!=t)for(n in void 0!==t.ref&&(l=t.ref),void 0!==t.key&&(i=""+t.key),t)P.call(t,n)&&!w.hasOwnProperty(n)&&(a[n]=t[n]);var s=arguments.length-2;if(1===s)a.children=r;else if(1<s){for(var p=Array(s),c=0;c<s;c++)p[c]=arguments[c+2];a.children=p}if(e&&e.defaultProps)for(n in s=e.defaultProps)void 0===a[n]&&(a[n]=s[n]);return{$$typeof:o,type:e,key:i,ref:l,props:a,_owner:x.current}}function N(e){return"object"==typeof e&&null!==e&&e.$$typeof===o}var T=/\/+/g,_=[];function M(e,t,r,n){if(_.length){var a=_.pop();return a.result=e,a.keyPrefix=t,a.func=r,a.context=n,a.count=0,a}return{result:e,keyPrefix:t,func:r,context:n,count:0}}function L(e){e.result=null,e.keyPrefix=null,e.func=null,e.context=null,e.count=0,10>_.length&&_.push(e)}function D(e,t,r){return null==e?0:function e(t,r,n,a){var l=typeof t;"undefined"!==l&&"boolean"!==l||(t=null);var s=!1;if(null===t)s=!0;else switch(l){case"string":case"number":s=!0;break;case"object":switch(t.$$typeof){case o:case i:s=!0}}if(s)return n(a,t,""===r?"."+R(t,0):r),1;if(s=0,r=""===r?".":r+":",Array.isArray(t))for(var p=0;p<t.length;p++){var c=r+R(l=t[p],p);s+=e(l,c,n,a)}else if(null===t||"object"!=typeof t?c=null:c="function"==typeof(c=g&&t[g]||t["@@iterator"])?c:null,"function"==typeof c)for(t=c.call(t),p=0;!(l=t.next()).done;)s+=e(l=l.value,c=r+R(l,p++),n,a);else if("object"===l)throw n=""+t,Error(f(31,"[object Object]"===n?"object with keys {"+Object.keys(t).join(", ")+"}":n,""));return s}(e,"",t,r)}function R(e,t){return"object"==typeof e&&null!==e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+(""+e).replace(/[=:]/g,(function(e){return t[e]}))}(e.key):t.toString(36)}function A(e,t){e.func.call(e.context,t,e.count++)}function I(e,t,r){var n=e.result,a=e.keyPrefix;e=e.func.call(e.context,t,e.count++),Array.isArray(e)?j(e,n,r,(function(e){return e})):null!=e&&(N(e)&&(e=function(e,t){return{$$typeof:o,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}(e,a+(!e.key||t&&t.key===e.key?"":(""+e.key).replace(T,"$&/")+"/")+r)),n.push(e))}function j(e,t,r,n,a){var o="";null!=r&&(o=(""+r).replace(T,"$&/")+"/"),D(e,I,t=M(t,o,n,a)),L(t)}var z={current:null};function F(){var e=z.current;if(null===e)throw Error(f(321));return e}var G={ReactCurrentDispatcher:z,ReactCurrentBatchConfig:{suspense:null},ReactCurrentOwner:x,IsSomeRendererActing:{current:!1},assign:n};t.Children={map:function(e,t,r){if(null==e)return e;var n=[];return j(e,n,null,t,r),n},forEach:function(e,t,r){if(null==e)return e;D(e,A,t=M(null,null,t,r)),L(t)},count:function(e){return D(e,(function(){return null}),null)},toArray:function(e){var t=[];return j(e,t,null,(function(e){return e})),t},only:function(e){if(!N(e))throw Error(f(143));return e}},t.Component=C,t.Fragment=l,t.Profiler=p,t.PureComponent=O,t.StrictMode=s,t.Suspense=h,t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=G,t.cloneElement=function(e,t,r){if(null==e)throw Error(f(267,e));var a=n({},e.props),i=e.key,l=e.ref,s=e._owner;if(null!=t){if(void 0!==t.ref&&(l=t.ref,s=x.current),void 0!==t.key&&(i=""+t.key),e.type&&e.type.defaultProps)var p=e.type.defaultProps;for(c in t)P.call(t,c)&&!w.hasOwnProperty(c)&&(a[c]=void 0===t[c]&&void 0!==p?p[c]:t[c])}var c=arguments.length-2;if(1===c)a.children=r;else if(1<c){p=Array(c);for(var u=0;u<c;u++)p[u]=arguments[u+2];a.children=p}return{$$typeof:o,type:e.type,key:i,ref:l,props:a,_owner:s}},t.createContext=function(e,t){return void 0===t&&(t=null),(e={$$typeof:u,_calculateChangedBits:t,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null}).Provider={$$typeof:c,_context:e},e.Consumer=e},t.createElement=k,t.createFactory=function(e){var t=k.bind(null,e);return t.type=e,t},t.createRef=function(){return{current:null}},t.forwardRef=function(e){return{$$typeof:d,render:e}},t.isValidElement=N,t.lazy=function(e){return{$$typeof:m,_ctor:e,_status:-1,_result:null}},t.memo=function(e,t){return{$$typeof:b,type:e,compare:void 0===t?null:t}},t.useCallback=function(e,t){return F().useCallback(e,t)},t.useContext=function(e,t){return F().useContext(e,t)},t.useDebugValue=function(){},t.useEffect=function(e,t){return F().useEffect(e,t)},t.useImperativeHandle=function(e,t,r){return F().useImperativeHandle(e,t,r)},t.useLayoutEffect=function(e,t){return F().useLayoutEffect(e,t)},t.useMemo=function(e,t){return F().useMemo(e,t)},t.useReducer=function(e,t,r){return F().useReducer(e,t,r)},t.useRef=function(e){return F().useRef(e)},t.useState=function(e){return F().useState(e)},t.version="16.13.1"},function(e,t,r){"use strict"; /** @license React v16.13.1 * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var n=r(0),a=r(4),o=r(20);function i(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=1;r<arguments.length;r++)t+="&args[]="+encodeURIComponent(arguments[r]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}if(!n)throw Error(i(227));function l(e,t,r,n,a,o,i,l,s){var p=Array.prototype.slice.call(arguments,3);try{t.apply(r,p)}catch(e){this.onError(e)}}var s=!1,p=null,c=!1,u=null,d={onError:function(e){s=!0,p=e}};function h(e,t,r,n,a,o,i,c,u){s=!1,p=null,l.apply(d,arguments)}var b=null,m=null,g=null;function f(e,t,r){var n=e.type||"unknown-event";e.currentTarget=g(r),function(e,t,r,n,a,o,l,d,b){if(h.apply(this,arguments),s){if(!s)throw Error(i(198));var m=p;s=!1,p=null,c||(c=!0,u=m)}}(n,t,void 0,e),e.currentTarget=null}var v=null,y={};function C(){if(v)for(var e in y){var t=y[e],r=v.indexOf(e);if(!(-1<r))throw Error(i(96,e));if(!O[r]){if(!t.extractEvents)throw Error(i(97,e));for(var n in O[r]=t,r=t.eventTypes){var a=void 0,o=r[n],l=t,s=n;if(S.hasOwnProperty(s))throw Error(i(99,s));S[s]=o;var p=o.phasedRegistrationNames;if(p){for(a in p)p.hasOwnProperty(a)&&E(p[a],l,s);a=!0}else o.registrationName?(E(o.registrationName,l,s),a=!0):a=!1;if(!a)throw Error(i(98,n,e))}}}}function E(e,t,r){if(x[e])throw Error(i(100,e));x[e]=t,P[e]=t.eventTypes[r].dependencies}var O=[],S={},x={},P={};function w(e){var t,r=!1;for(t in e)if(e.hasOwnProperty(t)){var n=e[t];if(!y.hasOwnProperty(t)||y[t]!==n){if(y[t])throw Error(i(102,t));y[t]=n,r=!0}}r&&C()}var k=!("undefined"==typeof window||void 0===window.document||void 0===window.document.createElement),N=null,T=null,_=null;function M(e){if(e=m(e)){if("function"!=typeof N)throw Error(i(280));var t=e.stateNode;t&&(t=b(t),N(e.stateNode,e.type,t))}}function L(e){T?_?_.push(e):_=[e]:T=e}function D(){if(T){var e=T,t=_;if(_=T=null,M(e),t)for(e=0;e<t.length;e++)M(t[e])}}function R(e,t){return e(t)}function A(e,t,r,n,a){return e(t,r,n,a)}function I(){}var j=R,z=!1,F=!1;function G(){null===T&&null===_||(I(),D())}function V(e,t,r){if(F)return e(t,r);F=!0;try{return j(e,t,r)}finally{F=!1,G()}}var U=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,H=Object.prototype.hasOwnProperty,B={},W={};function Y(e,t,r,n,a,o){this.acceptsBooleans=2===t||3===t||4===t,this.attributeName=n,this.attributeNamespace=a,this.mustUseProperty=r,this.propertyName=e,this.type=t,this.sanitizeURL=o}var Z={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach((function(e){Z[e]=new Y(e,0,!1,e,null,!1)})),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach((function(e){var t=e[0];Z[t]=new Y(t,1,!1,e[1],null,!1)})),["contentEditable","draggable","spellCheck","value"].forEach((function(e){Z[e]=new Y(e,2,!1,e.toLowerCase(),null,!1)})),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach((function(e){Z[e]=new Y(e,2,!1,e,null,!1)})),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach((function(e){Z[e]=new Y(e,3,!1,e.toLowerCase(),null,!1)})),["checked","multiple","muted","selected"].forEach((function(e){Z[e]=new Y(e,3,!0,e,null,!1)})),["capture","download"].forEach((function(e){Z[e]=new Y(e,4,!1,e,null,!1)})),["cols","rows","size","span"].forEach((function(e){Z[e]=new Y(e,6,!1,e,null,!1)})),["rowSpan","start"].forEach((function(e){Z[e]=new Y(e,5,!1,e.toLowerCase(),null,!1)}));var K=/[\-:]([a-z])/g;function X(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach((function(e){var t=e.replace(K,X);Z[t]=new Y(t,1,!1,e,null,!1)})),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach((function(e){var t=e.replace(K,X);Z[t]=new Y(t,1,!1,e,"http://www.w3.org/1999/xlink",!1)})),["xml:base","xml:lang","xml:space"].forEach((function(e){var t=e.replace(K,X);Z[t]=new Y(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1)})),["tabIndex","crossOrigin"].forEach((function(e){Z[e]=new Y(e,1,!1,e.toLowerCase(),null,!1)})),Z.xlinkHref=new Y("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0),["src","href","action","formAction"].forEach((function(e){Z[e]=new Y(e,1,!1,e.toLowerCase(),null,!0)}));var Q=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function q(e,t,r,n){var a=Z.hasOwnProperty(t)?Z[t]:null;(null!==a?0===a.type:!n&&(2<t.length&&("o"===t[0]||"O"===t[0])&&("n"===t[1]||"N"===t[1])))||(function(e,t,r,n){if(null==t||function(e,t,r,n){if(null!==r&&0===r.type)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return!n&&(null!==r?!r.acceptsBooleans:"data-"!==(e=e.toLowerCase().slice(0,5))&&"aria-"!==e);default:return!1}}(e,t,r,n))return!0;if(n)return!1;if(null!==r)switch(r.type){case 3:return!t;case 4:return!1===t;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}(t,r,a,n)&&(r=null),n||null===a?function(e){return!!H.call(W,e)||!H.call(B,e)&&(U.test(e)?W[e]=!0:(B[e]=!0,!1))}(t)&&(null===r?e.removeAttribute(t):e.setAttribute(t,""+r)):a.mustUseProperty?e[a.propertyName]=null===r?3!==a.type&&"":r:(t=a.attributeName,n=a.attributeNamespace,null===r?e.removeAttribute(t):(r=3===(a=a.type)||4===a&&!0===r?"":""+r,n?e.setAttributeNS(n,t,r):e.setAttribute(t,r))))}Q.hasOwnProperty("ReactCurrentDispatcher")||(Q.ReactCurrentDispatcher={current:null}),Q.hasOwnProperty("ReactCurrentBatchConfig")||(Q.ReactCurrentBatchConfig={suspense:null});var $=/^(.*)[\\\/]/,J="function"==typeof Symbol&&Symbol.for,ee=J?Symbol.for("react.element"):60103,te=J?Symbol.for("react.portal"):60106,re=J?Symbol.for("react.fragment"):60107,ne=J?Symbol.for("react.strict_mode"):60108,ae=J?Symbol.for("react.profiler"):60114,oe=J?Symbol.for("react.provider"):60109,ie=J?Symbol.for("react.context"):60110,le=J?Symbol.for("react.concurrent_mode"):60111,se=J?Symbol.for("react.forward_ref"):60112,pe=J?Symbol.for("react.suspense"):60113,ce=J?Symbol.for("react.suspense_list"):60120,ue=J?Symbol.for("react.memo"):60115,de=J?Symbol.for("react.lazy"):60116,he=J?Symbol.for("react.block"):60121,be="function"==typeof Symbol&&Symbol.iterator;function me(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=be&&e[be]||e["@@iterator"])?e:null}function ge(e){if(null==e)return null;if("function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case re:return"Fragment";case te:return"Portal";case ae:return"Profiler";case ne:return"StrictMode";case pe:return"Suspense";case ce:return"SuspenseList"}if("object"==typeof e)switch(e.$$typeof){case ie:return"Context.Consumer";case oe:return"Context.Provider";case se:var t=e.render;return t=t.displayName||t.name||"",e.displayName||(""!==t?"ForwardRef("+t+")":"ForwardRef");case ue:return ge(e.type);case he:return ge(e.render);case de:if(e=1===e._status?e._result:null)return ge(e)}return null}function fe(e){var t="";do{e:switch(e.tag){case 3:case 4:case 6:case 7:case 10:case 9:var r="";break e;default:var n=e._debugOwner,a=e._debugSource,o=ge(e.type);r=null,n&&(r=ge(n.type)),n=o,o="",a?o=" (at "+a.fileName.replace($,"")+":"+a.lineNumber+")":r&&(o=" (created by "+r+")"),r="\n in "+(n||"Unknown")+o}t+=r,e=e.return}while(e);return t}function ve(e){switch(typeof e){case"boolean":case"number":case"object":case"string":case"undefined":return e;default:return""}}function ye(e){var t=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===t||"radio"===t)}function Ce(e){e._valueTracker||(e._valueTracker=function(e){var t=ye(e)?"checked":"value",r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),n=""+e[t];if(!e.hasOwnProperty(t)&&void 0!==r&&"function"==typeof r.get&&"function"==typeof r.set){var a=r.get,o=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return a.call(this)},set:function(e){n=""+e,o.call(this,e)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(e){n=""+e},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}(e))}function Ee(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var r=t.getValue(),n="";return e&&(n=ye(e)?e.checked?"true":"false":e.value),(e=n)!==r&&(t.setValue(e),!0)}function Oe(e,t){var r=t.checked;return a({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=r?r:e._wrapperState.initialChecked})}function Se(e,t){var r=null==t.defaultValue?"":t.defaultValue,n=null!=t.checked?t.checked:t.defaultChecked;r=ve(null!=t.value?t.value:r),e._wrapperState={initialChecked:n,initialValue:r,controlled:"checkbox"===t.type||"radio"===t.type?null!=t.checked:null!=t.value}}function xe(e,t){null!=(t=t.checked)&&q(e,"checked",t,!1)}function Pe(e,t){xe(e,t);var r=ve(t.value),n=t.type;if(null!=r)"number"===n?(0===r&&""===e.value||e.value!=r)&&(e.value=""+r):e.value!==""+r&&(e.value=""+r);else if("submit"===n||"reset"===n)return void e.removeAttribute("value");t.hasOwnProperty("value")?ke(e,t.type,r):t.hasOwnProperty("defaultValue")&&ke(e,t.type,ve(t.defaultValue)),null==t.checked&&null!=t.defaultChecked&&(e.defaultChecked=!!t.defaultChecked)}function we(e,t,r){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var n=t.type;if(!("submit"!==n&&"reset"!==n||void 0!==t.value&&null!==t.value))return;t=""+e._wrapperState.initialValue,r||t===e.value||(e.value=t),e.defaultValue=t}""!==(r=e.name)&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,""!==r&&(e.name=r)}function ke(e,t,r){"number"===t&&e.ownerDocument.activeElement===e||(null==r?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+r&&(e.defaultValue=""+r))}function Ne(e,t){return e=a({children:void 0},t),(t=function(e){var t="";return n.Children.forEach(e,(function(e){null!=e&&(t+=e)})),t}(t.children))&&(e.children=t),e}function Te(e,t,r,n){if(e=e.options,t){t={};for(var a=0;a<r.length;a++)t["$"+r[a]]=!0;for(r=0;r<e.length;r++)a=t.hasOwnProperty("$"+e[r].value),e[r].selected!==a&&(e[r].selected=a),a&&n&&(e[r].defaultSelected=!0)}else{for(r=""+ve(r),t=null,a=0;a<e.length;a++){if(e[a].value===r)return e[a].selected=!0,void(n&&(e[a].defaultSelected=!0));null!==t||e[a].disabled||(t=e[a])}null!==t&&(t.selected=!0)}}function _e(e,t){if(null!=t.dangerouslySetInnerHTML)throw Error(i(91));return a({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function Me(e,t){var r=t.value;if(null==r){if(r=t.children,t=t.defaultValue,null!=r){if(null!=t)throw Error(i(92));if(Array.isArray(r)){if(!(1>=r.length))throw Error(i(93));r=r[0]}t=r}null==t&&(t=""),r=t}e._wrapperState={initialValue:ve(r)}}function Le(e,t){var r=ve(t.value),n=ve(t.defaultValue);null!=r&&((r=""+r)!==e.value&&(e.value=r),null==t.defaultValue&&e.defaultValue!==r&&(e.defaultValue=r)),null!=n&&(e.defaultValue=""+n)}function De(e){var t=e.textContent;t===e._wrapperState.initialValue&&""!==t&&null!==t&&(e.value=t)}var Re="http://www.w3.org/1999/xhtml",Ae="http://www.w3.org/2000/svg";function Ie(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function je(e,t){return null==e||"http://www.w3.org/1999/xhtml"===e?Ie(t):"http://www.w3.org/2000/svg"===e&&"foreignObject"===t?"http://www.w3.org/1999/xhtml":e}var ze,Fe=function(e){return"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(t,r,n,a){MSApp.execUnsafeLocalFunction((function(){return e(t,r)}))}:e}((function(e,t){if(e.namespaceURI!==Ae||"innerHTML"in e)e.innerHTML=t;else{for((ze=ze||document.createElement("div")).innerHTML="<svg>"+t.valueOf().toString()+"</svg>",t=ze.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}}));function Ge(e,t){if(t){var r=e.firstChild;if(r&&r===e.lastChild&&3===r.nodeType)return void(r.nodeValue=t)}e.textContent=t}function Ve(e,t){var r={};return r[e.toLowerCase()]=t.toLowerCase(),r["Webkit"+e]="webkit"+t,r["Moz"+e]="moz"+t,r}var Ue={animationend:Ve("Animation","AnimationEnd"),animationiteration:Ve("Animation","AnimationIteration"),animationstart:Ve("Animation","AnimationStart"),transitionend:Ve("Transition","TransitionEnd")},He={},Be={};function We(e){if(He[e])return He[e];if(!Ue[e])return e;var t,r=Ue[e];for(t in r)if(r.hasOwnProperty(t)&&t in Be)return He[e]=r[t];return e}k&&(Be=document.createElement("div").style,"AnimationEvent"in window||(delete Ue.animationend.animation,delete Ue.animationiteration.animation,delete Ue.animationstart.animation),"TransitionEvent"in window||delete Ue.transitionend.transition);var Ye=We("animationend"),Ze=We("animationiteration"),Ke=We("animationstart"),Xe=We("transitionend"),Qe="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),qe=new("function"==typeof WeakMap?WeakMap:Map);function $e(e){var t=qe.get(e);return void 0===t&&(t=new Map,qe.set(e,t)),t}function Je(e){var t=e,r=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do{0!=(1026&(t=e).effectTag)&&(r=t.return),e=t.return}while(e)}return 3===t.tag?r:null}function et(e){if(13===e.tag){var t=e.memoizedState;if(null===t&&(null!==(e=e.alternate)&&(t=e.memoizedState)),null!==t)return t.dehydrated}return null}function tt(e){if(Je(e)!==e)throw Error(i(188))}function rt(e){if(!(e=function(e){var t=e.alternate;if(!t){if(null===(t=Je(e)))throw Error(i(188));return t!==e?null:e}for(var r=e,n=t;;){var a=r.return;if(null===a)break;var o=a.alternate;if(null===o){if(null!==(n=a.return)){r=n;continue}break}if(a.child===o.child){for(o=a.child;o;){if(o===r)return tt(a),e;if(o===n)return tt(a),t;o=o.sibling}throw Error(i(188))}if(r.return!==n.return)r=a,n=o;else{for(var l=!1,s=a.child;s;){if(s===r){l=!0,r=a,n=o;break}if(s===n){l=!0,n=a,r=o;break}s=s.sibling}if(!l){for(s=o.child;s;){if(s===r){l=!0,r=o,n=a;break}if(s===n){l=!0,n=o,r=a;break}s=s.sibling}if(!l)throw Error(i(189))}}if(r.alternate!==n)throw Error(i(190))}if(3!==r.tag)throw Error(i(188));return r.stateNode.current===r?e:t}(e)))return null;for(var t=e;;){if(5===t.tag||6===t.tag)return t;if(t.child)t.child.return=t,t=t.child;else{if(t===e)break;for(;!t.sibling;){if(!t.return||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}}return null}function nt(e,t){if(null==t)throw Error(i(30));return 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]}function at(e,t,r){Array.isArray(e)?e.forEach(t,r):e&&t.call(r,e)}var ot=null;function it(e){if(e){var t=e._dispatchListeners,r=e._dispatchInstances;if(Array.isArray(t))for(var n=0;n<t.length&&!e.isPropagationStopped();n++)f(e,t[n],r[n]);else t&&f(e,t,r);e._dispatchListeners=null,e._dispatchInstances=null,e.isPersistent()||e.constructor.release(e)}}function lt(e){if(null!==e&&(ot=nt(ot,e)),e=ot,ot=null,e){if(at(e,it),ot)throw Error(i(95));if(c)throw e=u,c=!1,u=null,e}}function st(e){return(e=e.target||e.srcElement||window).correspondingUseElement&&(e=e.correspondingUseElement),3===e.nodeType?e.parentNode:e}function pt(e){if(!k)return!1;var t=(e="on"+e)in document;return t||((t=document.createElement("div")).setAttribute(e,"return;"),t="function"==typeof t[e]),t}var ct=[];function ut(e){e.topLevelType=null,e.nativeEvent=null,e.targetInst=null,e.ancestors.length=0,10>ct.length&&ct.push(e)}function dt(e,t,r,n){if(ct.length){var a=ct.pop();return a.topLevelType=e,a.eventSystemFlags=n,a.nativeEvent=t,a.targetInst=r,a}return{topLevelType:e,eventSystemFlags:n,nativeEvent:t,targetInst:r,ancestors:[]}}function ht(e){var t=e.targetInst,r=t;do{if(!r){e.ancestors.push(r);break}var n=r;if(3===n.tag)n=n.stateNode.containerInfo;else{for(;n.return;)n=n.return;n=3!==n.tag?null:n.stateNode.containerInfo}if(!n)break;5!==(t=r.tag)&&6!==t||e.ancestors.push(r),r=wr(n)}while(r);for(r=0;r<e.ancestors.length;r++){t=e.ancestors[r];var a=st(e.nativeEvent);n=e.topLevelType;var o=e.nativeEvent,i=e.eventSystemFlags;0===r&&(i|=64);for(var l=null,s=0;s<O.length;s++){var p=O[s];p&&(p=p.extractEvents(n,t,o,a,i))&&(l=nt(l,p))}lt(l)}}function bt(e,t,r){if(!r.has(e)){switch(e){case"scroll":Kt(t,"scroll",!0);break;case"focus":case"blur":Kt(t,"focus",!0),Kt(t,"blur",!0),r.set("blur",null),r.set("focus",null);break;case"cancel":case"close":pt(e)&&Kt(t,e,!0);break;case"invalid":case"submit":case"reset":break;default:-1===Qe.indexOf(e)&&Zt(e,t)}r.set(e,null)}}var mt,gt,ft,vt=!1,yt=[],Ct=null,Et=null,Ot=null,St=new Map,xt=new Map,Pt=[],wt="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput close cancel copy cut paste click change contextmenu reset submit".split(" "),kt="focus blur dragenter dragleave mouseover mouseout pointerover pointerout gotpointercapture lostpointercapture".split(" ");function Nt(e,t,r,n,a){return{blockedOn:e,topLevelType:t,eventSystemFlags:32|r,nativeEvent:a,container:n}}function Tt(e,t){switch(e){case"focus":case"blur":Ct=null;break;case"dragenter":case"dragleave":Et=null;break;case"mouseover":case"mouseout":Ot=null;break;case"pointerover":case"pointerout":St.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":xt.delete(t.pointerId)}}function _t(e,t,r,n,a,o){return null===e||e.nativeEvent!==o?(e=Nt(t,r,n,a,o),null!==t&&(null!==(t=kr(t))&&gt(t)),e):(e.eventSystemFlags|=n,e)}function Mt(e){var t=wr(e.target);if(null!==t){var r=Je(t);if(null!==r)if(13===(t=r.tag)){if(null!==(t=et(r)))return e.blockedOn=t,void o.unstable_runWithPriority(e.priority,(function(){ft(r)}))}else if(3===t&&r.stateNode.hydrate)return void(e.blockedOn=3===r.tag?r.stateNode.containerInfo:null)}e.blockedOn=null}function Lt(e){if(null!==e.blockedOn)return!1;var t=$t(e.topLevelType,e.eventSystemFlags,e.container,e.nativeEvent);if(null!==t){var r=kr(t);return null!==r&&gt(r),e.blockedOn=t,!1}return!0}function Dt(e,t,r){Lt(e)&&r.delete(t)}function Rt(){for(vt=!1;0<yt.length;){var e=yt[0];if(null!==e.blockedOn){null!==(e=kr(e.blockedOn))&&mt(e);break}var t=$t(e.topLevelType,e.eventSystemFlags,e.container,e.nativeEvent);null!==t?e.blockedOn=t:yt.shift()}null!==Ct&&Lt(Ct)&&(Ct=null),null!==Et&&Lt(Et)&&(Et=null),null!==Ot&&Lt(Ot)&&(Ot=null),St.forEach(Dt),xt.forEach(Dt)}function At(e,t){e.blockedOn===t&&(e.blockedOn=null,vt||(vt=!0,o.unstable_scheduleCallback(o.unstable_NormalPriority,Rt)))}function It(e){function t(t){return At(t,e)}if(0<yt.length){At(yt[0],e);for(var r=1;r<yt.length;r++){var n=yt[r];n.blockedOn===e&&(n.blockedOn=null)}}for(null!==Ct&&At(Ct,e),null!==Et&&At(Et,e),null!==Ot&&At(Ot,e),St.forEach(t),xt.forEach(t),r=0;r<Pt.length;r++)(n=Pt[r]).blockedOn===e&&(n.blockedOn=null);for(;0<Pt.length&&null===(r=Pt[0]).blockedOn;)Mt(r),null===r.blockedOn&&Pt.shift()}var jt={},zt=new Map,Ft=new Map,Gt=["abort","abort",Ye,"animationEnd",Ze,"animationIteration",Ke,"animationStart","canplay","canPlay","canplaythrough","canPlayThrough","durationchange","durationChange","emptied","emptied","encrypted","encrypted","ended","ended","error","error","gotpointercapture","gotPointerCapture","load","load","loadeddata","loadedData","loadedmetadata","loadedMetadata","loadstart","loadStart","lostpointercapture","lostPointerCapture","playing","playing","progress","progress","seeking","seeking","stalled","stalled","suspend","suspend","timeupdate","timeUpdate",Xe,"transitionEnd","waiting","waiting"];function Vt(e,t){for(var r=0;r<e.length;r+=2){var n=e[r],a=e[r+1],o="on"+(a[0].toUpperCase()+a.slice(1));o={phasedRegistrationNames:{bubbled:o,captured:o+"Capture"},dependencies:[n],eventPriority:t},Ft.set(n,t),zt.set(n,o),jt[a]=o}}Vt("blur blur cancel cancel click click close close contextmenu contextMenu copy copy cut cut auxclick auxClick dblclick doubleClick dragend dragEnd dragstart dragStart drop drop focus focus input input invalid invalid keydown keyDown keypress keyPress keyup keyUp mousedown mouseDown mouseup mouseUp paste paste pause pause play play pointercancel pointerCancel pointerdown pointerDown pointerup pointerUp ratechange rateChange reset reset seeked seeked submit submit touchcancel touchCancel touchend touchEnd touchstart touchStart volumechange volumeChange".split(" "),0),Vt("drag drag dragenter dragEnter dragexit dragExit dragleave dragLeave dragover dragOver mousemove mouseMove mouseout mouseOut mouseover mouseOver pointermove pointerMove pointerout pointerOut pointerover pointerOver scroll scroll toggle toggle touchmove touchMove wheel wheel".split(" "),1),Vt(Gt,2);for(var Ut="change selectionchange textInput compositionstart compositionend compositionupdate".split(" "),Ht=0;Ht<Ut.length;Ht++)Ft.set(Ut[Ht],0);var Bt=o.unstable_UserBlockingPriority,Wt=o.unstable_runWithPriority,Yt=!0;function Zt(e,t){Kt(t,e,!1)}function Kt(e,t,r){var n=Ft.get(t);switch(void 0===n?2:n){case 0:n=Xt.bind(null,t,1,e);break;case 1:n=Qt.bind(null,t,1,e);break;default:n=qt.bind(null,t,1,e)}r?e.addEventListener(t,n,!0):e.addEventListener(t,n,!1)}function Xt(e,t,r,n){z||I();var a=qt,o=z;z=!0;try{A(a,e,t,r,n)}finally{(z=o)||G()}}function Qt(e,t,r,n){Wt(Bt,qt.bind(null,e,t,r,n))}function qt(e,t,r,n){if(Yt)if(0<yt.length&&-1<wt.indexOf(e))e=Nt(null,e,t,r,n),yt.push(e);else{var a=$t(e,t,r,n);if(null===a)Tt(e,n);else if(-1<wt.indexOf(e))e=Nt(a,e,t,r,n),yt.push(e);else if(!function(e,t,r,n,a){switch(t){case"focus":return Ct=_t(Ct,e,t,r,n,a),!0;case"dragenter":return Et=_t(Et,e,t,r,n,a),!0;case"mouseover":return Ot=_t(Ot,e,t,r,n,a),!0;case"pointerover":var o=a.pointerId;return St.set(o,_t(St.get(o)||null,e,t,r,n,a)),!0;case"gotpointercapture":return o=a.pointerId,xt.set(o,_t(xt.get(o)||null,e,t,r,n,a)),!0}return!1}(a,e,t,r,n)){Tt(e,n),e=dt(e,n,null,t);try{V(ht,e)}finally{ut(e)}}}}function $t(e,t,r,n){if(null!==(r=wr(r=st(n)))){var a=Je(r);if(null===a)r=null;else{var o=a.tag;if(13===o){if(null!==(r=et(a)))return r;r=null}else if(3===o){if(a.stateNode.hydrate)return 3===a.tag?a.stateNode.containerInfo:null;r=null}else a!==r&&(r=null)}}e=dt(e,n,r,t);try{V(ht,e)}finally{ut(e)}return null}var Jt={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},er=["Webkit","ms","Moz","O"];function tr(e,t,r){return null==t||"boolean"==typeof t||""===t?"":r||"number"!=typeof t||0===t||Jt.hasOwnProperty(e)&&Jt[e]?(""+t).trim():t+"px"}function rr(e,t){for(var r in e=e.style,t)if(t.hasOwnProperty(r)){var n=0===r.indexOf("--"),a=tr(r,t[r],n);"float"===r&&(r="cssFloat"),n?e.setProperty(r,a):e[r]=a}}Object.keys(Jt).forEach((function(e){er.forEach((function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Jt[t]=Jt[e]}))}));var nr=a({menuitem:!0},{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});function ar(e,t){if(t){if(nr[e]&&(null!=t.children||null!=t.dangerouslySetInnerHTML))throw Error(i(137,e,""));if(null!=t.dangerouslySetInnerHTML){if(null!=t.children)throw Error(i(60));if("object"!=typeof t.dangerouslySetInnerHTML||!("__html"in t.dangerouslySetInnerHTML))throw Error(i(61))}if(null!=t.style&&"object"!=typeof t.style)throw Error(i(62,""))}}function or(e,t){if(-1===e.indexOf("-"))return"string"==typeof t.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var ir=Re;function lr(e,t){var r=$e(e=9===e.nodeType||11===e.nodeType?e:e.ownerDocument);t=P[t];for(var n=0;n<t.length;n++)bt(t[n],e,r)}function sr(){}function pr(e){if(void 0===(e=e||("undefined"!=typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(t){return e.body}}function cr(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function ur(e,t){var r,n=cr(e);for(e=0;n;){if(3===n.nodeType){if(r=e+n.textContent.length,e<=t&&r>=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=cr(n)}}function dr(){for(var e=window,t=pr();t instanceof e.HTMLIFrameElement;){try{var r="string"==typeof t.contentWindow.location.href}catch(e){r=!1}if(!r)break;t=pr((e=t.contentWindow).document)}return t}function hr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}var br=null,mr=null;function gr(e,t){switch(e){case"button":case"input":case"select":case"textarea":return!!t.autoFocus}return!1}function fr(e,t){return"textarea"===e||"option"===e||"noscript"===e||"string"==typeof t.children||"number"==typeof t.children||"object"==typeof t.dangerouslySetInnerHTML&&null!==t.dangerouslySetInnerHTML&&null!=t.dangerouslySetInnerHTML.__html}var vr="function"==typeof setTimeout?setTimeout:void 0,yr="function"==typeof clearTimeout?clearTimeout:void 0;function Cr(e){for(;null!=e;e=e.nextSibling){var t=e.nodeType;if(1===t||3===t)break}return e}function Er(e){e=e.previousSibling;for(var t=0;e;){if(8===e.nodeType){var r=e.data;if("$"===r||"$!"===r||"$?"===r){if(0===t)return e;t--}else"/$"===r&&t++}e=e.previousSibling}return null}var Or=Math.random().toString(36).slice(2),Sr="__reactInternalInstance$"+Or,xr="__reactEventHandlers$"+Or,Pr="__reactContainere$"+Or;function wr(e){var t=e[Sr];if(t)return t;for(var r=e.parentNode;r;){if(t=r[Pr]||r[Sr]){if(r=t.alternate,null!==t.child||null!==r&&null!==r.child)for(e=Er(e);null!==e;){if(r=e[Sr])return r;e=Er(e)}return t}r=(e=r).parentNode}return null}function kr(e){return!(e=e[Sr]||e[Pr])||5!==e.tag&&6!==e.tag&&13!==e.tag&&3!==e.tag?null:e}function Nr(e){if(5===e.tag||6===e.tag)return e.stateNode;throw Error(i(33))}function Tr(e){return e[xr]||null}function _r(e){do{e=e.return}while(e&&5!==e.tag);return e||null}function Mr(e,t){var r=e.stateNode;if(!r)return null;var n=b(r);if(!n)return null;r=n[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(n=!n.disabled)||(n=!("button"===(e=e.type)||"input"===e||"select"===e||"textarea"===e)),e=!n;break e;default:e=!1}if(e)return null;if(r&&"function"!=typeof r)throw Error(i(231,t,typeof r));return r}function Lr(e,t,r){(t=Mr(e,r.dispatchConfig.phasedRegistrationNames[t]))&&(r._dispatchListeners=nt(r._dispatchListeners,t),r._dispatchInstances=nt(r._dispatchInstances,e))}function Dr(e){if(e&&e.dispatchConfig.phasedRegistrationNames){for(var t=e._targetInst,r=[];t;)r.push(t),t=_r(t);for(t=r.length;0<t--;)Lr(r[t],"captured",e);for(t=0;t<r.length;t++)Lr(r[t],"bubbled",e)}}function Rr(e,t,r){e&&r&&r.dispatchConfig.registrationName&&(t=Mr(e,r.dispatchConfig.registrationName))&&(r._dispatchListeners=nt(r._dispatchListeners,t),r._dispatchInstances=nt(r._dispatchInstances,e))}function Ar(e){e&&e.dispatchConfig.registrationName&&Rr(e._targetInst,null,e)}function Ir(e){at(e,Dr)}var jr=null,zr=null,Fr=null;function Gr(){if(Fr)return Fr;var e,t,r=zr,n=r.length,a="value"in jr?jr.value:jr.textContent,o=a.length;for(e=0;e<n&&r[e]===a[e];e++);var i=n-e;for(t=1;t<=i&&r[n-t]===a[o-t];t++);return Fr=a.slice(e,1<t?1-t:void 0)}function Vr(){return!0}function Ur(){return!1}function Hr(e,t,r,n){for(var a in this.dispatchConfig=e,this._targetInst=t,this.nativeEvent=r,e=this.constructor.Interface)e.hasOwnProperty(a)&&((t=e[a])?this[a]=t(r):"target"===a?this.target=n:this[a]=r[a]);return this.isDefaultPrevented=(null!=r.defaultPrevented?r.defaultPrevented:!1===r.returnValue)?Vr:Ur,this.isPropagationStopped=Ur,this}function Br(e,t,r,n){if(this.eventPool.length){var a=this.eventPool.pop();return this.call(a,e,t,r,n),a}return new this(e,t,r,n)}function Wr(e){if(!(e instanceof this))throw Error(i(279));e.destructor(),10>this.eventPool.length&&this.eventPool.push(e)}function Yr(e){e.eventPool=[],e.getPooled=Br,e.release=Wr}a(Hr.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=Vr)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=Vr)},persist:function(){this.isPersistent=Vr},isPersistent:Ur,destructor:function(){var e,t=this.constructor.Interface;for(e in t)this[e]=null;this.nativeEvent=this._targetInst=this.dispatchConfig=null,this.isPropagationStopped=this.isDefaultPrevented=Ur,this._dispatchInstances=this._dispatchListeners=null}}),Hr.Interface={type:null,target:null,currentTarget:function(){return null},eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null},Hr.extend=function(e){function t(){}function r(){return n.apply(this,arguments)}var n=this;t.prototype=n.prototype;var o=new t;return a(o,r.prototype),r.prototype=o,r.prototype.constructor=r,r.Interface=a({},n.Interface,e),r.extend=n.extend,Yr(r),r},Yr(Hr);var Zr=Hr.extend({data:null}),Kr=Hr.extend({data:null}),Xr=[9,13,27,32],Qr=k&&"CompositionEvent"in window,qr=null;k&&"documentMode"in document&&(qr=document.documentMode);var $r=k&&"TextEvent"in window&&!qr,Jr=k&&(!Qr||qr&&8<qr&&11>=qr),en=String.fromCharCode(32),tn={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["compositionend","keypress","textInput","paste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:"blur compositionend keydown keypress keyup mousedown".split(" ")},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",captured:"onCompositionStartCapture"},dependencies:"blur compositionstart keydown keypress keyup mousedown".split(" ")},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:"blur compositionupdate keydown keypress keyup mousedown".split(" ")}},rn=!1;function nn(e,t){switch(e){case"keyup":return-1!==Xr.indexOf(t.keyCode);case"keydown":return 229!==t.keyCode;case"keypress":case"mousedown":case"blur":return!0;default:return!1}}function an(e){return"object"==typeof(e=e.detail)&&"data"in e?e.data:null}var on=!1;var ln={eventTypes:tn,extractEvents:function(e,t,r,n){var a;if(Qr)e:{switch(e){case"compositionstart":var o=tn.compositionStart;break e;case"compositionend":o=tn.compositionEnd;break e;case"compositionupdate":o=tn.compositionUpdate;break e}o=void 0}else on?nn(e,r)&&(o=tn.compositionEnd):"keydown"===e&&229===r.keyCode&&(o=tn.compositionStart);return o?(Jr&&"ko"!==r.locale&&(on||o!==tn.compositionStart?o===tn.compositionEnd&&on&&(a=Gr()):(zr="value"in(jr=n)?jr.value:jr.textContent,on=!0)),o=Zr.getPooled(o,t,r,n),a?o.data=a:null!==(a=an(r))&&(o.data=a),Ir(o),a=o):a=null,(e=$r?function(e,t){switch(e){case"compositionend":return an(t);case"keypress":return 32!==t.which?null:(rn=!0,en);case"textInput":return(e=t.data)===en&&rn?null:e;default:return null}}(e,r):function(e,t){if(on)return"compositionend"===e||!Qr&&nn(e,t)?(e=Gr(),Fr=zr=jr=null,on=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return Jr&&"ko"!==t.locale?null:t.data;default:return null}}(e,r))?((t=Kr.getPooled(tn.beforeInput,t,r,n)).data=e,Ir(t)):t=null,null===a?t:null===t?a:[a,t]}},sn={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};function pn(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!sn[e.type]:"textarea"===t}var cn={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:"blur change click focus input keydown keyup selectionchange".split(" ")}};function un(e,t,r){return(e=Hr.getPooled(cn.change,e,t,r)).type="change",L(r),Ir(e),e}var dn=null,hn=null;function bn(e){lt(e)}function mn(e){if(Ee(Nr(e)))return e}function gn(e,t){if("change"===e)return t}var fn=!1;function vn(){dn&&(dn.detachEvent("onpropertychange",yn),hn=dn=null)}function yn(e){if("value"===e.propertyName&&mn(hn))if(e=un(hn,e,st(e)),z)lt(e);else{z=!0;try{R(bn,e)}finally{z=!1,G()}}}function Cn(e,t,r){"focus"===e?(vn(),hn=r,(dn=t).attachEvent("onpropertychange",yn)):"blur"===e&&vn()}function En(e){if("selectionchange"===e||"keyup"===e||"keydown"===e)return mn(hn)}function On(e,t){if("click"===e)return mn(t)}function Sn(e,t){if("input"===e||"change"===e)return mn(t)}k&&(fn=pt("input")&&(!document.documentMode||9<document.documentMode));var xn={eventTypes:cn,_isInputEventSupported:fn,extractEvents:function(e,t,r,n){var a=t?Nr(t):window,o=a.nodeName&&a.nodeName.toLowerCase();if("select"===o||"input"===o&&"file"===a.type)var i=gn;else if(pn(a))if(fn)i=Sn;else{i=En;var l=Cn}else(o=a.nodeName)&&"input"===o.toLowerCase()&&("checkbox"===a.type||"radio"===a.type)&&(i=On);if(i&&(i=i(e,t)))return un(i,r,n);l&&l(e,a,t),"blur"===e&&(e=a._wrapperState)&&e.controlled&&"number"===a.type&&ke(a,"number",a.value)}},Pn=Hr.extend({view:null,detail:null}),wn={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function kn(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):!!(e=wn[e])&&!!t[e]}function Nn(){return kn}var Tn=0,_n=0,Mn=!1,Ln=!1,Dn=Pn.extend({screenX:null,screenY:null,clientX:null,clientY:null,pageX:null,pageY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:Nn,button:null,buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},movementX:function(e){if("movementX"in e)return e.movementX;var t=Tn;return Tn=e.screenX,Mn?"mousemove"===e.type?e.screenX-t:0:(Mn=!0,0)},movementY:function(e){if("movementY"in e)return e.movementY;var t=_n;return _n=e.screenY,Ln?"mousemove"===e.type?e.screenY-t:0:(Ln=!0,0)}}),Rn=Dn.extend({pointerId:null,width:null,height:null,pressure:null,tangentialPressure:null,tiltX:null,tiltY:null,twist:null,pointerType:null,isPrimary:null}),An={mouseEnter:{registrationName:"onMouseEnter",dependencies:["mouseout","mouseover"]},mouseLeave:{registrationName:"onMouseLeave",dependencies:["mouseout","mouseover"]},pointerEnter:{registrationName:"onPointerEnter",dependencies:["pointerout","pointerover"]},pointerLeave:{registrationName:"onPointerLeave",dependencies:["pointerout","pointerover"]}},In={eventTypes:An,extractEvents:function(e,t,r,n,a){var o="mouseover"===e||"pointerover"===e,i="mouseout"===e||"pointerout"===e;if(o&&0==(32&a)&&(r.relatedTarget||r.fromElement)||!i&&!o)return null;(o=n.window===n?n:(o=n.ownerDocument)?o.defaultView||o.parentWindow:window,i)?(i=t,null!==(t=(t=r.relatedTarget||r.toElement)?wr(t):null)&&(t!==Je(t)||5!==t.tag&&6!==t.tag)&&(t=null)):i=null;if(i===t)return null;if("mouseout"===e||"mouseover"===e)var l=Dn,s=An.mouseLeave,p=An.mouseEnter,c="mouse";else"pointerout"!==e&&"pointerover"!==e||(l=Rn,s=An.pointerLeave,p=An.pointerEnter,c="pointer");if(e=null==i?o:Nr(i),o=null==t?o:Nr(t),(s=l.getPooled(s,i,r,n)).type=c+"leave",s.target=e,s.relatedTarget=o,(r=l.getPooled(p,t,r,n)).type=c+"enter",r.target=o,r.relatedTarget=e,c=t,(n=i)&&c)e:{for(p=c,i=0,e=l=n;e;e=_r(e))i++;for(e=0,t=p;t;t=_r(t))e++;for(;0<i-e;)l=_r(l),i--;for(;0<e-i;)p=_r(p),e--;for(;i--;){if(l===p||l===p.alternate)break e;l=_r(l),p=_r(p)}l=null}else l=null;for(p=l,l=[];n&&n!==p&&(null===(i=n.alternate)||i!==p);)l.push(n),n=_r(n);for(n=[];c&&c!==p&&(null===(i=c.alternate)||i!==p);)n.push(c),c=_r(c);for(c=0;c<l.length;c++)Rr(l[c],"bubbled",s);for(c=n.length;0<c--;)Rr(n[c],"captured",r);return 0==(64&a)?[s]:[s,r]}};var jn="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},zn=Object.prototype.hasOwnProperty;function Fn(e,t){if(jn(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(n=0;n<r.length;n++)if(!zn.call(t,r[n])||!jn(e[r[n]],t[r[n]]))return!1;return!0}var Gn=k&&"documentMode"in document&&11>=document.documentMode,Vn={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:"blur contextmenu dragend focus keydown keyup mousedown mouseup selectionchange".split(" ")}},Un=null,Hn=null,Bn=null,Wn=!1;function Yn(e,t){var r=t.window===t?t.document:9===t.nodeType?t:t.ownerDocument;return Wn||null==Un||Un!==pr(r)?null:("selectionStart"in(r=Un)&&hr(r)?r={start:r.selectionStart,end:r.selectionEnd}:r={anchorNode:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset},Bn&&Fn(Bn,r)?null:(Bn=r,(e=Hr.getPooled(Vn.select,Hn,e,t)).type="select",e.target=Un,Ir(e),e))}var Zn={eventTypes:Vn,extractEvents:function(e,t,r,n,a,o){if(!(o=!(a=o||(n.window===n?n.document:9===n.nodeType?n:n.ownerDocument)))){e:{a=$e(a),o=P.onSelect;for(var i=0;i<o.length;i++)if(!a.has(o[i])){a=!1;break e}a=!0}o=!a}if(o)return null;switch(a=t?Nr(t):window,e){case"focus":(pn(a)||"true"===a.contentEditable)&&(Un=a,Hn=t,Bn=null);break;case"blur":Bn=Hn=Un=null;break;case"mousedown":Wn=!0;break;case"contextmenu":case"mouseup":case"dragend":return Wn=!1,Yn(r,n);case"selectionchange":if(Gn)break;case"keydown":case"keyup":return Yn(r,n)}return null}},Kn=Hr.extend({animationName:null,elapsedTime:null,pseudoElement:null}),Xn=Hr.extend({clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),Qn=Pn.extend({relatedTarget:null});function qn(e){var t=e.keyCode;return"charCode"in e?0===(e=e.charCode)&&13===t&&(e=13):e=t,10===e&&(e=13),32<=e||13===e?e:0}var $n={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},Jn={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"},ea=Pn.extend({key:function(e){if(e.key){var t=$n[e.key]||e.key;if("Unidentified"!==t)return t}return"keypress"===e.type?13===(e=qn(e))?"Enter":String.fromCharCode(e):"keydown"===e.type||"keyup"===e.type?Jn[e.keyCode]||"Unidentified":""},location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:Nn,charCode:function(e){return"keypress"===e.type?qn(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?qn(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}}),ta=Dn.extend({dataTransfer:null}),ra=Pn.extend({touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:Nn}),na=Hr.extend({propertyName:null,elapsedTime:null,pseudoElement:null}),aa=Dn.extend({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}),oa={eventTypes:jt,extractEvents:function(e,t,r,n){var a=zt.get(e);if(!a)return null;switch(e){case"keypress":if(0===qn(r))return null;case"keydown":case"keyup":e=ea;break;case"blur":case"focus":e=Qn;break;case"click":if(2===r.button)return null;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":e=Dn;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":e=ta;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":e=ra;break;case Ye:case Ze:case Ke:e=Kn;break;case Xe:e=na;break;case"scroll":e=Pn;break;case"wheel":e=aa;break;case"copy":case"cut":case"paste":e=Xn;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":e=Rn;break;default:e=Hr}return Ir(t=e.getPooled(a,t,r,n)),t}};if(v)throw Error(i(101));v=Array.prototype.slice.call("ResponderEventPlugin SimpleEventPlugin EnterLeaveEventPlugin ChangeEventPlugin SelectEventPlugin BeforeInputEventPlugin".split(" ")),C(),b=Tr,m=kr,g=Nr,w({SimpleEventPlugin:oa,EnterLeaveEventPlugin:In,ChangeEventPlugin:xn,SelectEventPlugin:Zn,BeforeInputEventPlugin:ln});var ia=[],la=-1;function sa(e){0>la||(e.current=ia[la],ia[la]=null,la--)}function pa(e,t){la++,ia[la]=e.current,e.current=t}var ca={},ua={current:ca},da={current:!1},ha=ca;function ba(e,t){var r=e.type.contextTypes;if(!r)return ca;var n=e.stateNode;if(n&&n.__reactInternalMemoizedUnmaskedChildContext===t)return n.__reactInternalMemoizedMaskedChildContext;var a,o={};for(a in r)o[a]=t[a];return n&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function ma(e){return null!=(e=e.childContextTypes)}function ga(){sa(da),sa(ua)}function fa(e,t,r){if(ua.current!==ca)throw Error(i(168));pa(ua,t),pa(da,r)}function va(e,t,r){var n=e.stateNode;if(e=t.childContextTypes,"function"!=typeof n.getChildContext)return r;for(var o in n=n.getChildContext())if(!(o in e))throw Error(i(108,ge(t)||"Unknown",o));return a({},r,{},n)}function ya(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ca,ha=ua.current,pa(ua,e),pa(da,da.current),!0}function Ca(e,t,r){var n=e.stateNode;if(!n)throw Error(i(169));r?(e=va(e,t,ha),n.__reactInternalMemoizedMergedChildContext=e,sa(da),sa(ua),pa(ua,e)):sa(da),pa(da,r)}var Ea=o.unstable_runWithPriority,Oa=o.unstable_scheduleCallback,Sa=o.unstable_cancelCallback,xa=o.unstable_requestPaint,Pa=o.unstable_now,wa=o.unstable_getCurrentPriorityLevel,ka=o.unstable_ImmediatePriority,Na=o.unstable_UserBlockingPriority,Ta=o.unstable_NormalPriority,_a=o.unstable_LowPriority,Ma=o.unstable_IdlePriority,La={},Da=o.unstable_shouldYield,Ra=void 0!==xa?xa:function(){},Aa=null,Ia=null,ja=!1,za=Pa(),Fa=1e4>za?Pa:function(){return Pa()-za};function Ga(){switch(wa()){case ka:return 99;case Na:return 98;case Ta:return 97;case _a:return 96;case Ma:return 95;default:throw Error(i(332))}}function Va(e){switch(e){case 99:return ka;case 98:return Na;case 97:return Ta;case 96:return _a;case 95:return Ma;default:throw Error(i(332))}}function Ua(e,t){return e=Va(e),Ea(e,t)}function Ha(e,t,r){return e=Va(e),Oa(e,t,r)}function Ba(e){return null===Aa?(Aa=[e],Ia=Oa(ka,Ya)):Aa.push(e),La}function Wa(){if(null!==Ia){var e=Ia;Ia=null,Sa(e)}Ya()}function Ya(){if(!ja&&null!==Aa){ja=!0;var e=0;try{var t=Aa;Ua(99,(function(){for(;e<t.length;e++){var r=t[e];do{r=r(!0)}while(null!==r)}})),Aa=null}catch(t){throw null!==Aa&&(Aa=Aa.slice(e+1)),Oa(ka,Wa),t}finally{ja=!1}}}function Za(e,t,r){return 1073741821-(1+((1073741821-e+t/10)/(r/=10)|0))*r}function Ka(e,t){if(e&&e.defaultProps)for(var r in t=a({},t),e=e.defaultProps)void 0===t[r]&&(t[r]=e[r]);return t}var Xa={current:null},Qa=null,qa=null,$a=null;function Ja(){$a=qa=Qa=null}function eo(e){var t=Xa.current;sa(Xa),e.type._context._currentValue=t}function to(e,t){for(;null!==e;){var r=e.alternate;if(e.childExpirationTime<t)e.childExpirationTime=t,null!==r&&r.childExpirationTime<t&&(r.childExpirationTime=t);else{if(!(null!==r&&r.childExpirationTime<t))break;r.childExpirationTime=t}e=e.return}}function ro(e,t){Qa=e,$a=qa=null,null!==(e=e.dependencies)&&null!==e.firstContext&&(e.expirationTime>=t&&(_i=!0),e.firstContext=null)}function no(e,t){if($a!==e&&!1!==t&&0!==t)if("number"==typeof t&&1073741823!==t||($a=e,t=1073741823),t={context:e,observedBits:t,next:null},null===qa){if(null===Qa)throw Error(i(308));qa=t,Qa.dependencies={expirationTime:0,firstContext:t,responders:null}}else qa=qa.next=t;return e._currentValue}var ao=!1;function oo(e){e.updateQueue={baseState:e.memoizedState,baseQueue:null,shared:{pending:null},effects:null}}function io(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,baseQueue:e.baseQueue,shared:e.shared,effects:e.effects})}function lo(e,t){return(e={expirationTime:e,suspenseConfig:t,tag:0,payload:null,callback:null,next:null}).next=e}function so(e,t){if(null!==(e=e.updateQueue)){var r=(e=e.shared).pending;null===r?t.next=t:(t.next=r.next,r.next=t),e.pending=t}}function po(e,t){var r=e.alternate;null!==r&&io(r,e),null===(r=(e=e.updateQueue).baseQueue)?(e.baseQueue=t.next=t,t.next=t):(t.next=r.next,r.next=t)}function co(e,t,r,n){var o=e.updateQueue;ao=!1;var i=o.baseQueue,l=o.shared.pending;if(null!==l){if(null!==i){var s=i.next;i.next=l.next,l.next=s}i=l,o.shared.pending=null,null!==(s=e.alternate)&&(null!==(s=s.updateQueue)&&(s.baseQueue=l))}if(null!==i){s=i.next;var p=o.baseState,c=0,u=null,d=null,h=null;if(null!==s)for(var b=s;;){if((l=b.expirationTime)<n){var m={expirationTime:b.expirationTime,suspenseConfig:b.suspenseConfig,tag:b.tag,payload:b.payload,callback:b.callback,next:null};null===h?(d=h=m,u=p):h=h.next=m,l>c&&(c=l)}else{null!==h&&(h=h.next={expirationTime:1073741823,suspenseConfig:b.suspenseConfig,tag:b.tag,payload:b.payload,callback:b.callback,next:null}),os(l,b.suspenseConfig);e:{var g=e,f=b;switch(l=t,m=r,f.tag){case 1:if("function"==typeof(g=f.payload)){p=g.call(m,p,l);break e}p=g;break e;case 3:g.effectTag=-4097&g.effectTag|64;case 0:if(null==(l="function"==typeof(g=f.payload)?g.call(m,p,l):g))break e;p=a({},p,l);break e;case 2:ao=!0}}null!==b.callback&&(e.effectTag|=32,null===(l=o.effects)?o.effects=[b]:l.push(b))}if(null===(b=b.next)||b===s){if(null===(l=o.shared.pending))break;b=i.next=l.next,l.next=s,o.baseQueue=i=l,o.shared.pending=null}}null===h?u=p:h.next=d,o.baseState=u,o.baseQueue=h,is(c),e.expirationTime=c,e.memoizedState=p}}function uo(e,t,r){if(e=t.effects,t.effects=null,null!==e)for(t=0;t<e.length;t++){var n=e[t],a=n.callback;if(null!==a){if(n.callback=null,n=a,a=r,"function"!=typeof n)throw Error(i(191,n));n.call(a)}}}var ho=Q.ReactCurrentBatchConfig,bo=(new n.Component).refs;function mo(e,t,r,n){r=null==(r=r(n,t=e.memoizedState))?t:a({},t,r),e.memoizedState=r,0===e.expirationTime&&(e.updateQueue.baseState=r)}var go={isMounted:function(e){return!!(e=e._reactInternalFiber)&&Je(e)===e},enqueueSetState:function(e,t,r){e=e._reactInternalFiber;var n=Yl(),a=ho.suspense;(a=lo(n=Zl(n,e,a),a)).payload=t,null!=r&&(a.callback=r),so(e,a),Kl(e,n)},enqueueReplaceState:function(e,t,r){e=e._reactInternalFiber;var n=Yl(),a=ho.suspense;(a=lo(n=Zl(n,e,a),a)).tag=1,a.payload=t,null!=r&&(a.callback=r),so(e,a),Kl(e,n)},enqueueForceUpdate:function(e,t){e=e._reactInternalFiber;var r=Yl(),n=ho.suspense;(n=lo(r=Zl(r,e,n),n)).tag=2,null!=t&&(n.callback=t),so(e,n),Kl(e,r)}};function fo(e,t,r,n,a,o,i){return"function"==typeof(e=e.stateNode).shouldComponentUpdate?e.shouldComponentUpdate(n,o,i):!t.prototype||!t.prototype.isPureReactComponent||(!Fn(r,n)||!Fn(a,o))}function vo(e,t,r){var n=!1,a=ca,o=t.contextType;return"object"==typeof o&&null!==o?o=no(o):(a=ma(t)?ha:ua.current,o=(n=null!=(n=t.contextTypes))?ba(e,a):ca),t=new t(r,o),e.memoizedState=null!==t.state&&void 0!==t.state?t.state:null,t.updater=go,e.stateNode=t,t._reactInternalFiber=e,n&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=a,e.__reactInternalMemoizedMaskedChildContext=o),t}function yo(e,t,r,n){e=t.state,"function"==typeof t.componentWillReceiveProps&&t.componentWillReceiveProps(r,n),"function"==typeof t.UNSAFE_componentWillReceiveProps&&t.UNSAFE_componentWillReceiveProps(r,n),t.state!==e&&go.enqueueReplaceState(t,t.state,null)}function Co(e,t,r,n){var a=e.stateNode;a.props=r,a.state=e.memoizedState,a.refs=bo,oo(e);var o=t.contextType;"object"==typeof o&&null!==o?a.context=no(o):(o=ma(t)?ha:ua.current,a.context=ba(e,o)),co(e,r,a,n),a.state=e.memoizedState,"function"==typeof(o=t.getDerivedStateFromProps)&&(mo(e,t,o,r),a.state=e.memoizedState),"function"==typeof t.getDerivedStateFromProps||"function"==typeof a.getSnapshotBeforeUpdate||"function"!=typeof a.UNSAFE_componentWillMount&&"function"!=typeof a.componentWillMount||(t=a.state,"function"==typeof a.componentWillMount&&a.componentWillMount(),"function"==typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount(),t!==a.state&&go.enqueueReplaceState(a,a.state,null),co(e,r,a,n),a.state=e.memoizedState),"function"==typeof a.componentDidMount&&(e.effectTag|=4)}var Eo=Array.isArray;function Oo(e,t,r){if(null!==(e=r.ref)&&"function"!=typeof e&&"object"!=typeof e){if(r._owner){if(r=r._owner){if(1!==r.tag)throw Error(i(309));var n=r.stateNode}if(!n)throw Error(i(147,e));var a=""+e;return null!==t&&null!==t.ref&&"function"==typeof t.ref&&t.ref._stringRef===a?t.ref:((t=function(e){var t=n.refs;t===bo&&(t=n.refs={}),null===e?delete t[a]:t[a]=e})._stringRef=a,t)}if("string"!=typeof e)throw Error(i(284));if(!r._owner)throw Error(i(290,e))}return e}function So(e,t){if("textarea"!==e.type)throw Error(i(31,"[object Object]"===Object.prototype.toString.call(t)?"object with keys {"+Object.keys(t).join(", ")+"}":t,""))}function xo(e){function t(t,r){if(e){var n=t.lastEffect;null!==n?(n.nextEffect=r,t.lastEffect=r):t.firstEffect=t.lastEffect=r,r.nextEffect=null,r.effectTag=8}}function r(r,n){if(!e)return null;for(;null!==n;)t(r,n),n=n.sibling;return null}function n(e,t){for(e=new Map;null!==t;)null!==t.key?e.set(t.key,t):e.set(t.index,t),t=t.sibling;return e}function a(e,t){return(e=ws(e,t)).index=0,e.sibling=null,e}function o(t,r,n){return t.index=n,e?null!==(n=t.alternate)?(n=n.index)<r?(t.effectTag=2,r):n:(t.effectTag=2,r):r}function l(t){return e&&null===t.alternate&&(t.effectTag=2),t}function s(e,t,r,n){return null===t||6!==t.tag?((t=Ts(r,e.mode,n)).return=e,t):((t=a(t,r)).return=e,t)}function p(e,t,r,n){return null!==t&&t.elementType===r.type?((n=a(t,r.props)).ref=Oo(e,t,r),n.return=e,n):((n=ks(r.type,r.key,r.props,null,e.mode,n)).ref=Oo(e,t,r),n.return=e,n)}function c(e,t,r,n){return null===t||4!==t.tag||t.stateNode.containerInfo!==r.containerInfo||t.stateNode.implementation!==r.implementation?((t=_s(r,e.mode,n)).return=e,t):((t=a(t,r.children||[])).return=e,t)}function u(e,t,r,n,o){return null===t||7!==t.tag?((t=Ns(r,e.mode,n,o)).return=e,t):((t=a(t,r)).return=e,t)}function d(e,t,r){if("string"==typeof t||"number"==typeof t)return(t=Ts(""+t,e.mode,r)).return=e,t;if("object"==typeof t&&null!==t){switch(t.$$typeof){case ee:return(r=ks(t.type,t.key,t.props,null,e.mode,r)).ref=Oo(e,null,t),r.return=e,r;case te:return(t=_s(t,e.mode,r)).return=e,t}if(Eo(t)||me(t))return(t=Ns(t,e.mode,r,null)).return=e,t;So(e,t)}return null}function h(e,t,r,n){var a=null!==t?t.key:null;if("string"==typeof r||"number"==typeof r)return null!==a?null:s(e,t,""+r,n);if("object"==typeof r&&null!==r){switch(r.$$typeof){case ee:return r.key===a?r.type===re?u(e,t,r.props.children,n,a):p(e,t,r,n):null;case te:return r.key===a?c(e,t,r,n):null}if(Eo(r)||me(r))return null!==a?null:u(e,t,r,n,null);So(e,r)}return null}function b(e,t,r,n,a){if("string"==typeof n||"number"==typeof n)return s(t,e=e.get(r)||null,""+n,a);if("object"==typeof n&&null!==n){switch(n.$$typeof){case ee:return e=e.get(null===n.key?r:n.key)||null,n.type===re?u(t,e,n.props.children,a,n.key):p(t,e,n,a);case te:return c(t,e=e.get(null===n.key?r:n.key)||null,n,a)}if(Eo(n)||me(n))return u(t,e=e.get(r)||null,n,a,null);So(t,n)}return null}function m(a,i,l,s){for(var p=null,c=null,u=i,m=i=0,g=null;null!==u&&m<l.length;m++){u.index>m?(g=u,u=null):g=u.sibling;var f=h(a,u,l[m],s);if(null===f){null===u&&(u=g);break}e&&u&&null===f.alternate&&t(a,u),i=o(f,i,m),null===c?p=f:c.sibling=f,c=f,u=g}if(m===l.length)return r(a,u),p;if(null===u){for(;m<l.length;m++)null!==(u=d(a,l[m],s))&&(i=o(u,i,m),null===c?p=u:c.sibling=u,c=u);return p}for(u=n(a,u);m<l.length;m++)null!==(g=b(u,a,m,l[m],s))&&(e&&null!==g.alternate&&u.delete(null===g.key?m:g.key),i=o(g,i,m),null===c?p=g:c.sibling=g,c=g);return e&&u.forEach((function(e){return t(a,e)})),p}function g(a,l,s,p){var c=me(s);if("function"!=typeof c)throw Error(i(150));if(null==(s=c.call(s)))throw Error(i(151));for(var u=c=null,m=l,g=l=0,f=null,v=s.next();null!==m&&!v.done;g++,v=s.next()){m.index>g?(f=m,m=null):f=m.sibling;var y=h(a,m,v.value,p);if(null===y){null===m&&(m=f);break}e&&m&&null===y.alternate&&t(a,m),l=o(y,l,g),null===u?c=y:u.sibling=y,u=y,m=f}if(v.done)return r(a,m),c;if(null===m){for(;!v.done;g++,v=s.next())null!==(v=d(a,v.value,p))&&(l=o(v,l,g),null===u?c=v:u.sibling=v,u=v);return c}for(m=n(a,m);!v.done;g++,v=s.next())null!==(v=b(m,a,g,v.value,p))&&(e&&null!==v.alternate&&m.delete(null===v.key?g:v.key),l=o(v,l,g),null===u?c=v:u.sibling=v,u=v);return e&&m.forEach((function(e){return t(a,e)})),c}return function(e,n,o,s){var p="object"==typeof o&&null!==o&&o.type===re&&null===o.key;p&&(o=o.props.children);var c="object"==typeof o&&null!==o;if(c)switch(o.$$typeof){case ee:e:{for(c=o.key,p=n;null!==p;){if(p.key===c){switch(p.tag){case 7:if(o.type===re){r(e,p.sibling),(n=a(p,o.props.children)).return=e,e=n;break e}break;default:if(p.elementType===o.type){r(e,p.sibling),(n=a(p,o.props)).ref=Oo(e,p,o),n.return=e,e=n;break e}}r(e,p);break}t(e,p),p=p.sibling}o.type===re?((n=Ns(o.props.children,e.mode,s,o.key)).return=e,e=n):((s=ks(o.type,o.key,o.props,null,e.mode,s)).ref=Oo(e,n,o),s.return=e,e=s)}return l(e);case te:e:{for(p=o.key;null!==n;){if(n.key===p){if(4===n.tag&&n.stateNode.containerInfo===o.containerInfo&&n.stateNode.implementation===o.implementation){r(e,n.sibling),(n=a(n,o.children||[])).return=e,e=n;break e}r(e,n);break}t(e,n),n=n.sibling}(n=_s(o,e.mode,s)).return=e,e=n}return l(e)}if("string"==typeof o||"number"==typeof o)return o=""+o,null!==n&&6===n.tag?(r(e,n.sibling),(n=a(n,o)).return=e,e=n):(r(e,n),(n=Ts(o,e.mode,s)).return=e,e=n),l(e);if(Eo(o))return m(e,n,o,s);if(me(o))return g(e,n,o,s);if(c&&So(e,o),void 0===o&&!p)switch(e.tag){case 1:case 0:throw e=e.type,Error(i(152,e.displayName||e.name||"Component"))}return r(e,n)}}var Po=xo(!0),wo=xo(!1),ko={},No={current:ko},To={current:ko},_o={current:ko};function Mo(e){if(e===ko)throw Error(i(174));return e}function Lo(e,t){switch(pa(_o,t),pa(To,e),pa(No,ko),e=t.nodeType){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:je(null,"");break;default:t=je(t=(e=8===e?t.parentNode:t).namespaceURI||null,e=e.tagName)}sa(No),pa(No,t)}function Do(){sa(No),sa(To),sa(_o)}function Ro(e){Mo(_o.current);var t=Mo(No.current),r=je(t,e.type);t!==r&&(pa(To,e),pa(No,r))}function Ao(e){To.current===e&&(sa(No),sa(To))}var Io={current:0};function jo(e){for(var t=e;null!==t;){if(13===t.tag){var r=t.memoizedState;if(null!==r&&(null===(r=r.dehydrated)||"$?"===r.data||"$!"===r.data))return t}else if(19===t.tag&&void 0!==t.memoizedProps.revealOrder){if(0!=(64&t.effectTag))return t}else if(null!==t.child){t.child.return=t,t=t.child;continue}if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}function zo(e,t){return{responder:e,props:t}}var Fo=Q.ReactCurrentDispatcher,Go=Q.ReactCurrentBatchConfig,Vo=0,Uo=null,Ho=null,Bo=null,Wo=!1;function Yo(){throw Error(i(321))}function Zo(e,t){if(null===t)return!1;for(var r=0;r<t.length&&r<e.length;r++)if(!jn(e[r],t[r]))return!1;return!0}function Ko(e,t,r,n,a,o){if(Vo=o,Uo=t,t.memoizedState=null,t.updateQueue=null,t.expirationTime=0,Fo.current=null===e||null===e.memoizedState?fi:vi,e=r(n,a),t.expirationTime===Vo){o=0;do{if(t.expirationTime=0,!(25>o))throw Error(i(301));o+=1,Bo=Ho=null,t.updateQueue=null,Fo.current=yi,e=r(n,a)}while(t.expirationTime===Vo)}if(Fo.current=gi,t=null!==Ho&&null!==Ho.next,Vo=0,Bo=Ho=Uo=null,Wo=!1,t)throw Error(i(300));return e}function Xo(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return null===Bo?Uo.memoizedState=Bo=e:Bo=Bo.next=e,Bo}function Qo(){if(null===Ho){var e=Uo.alternate;e=null!==e?e.memoizedState:null}else e=Ho.next;var t=null===Bo?Uo.memoizedState:Bo.next;if(null!==t)Bo=t,Ho=e;else{if(null===e)throw Error(i(310));e={memoizedState:(Ho=e).memoizedState,baseState:Ho.baseState,baseQueue:Ho.baseQueue,queue:Ho.queue,next:null},null===Bo?Uo.memoizedState=Bo=e:Bo=Bo.next=e}return Bo}function qo(e,t){return"function"==typeof t?t(e):t}function $o(e){var t=Qo(),r=t.queue;if(null===r)throw Error(i(311));r.lastRenderedReducer=e;var n=Ho,a=n.baseQueue,o=r.pending;if(null!==o){if(null!==a){var l=a.next;a.next=o.next,o.next=l}n.baseQueue=a=o,r.pending=null}if(null!==a){a=a.next,n=n.baseState;var s=l=o=null,p=a;do{var c=p.expirationTime;if(c<Vo){var u={expirationTime:p.expirationTime,suspenseConfig:p.suspenseConfig,action:p.action,eagerReducer:p.eagerReducer,eagerState:p.eagerState,next:null};null===s?(l=s=u,o=n):s=s.next=u,c>Uo.expirationTime&&(Uo.expirationTime=c,is(c))}else null!==s&&(s=s.next={expirationTime:1073741823,suspenseConfig:p.suspenseConfig,action:p.action,eagerReducer:p.eagerReducer,eagerState:p.eagerState,next:null}),os(c,p.suspenseConfig),n=p.eagerReducer===e?p.eagerState:e(n,p.action);p=p.next}while(null!==p&&p!==a);null===s?o=n:s.next=l,jn(n,t.memoizedState)||(_i=!0),t.memoizedState=n,t.baseState=o,t.baseQueue=s,r.lastRenderedState=n}return[t.memoizedState,r.dispatch]}function Jo(e){var t=Qo(),r=t.queue;if(null===r)throw Error(i(311));r.lastRenderedReducer=e;var n=r.dispatch,a=r.pending,o=t.memoizedState;if(null!==a){r.pending=null;var l=a=a.next;do{o=e(o,l.action),l=l.next}while(l!==a);jn(o,t.memoizedState)||(_i=!0),t.memoizedState=o,null===t.baseQueue&&(t.baseState=o),r.lastRenderedState=o}return[o,n]}function ei(e){var t=Xo();return"function"==typeof e&&(e=e()),t.memoizedState=t.baseState=e,e=(e=t.queue={pending:null,dispatch:null,lastRenderedReducer:qo,lastRenderedState:e}).dispatch=mi.bind(null,Uo,e),[t.memoizedState,e]}function ti(e,t,r,n){return e={tag:e,create:t,destroy:r,deps:n,next:null},null===(t=Uo.updateQueue)?(t={lastEffect:null},Uo.updateQueue=t,t.lastEffect=e.next=e):null===(r=t.lastEffect)?t.lastEffect=e.next=e:(n=r.next,r.next=e,e.next=n,t.lastEffect=e),e}function ri(){return Qo().memoizedState}function ni(e,t,r,n){var a=Xo();Uo.effectTag|=e,a.memoizedState=ti(1|t,r,void 0,void 0===n?null:n)}function ai(e,t,r,n){var a=Qo();n=void 0===n?null:n;var o=void 0;if(null!==Ho){var i=Ho.memoizedState;if(o=i.destroy,null!==n&&Zo(n,i.deps))return void ti(t,r,o,n)}Uo.effectTag|=e,a.memoizedState=ti(1|t,r,o,n)}function oi(e,t){return ni(516,4,e,t)}function ii(e,t){return ai(516,4,e,t)}function li(e,t){return ai(4,2,e,t)}function si(e,t){return"function"==typeof t?(e=e(),t(e),function(){t(null)}):null!=t?(e=e(),t.current=e,function(){t.current=null}):void 0}function pi(e,t,r){return r=null!=r?r.concat([e]):null,ai(4,2,si.bind(null,t,e),r)}function ci(){}function ui(e,t){return Xo().memoizedState=[e,void 0===t?null:t],e}function di(e,t){var r=Qo();t=void 0===t?null:t;var n=r.memoizedState;return null!==n&&null!==t&&Zo(t,n[1])?n[0]:(r.memoizedState=[e,t],e)}function hi(e,t){var r=Qo();t=void 0===t?null:t;var n=r.memoizedState;return null!==n&&null!==t&&Zo(t,n[1])?n[0]:(e=e(),r.memoizedState=[e,t],e)}function bi(e,t,r){var n=Ga();Ua(98>n?98:n,(function(){e(!0)})),Ua(97<n?97:n,(function(){var n=Go.suspense;Go.suspense=void 0===t?null:t;try{e(!1),r()}finally{Go.suspense=n}}))}function mi(e,t,r){var n=Yl(),a=ho.suspense;a={expirationTime:n=Zl(n,e,a),suspenseConfig:a,action:r,eagerReducer:null,eagerState:null,next:null};var o=t.pending;if(null===o?a.next=a:(a.next=o.next,o.next=a),t.pending=a,o=e.alternate,e===Uo||null!==o&&o===Uo)Wo=!0,a.expirationTime=Vo,Uo.expirationTime=Vo;else{if(0===e.expirationTime&&(null===o||0===o.expirationTime)&&null!==(o=t.lastRenderedReducer))try{var i=t.lastRenderedState,l=o(i,r);if(a.eagerReducer=o,a.eagerState=l,jn(l,i))return}catch(e){}Kl(e,n)}}var gi={readContext:no,useCallback:Yo,useContext:Yo,useEffect:Yo,useImperativeHandle:Yo,useLayoutEffect:Yo,useMemo:Yo,useReducer:Yo,useRef:Yo,useState:Yo,useDebugValue:Yo,useResponder:Yo,useDeferredValue:Yo,useTransition:Yo},fi={readContext:no,useCallback:ui,useContext:no,useEffect:oi,useImperativeHandle:function(e,t,r){return r=null!=r?r.concat([e]):null,ni(4,2,si.bind(null,t,e),r)},useLayoutEffect:function(e,t){return ni(4,2,e,t)},useMemo:function(e,t){var r=Xo();return t=void 0===t?null:t,e=e(),r.memoizedState=[e,t],e},useReducer:function(e,t,r){var n=Xo();return t=void 0!==r?r(t):t,n.memoizedState=n.baseState=t,e=(e=n.queue={pending:null,dispatch:null,lastRenderedReducer:e,lastRenderedState:t}).dispatch=mi.bind(null,Uo,e),[n.memoizedState,e]},useRef:function(e){return e={current:e},Xo().memoizedState=e},useState:ei,useDebugValue:ci,useResponder:zo,useDeferredValue:function(e,t){var r=ei(e),n=r[0],a=r[1];return oi((function(){var r=Go.suspense;Go.suspense=void 0===t?null:t;try{a(e)}finally{Go.suspense=r}}),[e,t]),n},useTransition:function(e){var t=ei(!1),r=t[0];return t=t[1],[ui(bi.bind(null,t,e),[t,e]),r]}},vi={readContext:no,useCallback:di,useContext:no,useEffect:ii,useImperativeHandle:pi,useLayoutEffect:li,useMemo:hi,useReducer:$o,useRef:ri,useState:function(){return $o(qo)},useDebugValue:ci,useResponder:zo,useDeferredValue:function(e,t){var r=$o(qo),n=r[0],a=r[1];return ii((function(){var r=Go.suspense;Go.suspense=void 0===t?null:t;try{a(e)}finally{Go.suspense=r}}),[e,t]),n},useTransition:function(e){var t=$o(qo),r=t[0];return t=t[1],[di(bi.bind(null,t,e),[t,e]),r]}},yi={readContext:no,useCallback:di,useContext:no,useEffect:ii,useImperativeHandle:pi,useLayoutEffect:li,useMemo:hi,useReducer:Jo,useRef:ri,useState:function(){return Jo(qo)},useDebugValue:ci,useResponder:zo,useDeferredValue:function(e,t){var r=Jo(qo),n=r[0],a=r[1];return ii((function(){var r=Go.suspense;Go.suspense=void 0===t?null:t;try{a(e)}finally{Go.suspense=r}}),[e,t]),n},useTransition:function(e){var t=Jo(qo),r=t[0];return t=t[1],[di(bi.bind(null,t,e),[t,e]),r]}},Ci=null,Ei=null,Oi=!1;function Si(e,t){var r=xs(5,null,null,0);r.elementType="DELETED",r.type="DELETED",r.stateNode=t,r.return=e,r.effectTag=8,null!==e.lastEffect?(e.lastEffect.nextEffect=r,e.lastEffect=r):e.firstEffect=e.lastEffect=r}function xi(e,t){switch(e.tag){case 5:var r=e.type;return null!==(t=1!==t.nodeType||r.toLowerCase()!==t.nodeName.toLowerCase()?null:t)&&(e.stateNode=t,!0);case 6:return null!==(t=""===e.pendingProps||3!==t.nodeType?null:t)&&(e.stateNode=t,!0);case 13:default:return!1}}function Pi(e){if(Oi){var t=Ei;if(t){var r=t;if(!xi(e,t)){if(!(t=Cr(r.nextSibling))||!xi(e,t))return e.effectTag=-1025&e.effectTag|2,Oi=!1,void(Ci=e);Si(Ci,r)}Ci=e,Ei=Cr(t.firstChild)}else e.effectTag=-1025&e.effectTag|2,Oi=!1,Ci=e}}function wi(e){for(e=e.return;null!==e&&5!==e.tag&&3!==e.tag&&13!==e.tag;)e=e.return;Ci=e}function ki(e){if(e!==Ci)return!1;if(!Oi)return wi(e),Oi=!0,!1;var t=e.type;if(5!==e.tag||"head"!==t&&"body"!==t&&!fr(t,e.memoizedProps))for(t=Ei;t;)Si(e,t),t=Cr(t.nextSibling);if(wi(e),13===e.tag){if(!(e=null!==(e=e.memoizedState)?e.dehydrated:null))throw Error(i(317));e:{for(e=e.nextSibling,t=0;e;){if(8===e.nodeType){var r=e.data;if("/$"===r){if(0===t){Ei=Cr(e.nextSibling);break e}t--}else"$"!==r&&"$!"!==r&&"$?"!==r||t++}e=e.nextSibling}Ei=null}}else Ei=Ci?Cr(e.stateNode.nextSibling):null;return!0}function Ni(){Ei=Ci=null,Oi=!1}var Ti=Q.ReactCurrentOwner,_i=!1;function Mi(e,t,r,n){t.child=null===e?wo(t,null,r,n):Po(t,e.child,r,n)}function Li(e,t,r,n,a){r=r.render;var o=t.ref;return ro(t,a),n=Ko(e,t,r,n,o,a),null===e||_i?(t.effectTag|=1,Mi(e,t,n,a),t.child):(t.updateQueue=e.updateQueue,t.effectTag&=-517,e.expirationTime<=a&&(e.expirationTime=0),Ki(e,t,a))}function Di(e,t,r,n,a,o){if(null===e){var i=r.type;return"function"!=typeof i||Ps(i)||void 0!==i.defaultProps||null!==r.compare||void 0!==r.defaultProps?((e=ks(r.type,null,n,null,t.mode,o)).ref=t.ref,e.return=t,t.child=e):(t.tag=15,t.type=i,Ri(e,t,i,n,a,o))}return i=e.child,a<o&&(a=i.memoizedProps,(r=null!==(r=r.compare)?r:Fn)(a,n)&&e.ref===t.ref)?Ki(e,t,o):(t.effectTag|=1,(e=ws(i,n)).ref=t.ref,e.return=t,t.child=e)}function Ri(e,t,r,n,a,o){return null!==e&&Fn(e.memoizedProps,n)&&e.ref===t.ref&&(_i=!1,a<o)?(t.expirationTime=e.expirationTime,Ki(e,t,o)):Ii(e,t,r,n,o)}function Ai(e,t){var r=t.ref;(null===e&&null!==r||null!==e&&e.ref!==r)&&(t.effectTag|=128)}function Ii(e,t,r,n,a){var o=ma(r)?ha:ua.current;return o=ba(t,o),ro(t,a),r=Ko(e,t,r,n,o,a),null===e||_i?(t.effectTag|=1,Mi(e,t,r,a),t.child):(t.updateQueue=e.updateQueue,t.effectTag&=-517,e.expirationTime<=a&&(e.expirationTime=0),Ki(e,t,a))}function ji(e,t,r,n,a){if(ma(r)){var o=!0;ya(t)}else o=!1;if(ro(t,a),null===t.stateNode)null!==e&&(e.alternate=null,t.alternate=null,t.effectTag|=2),vo(t,r,n),Co(t,r,n,a),n=!0;else if(null===e){var i=t.stateNode,l=t.memoizedProps;i.props=l;var s=i.context,p=r.contextType;"object"==typeof p&&null!==p?p=no(p):p=ba(t,p=ma(r)?ha:ua.current);var c=r.getDerivedStateFromProps,u="function"==typeof c||"function"==typeof i.getSnapshotBeforeUpdate;u||"function"!=typeof i.UNSAFE_componentWillReceiveProps&&"function"!=typeof i.componentWillReceiveProps||(l!==n||s!==p)&&yo(t,i,n,p),ao=!1;var d=t.memoizedState;i.state=d,co(t,n,i,a),s=t.memoizedState,l!==n||d!==s||da.current||ao?("function"==typeof c&&(mo(t,r,c,n),s=t.memoizedState),(l=ao||fo(t,r,l,n,d,s,p))?(u||"function"!=typeof i.UNSAFE_componentWillMount&&"function"!=typeof i.componentWillMount||("function"==typeof i.componentWillMount&&i.componentWillMount(),"function"==typeof i.UNSAFE_componentWillMount&&i.UNSAFE_componentWillMount()),"function"==typeof i.componentDidMount&&(t.effectTag|=4)):("function"==typeof i.componentDidMount&&(t.effectTag|=4),t.memoizedProps=n,t.memoizedState=s),i.props=n,i.state=s,i.context=p,n=l):("function"==typeof i.componentDidMount&&(t.effectTag|=4),n=!1)}else i=t.stateNode,io(e,t),l=t.memoizedProps,i.props=t.type===t.elementType?l:Ka(t.type,l),s=i.context,"object"==typeof(p=r.contextType)&&null!==p?p=no(p):p=ba(t,p=ma(r)?ha:ua.current),(u="function"==typeof(c=r.getDerivedStateFromProps)||"function"==typeof i.getSnapshotBeforeUpdate)||"function"!=typeof i.UNSAFE_componentWillReceiveProps&&"function"!=typeof i.componentWillReceiveProps||(l!==n||s!==p)&&yo(t,i,n,p),ao=!1,s=t.memoizedState,i.state=s,co(t,n,i,a),d=t.memoizedState,l!==n||s!==d||da.current||ao?("function"==typeof c&&(mo(t,r,c,n),d=t.memoizedState),(c=ao||fo(t,r,l,n,s,d,p))?(u||"function"!=typeof i.UNSAFE_componentWillUpdate&&"function"!=typeof i.componentWillUpdate||("function"==typeof i.componentWillUpdate&&i.componentWillUpdate(n,d,p),"function"==typeof i.UNSAFE_componentWillUpdate&&i.UNSAFE_componentWillUpdate(n,d,p)),"function"==typeof i.componentDidUpdate&&(t.effectTag|=4),"function"==typeof i.getSnapshotBeforeUpdate&&(t.effectTag|=256)):("function"!=typeof i.componentDidUpdate||l===e.memoizedProps&&s===e.memoizedState||(t.effectTag|=4),"function"!=typeof i.getSnapshotBeforeUpdate||l===e.memoizedProps&&s===e.memoizedState||(t.effectTag|=256),t.memoizedProps=n,t.memoizedState=d),i.props=n,i.state=d,i.context=p,n=c):("function"!=typeof i.componentDidUpdate||l===e.memoizedProps&&s===e.memoizedState||(t.effectTag|=4),"function"!=typeof i.getSnapshotBeforeUpdate||l===e.memoizedProps&&s===e.memoizedState||(t.effectTag|=256),n=!1);return zi(e,t,r,n,o,a)}function zi(e,t,r,n,a,o){Ai(e,t);var i=0!=(64&t.effectTag);if(!n&&!i)return a&&Ca(t,r,!1),Ki(e,t,o);n=t.stateNode,Ti.current=t;var l=i&&"function"!=typeof r.getDerivedStateFromError?null:n.render();return t.effectTag|=1,null!==e&&i?(t.child=Po(t,e.child,null,o),t.child=Po(t,null,l,o)):Mi(e,t,l,o),t.memoizedState=n.state,a&&Ca(t,r,!0),t.child}function Fi(e){var t=e.stateNode;t.pendingContext?fa(0,t.pendingContext,t.pendingContext!==t.context):t.context&&fa(0,t.context,!1),Lo(e,t.containerInfo)}var Gi,Vi,Ui,Hi={dehydrated:null,retryTime:0};function Bi(e,t,r){var n,a=t.mode,o=t.pendingProps,i=Io.current,l=!1;if((n=0!=(64&t.effectTag))||(n=0!=(2&i)&&(null===e||null!==e.memoizedState)),n?(l=!0,t.effectTag&=-65):null!==e&&null===e.memoizedState||void 0===o.fallback||!0===o.unstable_avoidThisFallback||(i|=1),pa(Io,1&i),null===e){if(void 0!==o.fallback&&Pi(t),l){if(l=o.fallback,(o=Ns(null,a,0,null)).return=t,0==(2&t.mode))for(e=null!==t.memoizedState?t.child.child:t.child,o.child=e;null!==e;)e.return=o,e=e.sibling;return(r=Ns(l,a,r,null)).return=t,o.sibling=r,t.memoizedState=Hi,t.child=o,r}return a=o.children,t.memoizedState=null,t.child=wo(t,null,a,r)}if(null!==e.memoizedState){if(a=(e=e.child).sibling,l){if(o=o.fallback,(r=ws(e,e.pendingProps)).return=t,0==(2&t.mode)&&(l=null!==t.memoizedState?t.child.child:t.child)!==e.child)for(r.child=l;null!==l;)l.return=r,l=l.sibling;return(a=ws(a,o)).return=t,r.sibling=a,r.childExpirationTime=0,t.memoizedState=Hi,t.child=r,a}return r=Po(t,e.child,o.children,r),t.memoizedState=null,t.child=r}if(e=e.child,l){if(l=o.fallback,(o=Ns(null,a,0,null)).return=t,o.child=e,null!==e&&(e.return=o),0==(2&t.mode))for(e=null!==t.memoizedState?t.child.child:t.child,o.child=e;null!==e;)e.return=o,e=e.sibling;return(r=Ns(l,a,r,null)).return=t,o.sibling=r,r.effectTag|=2,o.childExpirationTime=0,t.memoizedState=Hi,t.child=o,r}return t.memoizedState=null,t.child=Po(t,e,o.children,r)}function Wi(e,t){e.expirationTime<t&&(e.expirationTime=t);var r=e.alternate;null!==r&&r.expirationTime<t&&(r.expirationTime=t),to(e.return,t)}function Yi(e,t,r,n,a,o){var i=e.memoizedState;null===i?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:n,tail:r,tailExpiration:0,tailMode:a,lastEffect:o}:(i.isBackwards=t,i.rendering=null,i.renderingStartTime=0,i.last=n,i.tail=r,i.tailExpiration=0,i.tailMode=a,i.lastEffect=o)}function Zi(e,t,r){var n=t.pendingProps,a=n.revealOrder,o=n.tail;if(Mi(e,t,n.children,r),0!=(2&(n=Io.current)))n=1&n|2,t.effectTag|=64;else{if(null!==e&&0!=(64&e.effectTag))e:for(e=t.child;null!==e;){if(13===e.tag)null!==e.memoizedState&&Wi(e,r);else if(19===e.tag)Wi(e,r);else if(null!==e.child){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;null===e.sibling;){if(null===e.return||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}n&=1}if(pa(Io,n),0==(2&t.mode))t.memoizedState=null;else switch(a){case"forwards":for(r=t.child,a=null;null!==r;)null!==(e=r.alternate)&&null===jo(e)&&(a=r),r=r.sibling;null===(r=a)?(a=t.child,t.child=null):(a=r.sibling,r.sibling=null),Yi(t,!1,a,r,o,t.lastEffect);break;case"backwards":for(r=null,a=t.child,t.child=null;null!==a;){if(null!==(e=a.alternate)&&null===jo(e)){t.child=a;break}e=a.sibling,a.sibling=r,r=a,a=e}Yi(t,!0,r,null,o,t.lastEffect);break;case"together":Yi(t,!1,null,null,void 0,t.lastEffect);break;default:t.memoizedState=null}return t.child}function Ki(e,t,r){null!==e&&(t.dependencies=e.dependencies);var n=t.expirationTime;if(0!==n&&is(n),t.childExpirationTime<r)return null;if(null!==e&&t.child!==e.child)throw Error(i(153));if(null!==t.child){for(r=ws(e=t.child,e.pendingProps),t.child=r,r.return=t;null!==e.sibling;)e=e.sibling,(r=r.sibling=ws(e,e.pendingProps)).return=t;r.sibling=null}return t.child}function Xi(e,t){switch(e.tailMode){case"hidden":t=e.tail;for(var r=null;null!==t;)null!==t.alternate&&(r=t),t=t.sibling;null===r?e.tail=null:r.sibling=null;break;case"collapsed":r=e.tail;for(var n=null;null!==r;)null!==r.alternate&&(n=r),r=r.sibling;null===n?t||null===e.tail?e.tail=null:e.tail.sibling=null:n.sibling=null}}function Qi(e,t,r){var n=t.pendingProps;switch(t.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return null;case 1:return ma(t.type)&&ga(),null;case 3:return Do(),sa(da),sa(ua),(r=t.stateNode).pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),null!==e&&null!==e.child||!ki(t)||(t.effectTag|=4),null;case 5:Ao(t),r=Mo(_o.current);var o=t.type;if(null!==e&&null!=t.stateNode)Vi(e,t,o,n,r),e.ref!==t.ref&&(t.effectTag|=128);else{if(!n){if(null===t.stateNode)throw Error(i(166));return null}if(e=Mo(No.current),ki(t)){n=t.stateNode,o=t.type;var l=t.memoizedProps;switch(n[Sr]=t,n[xr]=l,o){case"iframe":case"object":case"embed":Zt("load",n);break;case"video":case"audio":for(e=0;e<Qe.length;e++)Zt(Qe[e],n);break;case"source":Zt("error",n);break;case"img":case"image":case"link":Zt("error",n),Zt("load",n);break;case"form":Zt("reset",n),Zt("submit",n);break;case"details":Zt("toggle",n);break;case"input":Se(n,l),Zt("invalid",n),lr(r,"onChange");break;case"select":n._wrapperState={wasMultiple:!!l.multiple},Zt("invalid",n),lr(r,"onChange");break;case"textarea":Me(n,l),Zt("invalid",n),lr(r,"onChange")}for(var s in ar(o,l),e=null,l)if(l.hasOwnProperty(s)){var p=l[s];"children"===s?"string"==typeof p?n.textContent!==p&&(e=["children",p]):"number"==typeof p&&n.textContent!==""+p&&(e=["children",""+p]):x.hasOwnProperty(s)&&null!=p&&lr(r,s)}switch(o){case"input":Ce(n),we(n,l,!0);break;case"textarea":Ce(n),De(n);break;case"select":case"option":break;default:"function"==typeof l.onClick&&(n.onclick=sr)}r=e,t.updateQueue=r,null!==r&&(t.effectTag|=4)}else{switch(s=9===r.nodeType?r:r.ownerDocument,e===ir&&(e=Ie(o)),e===ir?"script"===o?((e=s.createElement("div")).innerHTML="<script><\/script>",e=e.removeChild(e.firstChild)):"string"==typeof n.is?e=s.createElement(o,{is:n.is}):(e=s.createElement(o),"select"===o&&(s=e,n.multiple?s.multiple=!0:n.size&&(s.size=n.size))):e=s.createElementNS(e,o),e[Sr]=t,e[xr]=n,Gi(e,t),t.stateNode=e,s=or(o,n),o){case"iframe":case"object":case"embed":Zt("load",e),p=n;break;case"video":case"audio":for(p=0;p<Qe.length;p++)Zt(Qe[p],e);p=n;break;case"source":Zt("error",e),p=n;break;case"img":case"image":case"link":Zt("error",e),Zt("load",e),p=n;break;case"form":Zt("reset",e),Zt("submit",e),p=n;break;case"details":Zt("toggle",e),p=n;break;case"input":Se(e,n),p=Oe(e,n),Zt("invalid",e),lr(r,"onChange");break;case"option":p=Ne(e,n);break;case"select":e._wrapperState={wasMultiple:!!n.multiple},p=a({},n,{value:void 0}),Zt("invalid",e),lr(r,"onChange");break;case"textarea":Me(e,n),p=_e(e,n),Zt("invalid",e),lr(r,"onChange");break;default:p=n}ar(o,p);var c=p;for(l in c)if(c.hasOwnProperty(l)){var u=c[l];"style"===l?rr(e,u):"dangerouslySetInnerHTML"===l?null!=(u=u?u.__html:void 0)&&Fe(e,u):"children"===l?"string"==typeof u?("textarea"!==o||""!==u)&&Ge(e,u):"number"==typeof u&&Ge(e,""+u):"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&"autoFocus"!==l&&(x.hasOwnProperty(l)?null!=u&&lr(r,l):null!=u&&q(e,l,u,s))}switch(o){case"input":Ce(e),we(e,n,!1);break;case"textarea":Ce(e),De(e);break;case"option":null!=n.value&&e.setAttribute("value",""+ve(n.value));break;case"select":e.multiple=!!n.multiple,null!=(r=n.value)?Te(e,!!n.multiple,r,!1):null!=n.defaultValue&&Te(e,!!n.multiple,n.defaultValue,!0);break;default:"function"==typeof p.onClick&&(e.onclick=sr)}gr(o,n)&&(t.effectTag|=4)}null!==t.ref&&(t.effectTag|=128)}return null;case 6:if(e&&null!=t.stateNode)Ui(0,t,e.memoizedProps,n);else{if("string"!=typeof n&&null===t.stateNode)throw Error(i(166));r=Mo(_o.current),Mo(No.current),ki(t)?(r=t.stateNode,n=t.memoizedProps,r[Sr]=t,r.nodeValue!==n&&(t.effectTag|=4)):((r=(9===r.nodeType?r:r.ownerDocument).createTextNode(n))[Sr]=t,t.stateNode=r)}return null;case 13:return sa(Io),n=t.memoizedState,0!=(64&t.effectTag)?(t.expirationTime=r,t):(r=null!==n,n=!1,null===e?void 0!==t.memoizedProps.fallback&&ki(t):(n=null!==(o=e.memoizedState),r||null===o||null!==(o=e.child.sibling)&&(null!==(l=t.firstEffect)?(t.firstEffect=o,o.nextEffect=l):(t.firstEffect=t.lastEffect=o,o.nextEffect=null),o.effectTag=8)),r&&!n&&0!=(2&t.mode)&&(null===e&&!0!==t.memoizedProps.unstable_avoidThisFallback||0!=(1&Io.current)?kl===Cl&&(kl=El):(kl!==Cl&&kl!==El||(kl=Ol),0!==Ll&&null!==xl&&(Ds(xl,wl),Rs(xl,Ll)))),(r||n)&&(t.effectTag|=4),null);case 4:return Do(),null;case 10:return eo(t),null;case 17:return ma(t.type)&&ga(),null;case 19:if(sa(Io),null===(n=t.memoizedState))return null;if(o=0!=(64&t.effectTag),null===(l=n.rendering)){if(o)Xi(n,!1);else if(kl!==Cl||null!==e&&0!=(64&e.effectTag))for(l=t.child;null!==l;){if(null!==(e=jo(l))){for(t.effectTag|=64,Xi(n,!1),null!==(o=e.updateQueue)&&(t.updateQueue=o,t.effectTag|=4),null===n.lastEffect&&(t.firstEffect=null),t.lastEffect=n.lastEffect,n=t.child;null!==n;)l=r,(o=n).effectTag&=2,o.nextEffect=null,o.firstEffect=null,o.lastEffect=null,null===(e=o.alternate)?(o.childExpirationTime=0,o.expirationTime=l,o.child=null,o.memoizedProps=null,o.memoizedState=null,o.updateQueue=null,o.dependencies=null):(o.childExpirationTime=e.childExpirationTime,o.expirationTime=e.expirationTime,o.child=e.child,o.memoizedProps=e.memoizedProps,o.memoizedState=e.memoizedState,o.updateQueue=e.updateQueue,l=e.dependencies,o.dependencies=null===l?null:{expirationTime:l.expirationTime,firstContext:l.firstContext,responders:l.responders}),n=n.sibling;return pa(Io,1&Io.current|2),t.child}l=l.sibling}}else{if(!o)if(null!==(e=jo(l))){if(t.effectTag|=64,o=!0,null!==(r=e.updateQueue)&&(t.updateQueue=r,t.effectTag|=4),Xi(n,!0),null===n.tail&&"hidden"===n.tailMode&&!l.alternate)return null!==(t=t.lastEffect=n.lastEffect)&&(t.nextEffect=null),null}else 2*Fa()-n.renderingStartTime>n.tailExpiration&&1<r&&(t.effectTag|=64,o=!0,Xi(n,!1),t.expirationTime=t.childExpirationTime=r-1);n.isBackwards?(l.sibling=t.child,t.child=l):(null!==(r=n.last)?r.sibling=l:t.child=l,n.last=l)}return null!==n.tail?(0===n.tailExpiration&&(n.tailExpiration=Fa()+500),r=n.tail,n.rendering=r,n.tail=r.sibling,n.lastEffect=t.lastEffect,n.renderingStartTime=Fa(),r.sibling=null,t=Io.current,pa(Io,o?1&t|2:1&t),r):null}throw Error(i(156,t.tag))}function qi(e){switch(e.tag){case 1:ma(e.type)&&ga();var t=e.effectTag;return 4096&t?(e.effectTag=-4097&t|64,e):null;case 3:if(Do(),sa(da),sa(ua),0!=(64&(t=e.effectTag)))throw Error(i(285));return e.effectTag=-4097&t|64,e;case 5:return Ao(e),null;case 13:return sa(Io),4096&(t=e.effectTag)?(e.effectTag=-4097&t|64,e):null;case 19:return sa(Io),null;case 4:return Do(),null;case 10:return eo(e),null;default:return null}}function $i(e,t){return{value:e,source:t,stack:fe(t)}}Gi=function(e,t){for(var r=t.child;null!==r;){if(5===r.tag||6===r.tag)e.appendChild(r.stateNode);else if(4!==r.tag&&null!==r.child){r.child.return=r,r=r.child;continue}if(r===t)break;for(;null===r.sibling;){if(null===r.return||r.return===t)return;r=r.return}r.sibling.return=r.return,r=r.sibling}},Vi=function(e,t,r,n,o){var i=e.memoizedProps;if(i!==n){var l,s,p=t.stateNode;switch(Mo(No.current),e=null,r){case"input":i=Oe(p,i),n=Oe(p,n),e=[];break;case"option":i=Ne(p,i),n=Ne(p,n),e=[];break;case"select":i=a({},i,{value:void 0}),n=a({},n,{value:void 0}),e=[];break;case"textarea":i=_e(p,i),n=_e(p,n),e=[];break;default:"function"!=typeof i.onClick&&"function"==typeof n.onClick&&(p.onclick=sr)}for(l in ar(r,n),r=null,i)if(!n.hasOwnProperty(l)&&i.hasOwnProperty(l)&&null!=i[l])if("style"===l)for(s in p=i[l])p.hasOwnProperty(s)&&(r||(r={}),r[s]="");else"dangerouslySetInnerHTML"!==l&&"children"!==l&&"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&"autoFocus"!==l&&(x.hasOwnProperty(l)?e||(e=[]):(e=e||[]).push(l,null));for(l in n){var c=n[l];if(p=null!=i?i[l]:void 0,n.hasOwnProperty(l)&&c!==p&&(null!=c||null!=p))if("style"===l)if(p){for(s in p)!p.hasOwnProperty(s)||c&&c.hasOwnProperty(s)||(r||(r={}),r[s]="");for(s in c)c.hasOwnProperty(s)&&p[s]!==c[s]&&(r||(r={}),r[s]=c[s])}else r||(e||(e=[]),e.push(l,r)),r=c;else"dangerouslySetInnerHTML"===l?(c=c?c.__html:void 0,p=p?p.__html:void 0,null!=c&&p!==c&&(e=e||[]).push(l,c)):"children"===l?p===c||"string"!=typeof c&&"number"!=typeof c||(e=e||[]).push(l,""+c):"suppressContentEditableWarning"!==l&&"suppressHydrationWarning"!==l&&(x.hasOwnProperty(l)?(null!=c&&lr(o,l),e||p===c||(e=[])):(e=e||[]).push(l,c))}r&&(e=e||[]).push("style",r),o=e,(t.updateQueue=o)&&(t.effectTag|=4)}},Ui=function(e,t,r,n){r!==n&&(t.effectTag|=4)};var Ji="function"==typeof WeakSet?WeakSet:Set;function el(e,t){var r=t.source,n=t.stack;null===n&&null!==r&&(n=fe(r)),null!==r&&ge(r.type),t=t.value,null!==e&&1===e.tag&&ge(e.type);try{console.error(t)}catch(e){setTimeout((function(){throw e}))}}function tl(e){var t=e.ref;if(null!==t)if("function"==typeof t)try{t(null)}catch(t){vs(e,t)}else t.current=null}function rl(e,t){switch(t.tag){case 0:case 11:case 15:case 22:return;case 1:if(256&t.effectTag&&null!==e){var r=e.memoizedProps,n=e.memoizedState;t=(e=t.stateNode).getSnapshotBeforeUpdate(t.elementType===t.type?r:Ka(t.type,r),n),e.__reactInternalSnapshotBeforeUpdate=t}return;case 3:case 5:case 6:case 4:case 17:return}throw Error(i(163))}function nl(e,t){if(null!==(t=null!==(t=t.updateQueue)?t.lastEffect:null)){var r=t=t.next;do{if((r.tag&e)===e){var n=r.destroy;r.destroy=void 0,void 0!==n&&n()}r=r.next}while(r!==t)}}function al(e,t){if(null!==(t=null!==(t=t.updateQueue)?t.lastEffect:null)){var r=t=t.next;do{if((r.tag&e)===e){var n=r.create;r.destroy=n()}r=r.next}while(r!==t)}}function ol(e,t,r){switch(r.tag){case 0:case 11:case 15:case 22:return void al(3,r);case 1:if(e=r.stateNode,4&r.effectTag)if(null===t)e.componentDidMount();else{var n=r.elementType===r.type?t.memoizedProps:Ka(r.type,t.memoizedProps);e.componentDidUpdate(n,t.memoizedState,e.__reactInternalSnapshotBeforeUpdate)}return void(null!==(t=r.updateQueue)&&uo(r,t,e));case 3:if(null!==(t=r.updateQueue)){if(e=null,null!==r.child)switch(r.child.tag){case 5:e=r.child.stateNode;break;case 1:e=r.child.stateNode}uo(r,t,e)}return;case 5:return e=r.stateNode,void(null===t&&4&r.effectTag&&gr(r.type,r.memoizedProps)&&e.focus());case 6:case 4:case 12:return;case 13:return void(null===r.memoizedState&&(r=r.alternate,null!==r&&(r=r.memoizedState,null!==r&&(r=r.dehydrated,null!==r&&It(r)))));case 19:case 17:case 20:case 21:return}throw Error(i(163))}function il(e,t,r){switch("function"==typeof Os&&Os(t),t.tag){case 0:case 11:case 14:case 15:case 22:if(null!==(e=t.updateQueue)&&null!==(e=e.lastEffect)){var n=e.next;Ua(97<r?97:r,(function(){var e=n;do{var r=e.destroy;if(void 0!==r){var a=t;try{r()}catch(e){vs(a,e)}}e=e.next}while(e!==n)}))}break;case 1:tl(t),"function"==typeof(r=t.stateNode).componentWillUnmount&&function(e,t){try{t.props=e.memoizedProps,t.state=e.memoizedState,t.componentWillUnmount()}catch(t){vs(e,t)}}(t,r);break;case 5:tl(t);break;case 4:cl(e,t,r)}}function ll(e){var t=e.alternate;e.return=null,e.child=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null,e.alternate=null,e.firstEffect=null,e.lastEffect=null,e.pendingProps=null,e.memoizedProps=null,e.stateNode=null,null!==t&&ll(t)}function sl(e){return 5===e.tag||3===e.tag||4===e.tag}function pl(e){e:{for(var t=e.return;null!==t;){if(sl(t)){var r=t;break e}t=t.return}throw Error(i(160))}switch(t=r.stateNode,r.tag){case 5:var n=!1;break;case 3:case 4:t=t.containerInfo,n=!0;break;default:throw Error(i(161))}16&r.effectTag&&(Ge(t,""),r.effectTag&=-17);e:t:for(r=e;;){for(;null===r.sibling;){if(null===r.return||sl(r.return)){r=null;break e}r=r.return}for(r.sibling.return=r.return,r=r.sibling;5!==r.tag&&6!==r.tag&&18!==r.tag;){if(2&r.effectTag)continue t;if(null===r.child||4===r.tag)continue t;r.child.return=r,r=r.child}if(!(2&r.effectTag)){r=r.stateNode;break e}}n?function e(t,r,n){var a=t.tag,o=5===a||6===a;if(o)t=o?t.stateNode:t.stateNode.instance,r?8===n.nodeType?n.parentNode.insertBefore(t,r):n.insertBefore(t,r):(8===n.nodeType?(r=n.parentNode).insertBefore(t,n):(r=n).appendChild(t),null!==(n=n._reactRootContainer)&&void 0!==n||null!==r.onclick||(r.onclick=sr));else if(4!==a&&null!==(t=t.child))for(e(t,r,n),t=t.sibling;null!==t;)e(t,r,n),t=t.sibling}(e,r,t):function e(t,r,n){var a=t.tag,o=5===a||6===a;if(o)t=o?t.stateNode:t.stateNode.instance,r?n.insertBefore(t,r):n.appendChild(t);else if(4!==a&&null!==(t=t.child))for(e(t,r,n),t=t.sibling;null!==t;)e(t,r,n),t=t.sibling}(e,r,t)}function cl(e,t,r){for(var n,a,o=t,l=!1;;){if(!l){l=o.return;e:for(;;){if(null===l)throw Error(i(160));switch(n=l.stateNode,l.tag){case 5:a=!1;break e;case 3:case 4:n=n.containerInfo,a=!0;break e}l=l.return}l=!0}if(5===o.tag||6===o.tag){e:for(var s=e,p=o,c=r,u=p;;)if(il(s,u,c),null!==u.child&&4!==u.tag)u.child.return=u,u=u.child;else{if(u===p)break e;for(;null===u.sibling;){if(null===u.return||u.return===p)break e;u=u.return}u.sibling.return=u.return,u=u.sibling}a?(s=n,p=o.stateNode,8===s.nodeType?s.parentNode.removeChild(p):s.removeChild(p)):n.removeChild(o.stateNode)}else if(4===o.tag){if(null!==o.child){n=o.stateNode.containerInfo,a=!0,o.child.return=o,o=o.child;continue}}else if(il(e,o,r),null!==o.child){o.child.return=o,o=o.child;continue}if(o===t)break;for(;null===o.sibling;){if(null===o.return||o.return===t)return;4===(o=o.return).tag&&(l=!1)}o.sibling.return=o.return,o=o.sibling}}function ul(e,t){switch(t.tag){case 0:case 11:case 14:case 15:case 22:return void nl(3,t);case 1:return;case 5:var r=t.stateNode;if(null!=r){var n=t.memoizedProps,a=null!==e?e.memoizedProps:n;e=t.type;var o=t.updateQueue;if(t.updateQueue=null,null!==o){for(r[xr]=n,"input"===e&&"radio"===n.type&&null!=n.name&&xe(r,n),or(e,a),t=or(e,n),a=0;a<o.length;a+=2){var l=o[a],s=o[a+1];"style"===l?rr(r,s):"dangerouslySetInnerHTML"===l?Fe(r,s):"children"===l?Ge(r,s):q(r,l,s,t)}switch(e){case"input":Pe(r,n);break;case"textarea":Le(r,n);break;case"select":t=r._wrapperState.wasMultiple,r._wrapperState.wasMultiple=!!n.multiple,null!=(e=n.value)?Te(r,!!n.multiple,e,!1):t!==!!n.multiple&&(null!=n.defaultValue?Te(r,!!n.multiple,n.defaultValue,!0):Te(r,!!n.multiple,n.multiple?[]:"",!1))}}}return;case 6:if(null===t.stateNode)throw Error(i(162));return void(t.stateNode.nodeValue=t.memoizedProps);case 3:return void((t=t.stateNode).hydrate&&(t.hydrate=!1,It(t.containerInfo)));case 12:return;case 13:if(r=t,null===t.memoizedState?n=!1:(n=!0,r=t.child,Rl=Fa()),null!==r)e:for(e=r;;){if(5===e.tag)o=e.stateNode,n?"function"==typeof(o=o.style).setProperty?o.setProperty("display","none","important"):o.display="none":(o=e.stateNode,a=null!=(a=e.memoizedProps.style)&&a.hasOwnProperty("display")?a.display:null,o.style.display=tr("display",a));else if(6===e.tag)e.stateNode.nodeValue=n?"":e.memoizedProps;else{if(13===e.tag&&null!==e.memoizedState&&null===e.memoizedState.dehydrated){(o=e.child.sibling).return=e,e=o;continue}if(null!==e.child){e.child.return=e,e=e.child;continue}}if(e===r)break;for(;null===e.sibling;){if(null===e.return||e.return===r)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}return void dl(t);case 19:return void dl(t);case 17:return}throw Error(i(163))}function dl(e){var t=e.updateQueue;if(null!==t){e.updateQueue=null;var r=e.stateNode;null===r&&(r=e.stateNode=new Ji),t.forEach((function(t){var n=Cs.bind(null,e,t);r.has(t)||(r.add(t),t.then(n,n))}))}}var hl="function"==typeof WeakMap?WeakMap:Map;function bl(e,t,r){(r=lo(r,null)).tag=3,r.payload={element:null};var n=t.value;return r.callback=function(){Il||(Il=!0,jl=n),el(e,t)},r}function ml(e,t,r){(r=lo(r,null)).tag=3;var n=e.type.getDerivedStateFromError;if("function"==typeof n){var a=t.value;r.payload=function(){return el(e,t),n(a)}}var o=e.stateNode;return null!==o&&"function"==typeof o.componentDidCatch&&(r.callback=function(){"function"!=typeof n&&(null===zl?zl=new Set([this]):zl.add(this),el(e,t));var r=t.stack;this.componentDidCatch(t.value,{componentStack:null!==r?r:""})}),r}var gl,fl=Math.ceil,vl=Q.ReactCurrentDispatcher,yl=Q.ReactCurrentOwner,Cl=0,El=3,Ol=4,Sl=0,xl=null,Pl=null,wl=0,kl=Cl,Nl=null,Tl=1073741823,_l=1073741823,Ml=null,Ll=0,Dl=!1,Rl=0,Al=null,Il=!1,jl=null,zl=null,Fl=!1,Gl=null,Vl=90,Ul=null,Hl=0,Bl=null,Wl=0;function Yl(){return 0!=(48&Sl)?1073741821-(Fa()/10|0):0!==Wl?Wl:Wl=1073741821-(Fa()/10|0)}function Zl(e,t,r){if(0==(2&(t=t.mode)))return 1073741823;var n=Ga();if(0==(4&t))return 99===n?1073741823:1073741822;if(0!=(16&Sl))return wl;if(null!==r)e=Za(e,0|r.timeoutMs||5e3,250);else switch(n){case 99:e=1073741823;break;case 98:e=Za(e,150,100);break;case 97:case 96:e=Za(e,5e3,250);break;case 95:e=2;break;default:throw Error(i(326))}return null!==xl&&e===wl&&--e,e}function Kl(e,t){if(50<Hl)throw Hl=0,Bl=null,Error(i(185));if(null!==(e=Xl(e,t))){var r=Ga();1073741823===t?0!=(8&Sl)&&0==(48&Sl)?Jl(e):(ql(e),0===Sl&&Wa()):ql(e),0==(4&Sl)||98!==r&&99!==r||(null===Ul?Ul=new Map([[e,t]]):(void 0===(r=Ul.get(e))||r>t)&&Ul.set(e,t))}}function Xl(e,t){e.expirationTime<t&&(e.expirationTime=t);var r=e.alternate;null!==r&&r.expirationTime<t&&(r.expirationTime=t);var n=e.return,a=null;if(null===n&&3===e.tag)a=e.stateNode;else for(;null!==n;){if(r=n.alternate,n.childExpirationTime<t&&(n.childExpirationTime=t),null!==r&&r.childExpirationTime<t&&(r.childExpirationTime=t),null===n.return&&3===n.tag){a=n.stateNode;break}n=n.return}return null!==a&&(xl===a&&(is(t),kl===Ol&&Ds(a,wl)),Rs(a,t)),a}function Ql(e){var t=e.lastExpiredTime;if(0!==t)return t;if(!Ls(e,t=e.firstPendingTime))return t;var r=e.lastPingedTime;return 2>=(e=r>(e=e.nextKnownPendingLevel)?r:e)&&t!==e?0:e}function ql(e){if(0!==e.lastExpiredTime)e.callbackExpirationTime=1073741823,e.callbackPriority=99,e.callbackNode=Ba(Jl.bind(null,e));else{var t=Ql(e),r=e.callbackNode;if(0===t)null!==r&&(e.callbackNode=null,e.callbackExpirationTime=0,e.callbackPriority=90);else{var n=Yl();if(1073741823===t?n=99:1===t||2===t?n=95:n=0>=(n=10*(1073741821-t)-10*(1073741821-n))?99:250>=n?98:5250>=n?97:95,null!==r){var a=e.callbackPriority;if(e.callbackExpirationTime===t&&a>=n)return;r!==La&&Sa(r)}e.callbackExpirationTime=t,e.callbackPriority=n,t=1073741823===t?Ba(Jl.bind(null,e)):Ha(n,$l.bind(null,e),{timeout:10*(1073741821-t)-Fa()}),e.callbackNode=t}}}function $l(e,t){if(Wl=0,t)return As(e,t=Yl()),ql(e),null;var r=Ql(e);if(0!==r){if(t=e.callbackNode,0!=(48&Sl))throw Error(i(327));if(ms(),e===xl&&r===wl||rs(e,r),null!==Pl){var n=Sl;Sl|=16;for(var a=as();;)try{ss();break}catch(t){ns(e,t)}if(Ja(),Sl=n,vl.current=a,1===kl)throw t=Nl,rs(e,r),Ds(e,r),ql(e),t;if(null===Pl)switch(a=e.finishedWork=e.current.alternate,e.finishedExpirationTime=r,n=kl,xl=null,n){case Cl:case 1:throw Error(i(345));case 2:As(e,2<r?2:r);break;case El:if(Ds(e,r),r===(n=e.lastSuspendedTime)&&(e.nextKnownPendingLevel=us(a)),1073741823===Tl&&10<(a=Rl+500-Fa())){if(Dl){var o=e.lastPingedTime;if(0===o||o>=r){e.lastPingedTime=r,rs(e,r);break}}if(0!==(o=Ql(e))&&o!==r)break;if(0!==n&&n!==r){e.lastPingedTime=n;break}e.timeoutHandle=vr(ds.bind(null,e),a);break}ds(e);break;case Ol:if(Ds(e,r),r===(n=e.lastSuspendedTime)&&(e.nextKnownPendingLevel=us(a)),Dl&&(0===(a=e.lastPingedTime)||a>=r)){e.lastPingedTime=r,rs(e,r);break}if(0!==(a=Ql(e))&&a!==r)break;if(0!==n&&n!==r){e.lastPingedTime=n;break}if(1073741823!==_l?n=10*(1073741821-_l)-Fa():1073741823===Tl?n=0:(n=10*(1073741821-Tl)-5e3,0>(n=(a=Fa())-n)&&(n=0),(r=10*(1073741821-r)-a)<(n=(120>n?120:480>n?480:1080>n?1080:1920>n?1920:3e3>n?3e3:4320>n?4320:1960*fl(n/1960))-n)&&(n=r)),10<n){e.timeoutHandle=vr(ds.bind(null,e),n);break}ds(e);break;case 5:if(1073741823!==Tl&&null!==Ml){o=Tl;var l=Ml;if(0>=(n=0|l.busyMinDurationMs)?n=0:(a=0|l.busyDelayMs,n=(o=Fa()-(10*(1073741821-o)-(0|l.timeoutMs||5e3)))<=a?0:a+n-o),10<n){Ds(e,r),e.timeoutHandle=vr(ds.bind(null,e),n);break}}ds(e);break;default:throw Error(i(329))}if(ql(e),e.callbackNode===t)return $l.bind(null,e)}}return null}function Jl(e){var t=e.lastExpiredTime;if(t=0!==t?t:1073741823,0!=(48&Sl))throw Error(i(327));if(ms(),e===xl&&t===wl||rs(e,t),null!==Pl){var r=Sl;Sl|=16;for(var n=as();;)try{ls();break}catch(t){ns(e,t)}if(Ja(),Sl=r,vl.current=n,1===kl)throw r=Nl,rs(e,t),Ds(e,t),ql(e),r;if(null!==Pl)throw Error(i(261));e.finishedWork=e.current.alternate,e.finishedExpirationTime=t,xl=null,ds(e),ql(e)}return null}function es(e,t){var r=Sl;Sl|=1;try{return e(t)}finally{0===(Sl=r)&&Wa()}}function ts(e,t){var r=Sl;Sl&=-2,Sl|=8;try{return e(t)}finally{0===(Sl=r)&&Wa()}}function rs(e,t){e.finishedWork=null,e.finishedExpirationTime=0;var r=e.timeoutHandle;if(-1!==r&&(e.timeoutHandle=-1,yr(r)),null!==Pl)for(r=Pl.return;null!==r;){var n=r;switch(n.tag){case 1:null!=(n=n.type.childContextTypes)&&ga();break;case 3:Do(),sa(da),sa(ua);break;case 5:Ao(n);break;case 4:Do();break;case 13:case 19:sa(Io);break;case 10:eo(n)}r=r.return}xl=e,Pl=ws(e.current,null),wl=t,kl=Cl,Nl=null,_l=Tl=1073741823,Ml=null,Ll=0,Dl=!1}function ns(e,t){for(;;){try{if(Ja(),Fo.current=gi,Wo)for(var r=Uo.memoizedState;null!==r;){var n=r.queue;null!==n&&(n.pending=null),r=r.next}if(Vo=0,Bo=Ho=Uo=null,Wo=!1,null===Pl||null===Pl.return)return kl=1,Nl=t,Pl=null;e:{var a=e,o=Pl.return,i=Pl,l=t;if(t=wl,i.effectTag|=2048,i.firstEffect=i.lastEffect=null,null!==l&&"object"==typeof l&&"function"==typeof l.then){var s=l;if(0==(2&i.mode)){var p=i.alternate;p?(i.updateQueue=p.updateQueue,i.memoizedState=p.memoizedState,i.expirationTime=p.expirationTime):(i.updateQueue=null,i.memoizedState=null)}var c=0!=(1&Io.current),u=o;do{var d;if(d=13===u.tag){var h=u.memoizedState;if(null!==h)d=null!==h.dehydrated;else{var b=u.memoizedProps;d=void 0!==b.fallback&&(!0!==b.unstable_avoidThisFallback||!c)}}if(d){var m=u.updateQueue;if(null===m){var g=new Set;g.add(s),u.updateQueue=g}else m.add(s);if(0==(2&u.mode)){if(u.effectTag|=64,i.effectTag&=-2981,1===i.tag)if(null===i.alternate)i.tag=17;else{var f=lo(1073741823,null);f.tag=2,so(i,f)}i.expirationTime=1073741823;break e}l=void 0,i=t;var v=a.pingCache;if(null===v?(v=a.pingCache=new hl,l=new Set,v.set(s,l)):void 0===(l=v.get(s))&&(l=new Set,v.set(s,l)),!l.has(i)){l.add(i);var y=ys.bind(null,a,s,i);s.then(y,y)}u.effectTag|=4096,u.expirationTime=t;break e}u=u.return}while(null!==u);l=Error((ge(i.type)||"A React component")+" suspended while rendering, but no fallback UI was specified.\n\nAdd a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display."+fe(i))}5!==kl&&(kl=2),l=$i(l,i),u=o;do{switch(u.tag){case 3:s=l,u.effectTag|=4096,u.expirationTime=t,po(u,bl(u,s,t));break e;case 1:s=l;var C=u.type,E=u.stateNode;if(0==(64&u.effectTag)&&("function"==typeof C.getDerivedStateFromError||null!==E&&"function"==typeof E.componentDidCatch&&(null===zl||!zl.has(E)))){u.effectTag|=4096,u.expirationTime=t,po(u,ml(u,s,t));break e}}u=u.return}while(null!==u)}Pl=cs(Pl)}catch(e){t=e;continue}break}}function as(){var e=vl.current;return vl.current=gi,null===e?gi:e}function os(e,t){e<Tl&&2<e&&(Tl=e),null!==t&&e<_l&&2<e&&(_l=e,Ml=t)}function is(e){e>Ll&&(Ll=e)}function ls(){for(;null!==Pl;)Pl=ps(Pl)}function ss(){for(;null!==Pl&&!Da();)Pl=ps(Pl)}function ps(e){var t=gl(e.alternate,e,wl);return e.memoizedProps=e.pendingProps,null===t&&(t=cs(e)),yl.current=null,t}function cs(e){Pl=e;do{var t=Pl.alternate;if(e=Pl.return,0==(2048&Pl.effectTag)){if(t=Qi(t,Pl,wl),1===wl||1!==Pl.childExpirationTime){for(var r=0,n=Pl.child;null!==n;){var a=n.expirationTime,o=n.childExpirationTime;a>r&&(r=a),o>r&&(r=o),n=n.sibling}Pl.childExpirationTime=r}if(null!==t)return t;null!==e&&0==(2048&e.effectTag)&&(null===e.firstEffect&&(e.firstEffect=Pl.firstEffect),null!==Pl.lastEffect&&(null!==e.lastEffect&&(e.lastEffect.nextEffect=Pl.firstEffect),e.lastEffect=Pl.lastEffect),1<Pl.effectTag&&(null!==e.lastEffect?e.lastEffect.nextEffect=Pl:e.firstEffect=Pl,e.lastEffect=Pl))}else{if(null!==(t=qi(Pl)))return t.effectTag&=2047,t;null!==e&&(e.firstEffect=e.lastEffect=null,e.effectTag|=2048)}if(null!==(t=Pl.sibling))return t;Pl=e}while(null!==Pl);return kl===Cl&&(kl=5),null}function us(e){var t=e.expirationTime;return t>(e=e.childExpirationTime)?t:e}function ds(e){var t=Ga();return Ua(99,hs.bind(null,e,t)),null}function hs(e,t){do{ms()}while(null!==Gl);if(0!=(48&Sl))throw Error(i(327));var r=e.finishedWork,n=e.finishedExpirationTime;if(null===r)return null;if(e.finishedWork=null,e.finishedExpirationTime=0,r===e.current)throw Error(i(177));e.callbackNode=null,e.callbackExpirationTime=0,e.callbackPriority=90,e.nextKnownPendingLevel=0;var a=us(r);if(e.firstPendingTime=a,n<=e.lastSuspendedTime?e.firstSuspendedTime=e.lastSuspendedTime=e.nextKnownPendingLevel=0:n<=e.firstSuspendedTime&&(e.firstSuspendedTime=n-1),n<=e.lastPingedTime&&(e.lastPingedTime=0),n<=e.lastExpiredTime&&(e.lastExpiredTime=0),e===xl&&(Pl=xl=null,wl=0),1<r.effectTag?null!==r.lastEffect?(r.lastEffect.nextEffect=r,a=r.firstEffect):a=r:a=r.firstEffect,null!==a){var o=Sl;Sl|=32,yl.current=null,br=Yt;var l=dr();if(hr(l)){if("selectionStart"in l)var s={start:l.selectionStart,end:l.selectionEnd};else e:{var p=(s=(s=l.ownerDocument)&&s.defaultView||window).getSelection&&s.getSelection();if(p&&0!==p.rangeCount){s=p.anchorNode;var c=p.anchorOffset,u=p.focusNode;p=p.focusOffset;try{s.nodeType,u.nodeType}catch(e){s=null;break e}var d=0,h=-1,b=-1,m=0,g=0,f=l,v=null;t:for(;;){for(var y;f!==s||0!==c&&3!==f.nodeType||(h=d+c),f!==u||0!==p&&3!==f.nodeType||(b=d+p),3===f.nodeType&&(d+=f.nodeValue.length),null!==(y=f.firstChild);)v=f,f=y;for(;;){if(f===l)break t;if(v===s&&++m===c&&(h=d),v===u&&++g===p&&(b=d),null!==(y=f.nextSibling))break;v=(f=v).parentNode}f=y}s=-1===h||-1===b?null:{start:h,end:b}}else s=null}s=s||{start:0,end:0}}else s=null;mr={activeElementDetached:null,focusedElem:l,selectionRange:s},Yt=!1,Al=a;do{try{bs()}catch(e){if(null===Al)throw Error(i(330));vs(Al,e),Al=Al.nextEffect}}while(null!==Al);Al=a;do{try{for(l=e,s=t;null!==Al;){var C=Al.effectTag;if(16&C&&Ge(Al.stateNode,""),128&C){var E=Al.alternate;if(null!==E){var O=E.ref;null!==O&&("function"==typeof O?O(null):O.current=null)}}switch(1038&C){case 2:pl(Al),Al.effectTag&=-3;break;case 6:pl(Al),Al.effectTag&=-3,ul(Al.alternate,Al);break;case 1024:Al.effectTag&=-1025;break;case 1028:Al.effectTag&=-1025,ul(Al.alternate,Al);break;case 4:ul(Al.alternate,Al);break;case 8:cl(l,c=Al,s),ll(c)}Al=Al.nextEffect}}catch(e){if(null===Al)throw Error(i(330));vs(Al,e),Al=Al.nextEffect}}while(null!==Al);if(O=mr,E=dr(),C=O.focusedElem,s=O.selectionRange,E!==C&&C&&C.ownerDocument&&function e(t,r){return!(!t||!r)&&(t===r||(!t||3!==t.nodeType)&&(r&&3===r.nodeType?e(t,r.parentNode):"contains"in t?t.contains(r):!!t.compareDocumentPosition&&!!(16&t.compareDocumentPosition(r))))}(C.ownerDocument.documentElement,C)){null!==s&&hr(C)&&(E=s.start,void 0===(O=s.end)&&(O=E),"selectionStart"in C?(C.selectionStart=E,C.selectionEnd=Math.min(O,C.value.length)):(O=(E=C.ownerDocument||document)&&E.defaultView||window).getSelection&&(O=O.getSelection(),c=C.textContent.length,l=Math.min(s.start,c),s=void 0===s.end?l:Math.min(s.end,c),!O.extend&&l>s&&(c=s,s=l,l=c),c=ur(C,l),u=ur(C,s),c&&u&&(1!==O.rangeCount||O.anchorNode!==c.node||O.anchorOffset!==c.offset||O.focusNode!==u.node||O.focusOffset!==u.offset)&&((E=E.createRange()).setStart(c.node,c.offset),O.removeAllRanges(),l>s?(O.addRange(E),O.extend(u.node,u.offset)):(E.setEnd(u.node,u.offset),O.addRange(E))))),E=[];for(O=C;O=O.parentNode;)1===O.nodeType&&E.push({element:O,left:O.scrollLeft,top:O.scrollTop});for("function"==typeof C.focus&&C.focus(),C=0;C<E.length;C++)(O=E[C]).element.scrollLeft=O.left,O.element.scrollTop=O.top}Yt=!!br,mr=br=null,e.current=r,Al=a;do{try{for(C=e;null!==Al;){var S=Al.effectTag;if(36&S&&ol(C,Al.alternate,Al),128&S){E=void 0;var x=Al.ref;if(null!==x){var P=Al.stateNode;switch(Al.tag){case 5:E=P;break;default:E=P}"function"==typeof x?x(E):x.current=E}}Al=Al.nextEffect}}catch(e){if(null===Al)throw Error(i(330));vs(Al,e),Al=Al.nextEffect}}while(null!==Al);Al=null,Ra(),Sl=o}else e.current=r;if(Fl)Fl=!1,Gl=e,Vl=t;else for(Al=a;null!==Al;)t=Al.nextEffect,Al.nextEffect=null,Al=t;if(0===(t=e.firstPendingTime)&&(zl=null),1073741823===t?e===Bl?Hl++:(Hl=0,Bl=e):Hl=0,"function"==typeof Es&&Es(r.stateNode,n),ql(e),Il)throw Il=!1,e=jl,jl=null,e;return 0!=(8&Sl)||Wa(),null}function bs(){for(;null!==Al;){var e=Al.effectTag;0!=(256&e)&&rl(Al.alternate,Al),0==(512&e)||Fl||(Fl=!0,Ha(97,(function(){return ms(),null}))),Al=Al.nextEffect}}function ms(){if(90!==Vl){var e=97<Vl?97:Vl;return Vl=90,Ua(e,gs)}}function gs(){if(null===Gl)return!1;var e=Gl;if(Gl=null,0!=(48&Sl))throw Error(i(331));var t=Sl;for(Sl|=32,e=e.current.firstEffect;null!==e;){try{var r=e;if(0!=(512&r.effectTag))switch(r.tag){case 0:case 11:case 15:case 22:nl(5,r),al(5,r)}}catch(t){if(null===e)throw Error(i(330));vs(e,t)}r=e.nextEffect,e.nextEffect=null,e=r}return Sl=t,Wa(),!0}function fs(e,t,r){so(e,t=bl(e,t=$i(r,t),1073741823)),null!==(e=Xl(e,1073741823))&&ql(e)}function vs(e,t){if(3===e.tag)fs(e,e,t);else for(var r=e.return;null!==r;){if(3===r.tag){fs(r,e,t);break}if(1===r.tag){var n=r.stateNode;if("function"==typeof r.type.getDerivedStateFromError||"function"==typeof n.componentDidCatch&&(null===zl||!zl.has(n))){so(r,e=ml(r,e=$i(t,e),1073741823)),null!==(r=Xl(r,1073741823))&&ql(r);break}}r=r.return}}function ys(e,t,r){var n=e.pingCache;null!==n&&n.delete(t),xl===e&&wl===r?kl===Ol||kl===El&&1073741823===Tl&&Fa()-Rl<500?rs(e,wl):Dl=!0:Ls(e,r)&&(0!==(t=e.lastPingedTime)&&t<r||(e.lastPingedTime=r,ql(e)))}function Cs(e,t){var r=e.stateNode;null!==r&&r.delete(t),0===(t=0)&&(t=Zl(t=Yl(),e,null)),null!==(e=Xl(e,t))&&ql(e)}gl=function(e,t,r){var n=t.expirationTime;if(null!==e){var a=t.pendingProps;if(e.memoizedProps!==a||da.current)_i=!0;else{if(n<r){switch(_i=!1,t.tag){case 3:Fi(t),Ni();break;case 5:if(Ro(t),4&t.mode&&1!==r&&a.hidden)return t.expirationTime=t.childExpirationTime=1,null;break;case 1:ma(t.type)&&ya(t);break;case 4:Lo(t,t.stateNode.containerInfo);break;case 10:n=t.memoizedProps.value,a=t.type._context,pa(Xa,a._currentValue),a._currentValue=n;break;case 13:if(null!==t.memoizedState)return 0!==(n=t.child.childExpirationTime)&&n>=r?Bi(e,t,r):(pa(Io,1&Io.current),null!==(t=Ki(e,t,r))?t.sibling:null);pa(Io,1&Io.current);break;case 19:if(n=t.childExpirationTime>=r,0!=(64&e.effectTag)){if(n)return Zi(e,t,r);t.effectTag|=64}if(null!==(a=t.memoizedState)&&(a.rendering=null,a.tail=null),pa(Io,Io.current),!n)return null}return Ki(e,t,r)}_i=!1}}else _i=!1;switch(t.expirationTime=0,t.tag){case 2:if(n=t.type,null!==e&&(e.alternate=null,t.alternate=null,t.effectTag|=2),e=t.pendingProps,a=ba(t,ua.current),ro(t,r),a=Ko(null,t,n,e,a,r),t.effectTag|=1,"object"==typeof a&&null!==a&&"function"==typeof a.render&&void 0===a.$$typeof){if(t.tag=1,t.memoizedState=null,t.updateQueue=null,ma(n)){var o=!0;ya(t)}else o=!1;t.memoizedState=null!==a.state&&void 0!==a.state?a.state:null,oo(t);var l=n.getDerivedStateFromProps;"function"==typeof l&&mo(t,n,l,e),a.updater=go,t.stateNode=a,a._reactInternalFiber=t,Co(t,n,e,r),t=zi(null,t,n,!0,o,r)}else t.tag=0,Mi(null,t,a,r),t=t.child;return t;case 16:e:{if(a=t.elementType,null!==e&&(e.alternate=null,t.alternate=null,t.effectTag|=2),e=t.pendingProps,function(e){if(-1===e._status){e._status=0;var t=e._ctor;t=t(),e._result=t,t.then((function(t){0===e._status&&(t=t.default,e._status=1,e._result=t)}),(function(t){0===e._status&&(e._status=2,e._result=t)}))}}(a),1!==a._status)throw a._result;switch(a=a._result,t.type=a,o=t.tag=function(e){if("function"==typeof e)return Ps(e)?1:0;if(null!=e){if((e=e.$$typeof)===se)return 11;if(e===ue)return 14}return 2}(a),e=Ka(a,e),o){case 0:t=Ii(null,t,a,e,r);break e;case 1:t=ji(null,t,a,e,r);break e;case 11:t=Li(null,t,a,e,r);break e;case 14:t=Di(null,t,a,Ka(a.type,e),n,r);break e}throw Error(i(306,a,""))}return t;case 0:return n=t.type,a=t.pendingProps,Ii(e,t,n,a=t.elementType===n?a:Ka(n,a),r);case 1:return n=t.type,a=t.pendingProps,ji(e,t,n,a=t.elementType===n?a:Ka(n,a),r);case 3:if(Fi(t),n=t.updateQueue,null===e||null===n)throw Error(i(282));if(n=t.pendingProps,a=null!==(a=t.memoizedState)?a.element:null,io(e,t),co(t,n,null,r),(n=t.memoizedState.element)===a)Ni(),t=Ki(e,t,r);else{if((a=t.stateNode.hydrate)&&(Ei=Cr(t.stateNode.containerInfo.firstChild),Ci=t,a=Oi=!0),a)for(r=wo(t,null,n,r),t.child=r;r;)r.effectTag=-3&r.effectTag|1024,r=r.sibling;else Mi(e,t,n,r),Ni();t=t.child}return t;case 5:return Ro(t),null===e&&Pi(t),n=t.type,a=t.pendingProps,o=null!==e?e.memoizedProps:null,l=a.children,fr(n,a)?l=null:null!==o&&fr(n,o)&&(t.effectTag|=16),Ai(e,t),4&t.mode&&1!==r&&a.hidden?(t.expirationTime=t.childExpirationTime=1,t=null):(Mi(e,t,l,r),t=t.child),t;case 6:return null===e&&Pi(t),null;case 13:return Bi(e,t,r);case 4:return Lo(t,t.stateNode.containerInfo),n=t.pendingProps,null===e?t.child=Po(t,null,n,r):Mi(e,t,n,r),t.child;case 11:return n=t.type,a=t.pendingProps,Li(e,t,n,a=t.elementType===n?a:Ka(n,a),r);case 7:return Mi(e,t,t.pendingProps,r),t.child;case 8:case 12:return Mi(e,t,t.pendingProps.children,r),t.child;case 10:e:{n=t.type._context,a=t.pendingProps,l=t.memoizedProps,o=a.value;var s=t.type._context;if(pa(Xa,s._currentValue),s._currentValue=o,null!==l)if(s=l.value,0===(o=jn(s,o)?0:0|("function"==typeof n._calculateChangedBits?n._calculateChangedBits(s,o):1073741823))){if(l.children===a.children&&!da.current){t=Ki(e,t,r);break e}}else for(null!==(s=t.child)&&(s.return=t);null!==s;){var p=s.dependencies;if(null!==p){l=s.child;for(var c=p.firstContext;null!==c;){if(c.context===n&&0!=(c.observedBits&o)){1===s.tag&&((c=lo(r,null)).tag=2,so(s,c)),s.expirationTime<r&&(s.expirationTime=r),null!==(c=s.alternate)&&c.expirationTime<r&&(c.expirationTime=r),to(s.return,r),p.expirationTime<r&&(p.expirationTime=r);break}c=c.next}}else l=10===s.tag&&s.type===t.type?null:s.child;if(null!==l)l.return=s;else for(l=s;null!==l;){if(l===t){l=null;break}if(null!==(s=l.sibling)){s.return=l.return,l=s;break}l=l.return}s=l}Mi(e,t,a.children,r),t=t.child}return t;case 9:return a=t.type,n=(o=t.pendingProps).children,ro(t,r),n=n(a=no(a,o.unstable_observedBits)),t.effectTag|=1,Mi(e,t,n,r),t.child;case 14:return o=Ka(a=t.type,t.pendingProps),Di(e,t,a,o=Ka(a.type,o),n,r);case 15:return Ri(e,t,t.type,t.pendingProps,n,r);case 17:return n=t.type,a=t.pendingProps,a=t.elementType===n?a:Ka(n,a),null!==e&&(e.alternate=null,t.alternate=null,t.effectTag|=2),t.tag=1,ma(n)?(e=!0,ya(t)):e=!1,ro(t,r),vo(t,n,a),Co(t,n,a,r),zi(null,t,n,!0,e,r);case 19:return Zi(e,t,r)}throw Error(i(156,t.tag))};var Es=null,Os=null;function Ss(e,t,r,n){this.tag=e,this.key=r,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=n,this.effectTag=0,this.lastEffect=this.firstEffect=this.nextEffect=null,this.childExpirationTime=this.expirationTime=0,this.alternate=null}function xs(e,t,r,n){return new Ss(e,t,r,n)}function Ps(e){return!(!(e=e.prototype)||!e.isReactComponent)}function ws(e,t){var r=e.alternate;return null===r?((r=xs(e.tag,t,e.key,e.mode)).elementType=e.elementType,r.type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=t,r.effectTag=0,r.nextEffect=null,r.firstEffect=null,r.lastEffect=null),r.childExpirationTime=e.childExpirationTime,r.expirationTime=e.expirationTime,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,t=e.dependencies,r.dependencies=null===t?null:{expirationTime:t.expirationTime,firstContext:t.firstContext,responders:t.responders},r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r}function ks(e,t,r,n,a,o){var l=2;if(n=e,"function"==typeof e)Ps(e)&&(l=1);else if("string"==typeof e)l=5;else e:switch(e){case re:return Ns(r.children,a,o,t);case le:l=8,a|=7;break;case ne:l=8,a|=1;break;case ae:return(e=xs(12,r,t,8|a)).elementType=ae,e.type=ae,e.expirationTime=o,e;case pe:return(e=xs(13,r,t,a)).type=pe,e.elementType=pe,e.expirationTime=o,e;case ce:return(e=xs(19,r,t,a)).elementType=ce,e.expirationTime=o,e;default:if("object"==typeof e&&null!==e)switch(e.$$typeof){case oe:l=10;break e;case ie:l=9;break e;case se:l=11;break e;case ue:l=14;break e;case de:l=16,n=null;break e;case he:l=22;break e}throw Error(i(130,null==e?e:typeof e,""))}return(t=xs(l,r,t,a)).elementType=e,t.type=n,t.expirationTime=o,t}function Ns(e,t,r,n){return(e=xs(7,e,n,t)).expirationTime=r,e}function Ts(e,t,r){return(e=xs(6,e,null,t)).expirationTime=r,e}function _s(e,t,r){return(t=xs(4,null!==e.children?e.children:[],e.key,t)).expirationTime=r,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Ms(e,t,r){this.tag=t,this.current=null,this.containerInfo=e,this.pingCache=this.pendingChildren=null,this.finishedExpirationTime=0,this.finishedWork=null,this.timeoutHandle=-1,this.pendingContext=this.context=null,this.hydrate=r,this.callbackNode=null,this.callbackPriority=90,this.lastExpiredTime=this.lastPingedTime=this.nextKnownPendingLevel=this.lastSuspendedTime=this.firstSuspendedTime=this.firstPendingTime=0}function Ls(e,t){var r=e.firstSuspendedTime;return e=e.lastSuspendedTime,0!==r&&r>=t&&e<=t}function Ds(e,t){var r=e.firstSuspendedTime,n=e.lastSuspendedTime;r<t&&(e.firstSuspendedTime=t),(n>t||0===r)&&(e.lastSuspendedTime=t),t<=e.lastPingedTime&&(e.lastPingedTime=0),t<=e.lastExpiredTime&&(e.lastExpiredTime=0)}function Rs(e,t){t>e.firstPendingTime&&(e.firstPendingTime=t);var r=e.firstSuspendedTime;0!==r&&(t>=r?e.firstSuspendedTime=e.lastSuspendedTime=e.nextKnownPendingLevel=0:t>=e.lastSuspendedTime&&(e.lastSuspendedTime=t+1),t>e.nextKnownPendingLevel&&(e.nextKnownPendingLevel=t))}function As(e,t){var r=e.lastExpiredTime;(0===r||r>t)&&(e.lastExpiredTime=t)}function Is(e,t,r,n){var a=t.current,o=Yl(),l=ho.suspense;o=Zl(o,a,l);e:if(r){t:{if(Je(r=r._reactInternalFiber)!==r||1!==r.tag)throw Error(i(170));var s=r;do{switch(s.tag){case 3:s=s.stateNode.context;break t;case 1:if(ma(s.type)){s=s.stateNode.__reactInternalMemoizedMergedChildContext;break t}}s=s.return}while(null!==s);throw Error(i(171))}if(1===r.tag){var p=r.type;if(ma(p)){r=va(r,p,s);break e}}r=s}else r=ca;return null===t.context?t.context=r:t.pendingContext=r,(t=lo(o,l)).payload={element:e},null!==(n=void 0===n?null:n)&&(t.callback=n),so(a,t),Kl(a,o),o}function js(e){if(!(e=e.current).child)return null;switch(e.child.tag){case 5:default:return e.child.stateNode}}function zs(e,t){null!==(e=e.memoizedState)&&null!==e.dehydrated&&e.retryTime<t&&(e.retryTime=t)}function Fs(e,t){zs(e,t),(e=e.alternate)&&zs(e,t)}function Gs(e,t,r){var n=new Ms(e,t,r=null!=r&&!0===r.hydrate),a=xs(3,null,null,2===t?7:1===t?3:0);n.current=a,a.stateNode=n,oo(a),e[Pr]=n.current,r&&0!==t&&function(e,t){var r=$e(t);wt.forEach((function(e){bt(e,t,r)})),kt.forEach((function(e){bt(e,t,r)}))}(0,9===e.nodeType?e:e.ownerDocument),this._internalRoot=n}function Vs(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType&&(8!==e.nodeType||" react-mount-point-unstable "!==e.nodeValue))}function Us(e,t,r,n,a){var o=r._reactRootContainer;if(o){var i=o._internalRoot;if("function"==typeof a){var l=a;a=function(){var e=js(i);l.call(e)}}Is(t,i,e,a)}else{if(o=r._reactRootContainer=function(e,t){if(t||(t=!(!(t=e?9===e.nodeType?e.documentElement:e.firstChild:null)||1!==t.nodeType||!t.hasAttribute("data-reactroot"))),!t)for(var r;r=e.lastChild;)e.removeChild(r);return new Gs(e,0,t?{hydrate:!0}:void 0)}(r,n),i=o._internalRoot,"function"==typeof a){var s=a;a=function(){var e=js(i);s.call(e)}}ts((function(){Is(t,i,e,a)}))}return js(i)}function Hs(e,t,r){var n=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:te,key:null==n?null:""+n,children:e,containerInfo:t,implementation:r}}function Bs(e,t){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!Vs(t))throw Error(i(200));return Hs(e,t,null,r)}Gs.prototype.render=function(e){Is(e,this._internalRoot,null,null)},Gs.prototype.unmount=function(){var e=this._internalRoot,t=e.containerInfo;Is(null,e,null,(function(){t[Pr]=null}))},mt=function(e){if(13===e.tag){var t=Za(Yl(),150,100);Kl(e,t),Fs(e,t)}},gt=function(e){13===e.tag&&(Kl(e,3),Fs(e,3))},ft=function(e){if(13===e.tag){var t=Yl();Kl(e,t=Zl(t,e,null)),Fs(e,t)}},N=function(e,t,r){switch(t){case"input":if(Pe(e,r),t=r.name,"radio"===r.type&&null!=t){for(r=e;r.parentNode;)r=r.parentNode;for(r=r.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<r.length;t++){var n=r[t];if(n!==e&&n.form===e.form){var a=Tr(n);if(!a)throw Error(i(90));Ee(n),Pe(n,a)}}}break;case"textarea":Le(e,r);break;case"select":null!=(t=r.value)&&Te(e,!!r.multiple,t,!1)}},R=es,A=function(e,t,r,n,a){var o=Sl;Sl|=4;try{return Ua(98,e.bind(null,t,r,n,a))}finally{0===(Sl=o)&&Wa()}},I=function(){0==(49&Sl)&&(function(){if(null!==Ul){var e=Ul;Ul=null,e.forEach((function(e,t){As(t,e),ql(t)})),Wa()}}(),ms())},j=function(e,t){var r=Sl;Sl|=2;try{return e(t)}finally{0===(Sl=r)&&Wa()}};var Ws,Ys,Zs={Events:[kr,Nr,Tr,w,S,Ir,function(e){at(e,Ar)},L,D,qt,lt,ms,{current:!1}]};Ys=(Ws={findFiberByHostInstance:wr,bundleType:0,version:"16.13.1",rendererPackageName:"react-dom"}).findFiberByHostInstance,function(e){if("undefined"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)return!1;var t=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(t.isDisabled||!t.supportsFiber)return!0;try{var r=t.inject(e);Es=function(e){try{t.onCommitFiberRoot(r,e,void 0,64==(64&e.current.effectTag))}catch(e){}},Os=function(e){try{t.onCommitFiberUnmount(r,e)}catch(e){}}}catch(e){}}(a({},Ws,{overrideHookState:null,overrideProps:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:Q.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return null===(e=rt(e))?null:e.stateNode},findFiberByHostInstance:function(e){return Ys?Ys(e):null},findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null})),t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Zs,t.createPortal=Bs,t.findDOMNode=function(e){if(null==e)return null;if(1===e.nodeType)return e;var t=e._reactInternalFiber;if(void 0===t){if("function"==typeof e.render)throw Error(i(188));throw Error(i(268,Object.keys(e)))}return e=null===(e=rt(t))?null:e.stateNode},t.flushSync=function(e,t){if(0!=(48&Sl))throw Error(i(187));var r=Sl;Sl|=1;try{return Ua(99,e.bind(null,t))}finally{Sl=r,Wa()}},t.hydrate=function(e,t,r){if(!Vs(t))throw Error(i(200));return Us(null,e,t,!0,r)},t.render=function(e,t,r){if(!Vs(t))throw Error(i(200));return Us(null,e,t,!1,r)},t.unmountComponentAtNode=function(e){if(!Vs(e))throw Error(i(40));return!!e._reactRootContainer&&(ts((function(){Us(null,null,e,!1,(function(){e._reactRootContainer=null,e[Pr]=null}))})),!0)},t.unstable_batchedUpdates=es,t.unstable_createPortal=function(e,t){return Bs(e,t,2<arguments.length&&void 0!==arguments[2]?arguments[2]:null)},t.unstable_renderSubtreeIntoContainer=function(e,t,r,n){if(!Vs(r))throw Error(i(200));if(null==e||void 0===e._reactInternalFiber)throw Error(i(38));return Us(e,t,r,!1,n)},t.version="16.13.1"},function(e,t,r){"use strict";e.exports=r(21)},function(e,t,r){"use strict"; /** @license React v0.19.1 * scheduler.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var n,a,o,i,l;if("undefined"==typeof window||"function"!=typeof MessageChannel){var s=null,p=null,c=function(){if(null!==s)try{var e=t.unstable_now();s(!0,e),s=null}catch(e){throw setTimeout(c,0),e}},u=Date.now();t.unstable_now=function(){return Date.now()-u},n=function(e){null!==s?setTimeout(n,0,e):(s=e,setTimeout(c,0))},a=function(e,t){p=setTimeout(e,t)},o=function(){clearTimeout(p)},i=function(){return!1},l=t.unstable_forceFrameRate=function(){}}else{var d=window.performance,h=window.Date,b=window.setTimeout,m=window.clearTimeout;if("undefined"!=typeof console){var g=window.cancelAnimationFrame;"function"!=typeof window.requestAnimationFrame&&console.error("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"),"function"!=typeof g&&console.error("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills")}if("object"==typeof d&&"function"==typeof d.now)t.unstable_now=function(){return d.now()};else{var f=h.now();t.unstable_now=function(){return h.now()-f}}var v=!1,y=null,C=-1,E=5,O=0;i=function(){return t.unstable_now()>=O},l=function(){},t.unstable_forceFrameRate=function(e){0>e||125<e?console.error("forceFrameRate takes a positive int between 0 and 125, forcing framerates higher than 125 fps is not unsupported"):E=0<e?Math.floor(1e3/e):5};var S=new MessageChannel,x=S.port2;S.port1.onmessage=function(){if(null!==y){var e=t.unstable_now();O=e+E;try{y(!0,e)?x.postMessage(null):(v=!1,y=null)}catch(e){throw x.postMessage(null),e}}else v=!1},n=function(e){y=e,v||(v=!0,x.postMessage(null))},a=function(e,r){C=b((function(){e(t.unstable_now())}),r)},o=function(){m(C),C=-1}}function P(e,t){var r=e.length;e.push(t);e:for(;;){var n=r-1>>>1,a=e[n];if(!(void 0!==a&&0<N(a,t)))break e;e[n]=t,e[r]=a,r=n}}function w(e){return void 0===(e=e[0])?null:e}function k(e){var t=e[0];if(void 0!==t){var r=e.pop();if(r!==t){e[0]=r;e:for(var n=0,a=e.length;n<a;){var o=2*(n+1)-1,i=e[o],l=o+1,s=e[l];if(void 0!==i&&0>N(i,r))void 0!==s&&0>N(s,i)?(e[n]=s,e[l]=r,n=l):(e[n]=i,e[o]=r,n=o);else{if(!(void 0!==s&&0>N(s,r)))break e;e[n]=s,e[l]=r,n=l}}}return t}return null}function N(e,t){var r=e.sortIndex-t.sortIndex;return 0!==r?r:e.id-t.id}var T=[],_=[],M=1,L=null,D=3,R=!1,A=!1,I=!1;function j(e){for(var t=w(_);null!==t;){if(null===t.callback)k(_);else{if(!(t.startTime<=e))break;k(_),t.sortIndex=t.expirationTime,P(T,t)}t=w(_)}}function z(e){if(I=!1,j(e),!A)if(null!==w(T))A=!0,n(F);else{var t=w(_);null!==t&&a(z,t.startTime-e)}}function F(e,r){A=!1,I&&(I=!1,o()),R=!0;var n=D;try{for(j(r),L=w(T);null!==L&&(!(L.expirationTime>r)||e&&!i());){var l=L.callback;if(null!==l){L.callback=null,D=L.priorityLevel;var s=l(L.expirationTime<=r);r=t.unstable_now(),"function"==typeof s?L.callback=s:L===w(T)&&k(T),j(r)}else k(T);L=w(T)}if(null!==L)var p=!0;else{var c=w(_);null!==c&&a(z,c.startTime-r),p=!1}return p}finally{L=null,D=n,R=!1}}function G(e){switch(e){case 1:return-1;case 2:return 250;case 5:return 1073741823;case 4:return 1e4;default:return 5e3}}var V=l;t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(e){e.callback=null},t.unstable_continueExecution=function(){A||R||(A=!0,n(F))},t.unstable_getCurrentPriorityLevel=function(){return D},t.unstable_getFirstCallbackNode=function(){return w(T)},t.unstable_next=function(e){switch(D){case 1:case 2:case 3:var t=3;break;default:t=D}var r=D;D=t;try{return e()}finally{D=r}},t.unstable_pauseExecution=function(){},t.unstable_requestPaint=V,t.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var r=D;D=e;try{return t()}finally{D=r}},t.unstable_scheduleCallback=function(e,r,i){var l=t.unstable_now();if("object"==typeof i&&null!==i){var s=i.delay;s="number"==typeof s&&0<s?l+s:l,i="number"==typeof i.timeout?i.timeout:G(e)}else i=G(e),s=l;return e={id:M++,callback:r,priorityLevel:e,startTime:s,expirationTime:i=s+i,sortIndex:-1},s>l?(e.sortIndex=s,P(_,e),null===w(T)&&e===w(_)&&(I?o():I=!0,a(z,s-l))):(e.sortIndex=i,P(T,e),A||R||(A=!0,n(F))),e},t.unstable_shouldYield=function(){var e=t.unstable_now();j(e);var r=w(T);return r!==L&&null!==L&&null!==r&&null!==r.callback&&r.startTime<=e&&r.expirationTime<L.expirationTime||i()},t.unstable_wrapCallback=function(e){var t=D;return function(){var r=D;D=t;try{return e.apply(this,arguments)}finally{D=r}}}},function(e,t,r){(function(e){var n=void 0!==e&&e||"undefined"!=typeof self&&self||window,a=Function.prototype.apply;function o(e,t){this._id=e,this._clearFn=t}t.setTimeout=function(){return new o(a.call(setTimeout,n,arguments),clearTimeout)},t.setInterval=function(){return new o(a.call(setInterval,n,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e&&e.close()},o.prototype.unref=o.prototype.ref=function(){},o.prototype.close=function(){this._clearFn.call(n,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},r(23),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(this,r(11))},function(e,t,r){(function(e,t){!function(e,r){"use strict";if(!e.setImmediate){var n,a,o,i,l,s=1,p={},c=!1,u=e.document,d=Object.getPrototypeOf&&Object.getPrototypeOf(e);d=d&&d.setTimeout?d:e,"[object process]"==={}.toString.call(e.process)?n=function(e){t.nextTick((function(){b(e)}))}:!function(){if(e.postMessage&&!e.importScripts){var t=!0,r=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=r,t}}()?e.MessageChannel?((o=new MessageChannel).port1.onmessage=function(e){b(e.data)},n=function(e){o.port2.postMessage(e)}):u&&"onreadystatechange"in u.createElement("script")?(a=u.documentElement,n=function(e){var t=u.createElement("script");t.onreadystatechange=function(){b(e),t.onreadystatechange=null,a.removeChild(t),t=null},a.appendChild(t)}):n=function(e){setTimeout(b,0,e)}:(i="setImmediate$"+Math.random()+"$",l=function(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(i)&&b(+t.data.slice(i.length))},e.addEventListener?e.addEventListener("message",l,!1):e.attachEvent("onmessage",l),n=function(t){e.postMessage(i+t,"*")}),d.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),r=0;r<t.length;r++)t[r]=arguments[r+1];var a={callback:e,args:t};return p[s]=a,n(s),s++},d.clearImmediate=h}function h(e){delete p[e]}function b(e){if(c)setTimeout(b,0,e);else{var t=p[e];if(t){c=!0;try{!function(e){var t=e.callback,r=e.args;switch(r.length){case 0:t();break;case 1:t(r[0]);break;case 2:t(r[0],r[1]);break;case 3:t(r[0],r[1],r[2]);break;default:t.apply(void 0,r)}}(t)}finally{h(e),c=!1}}}}}("undefined"==typeof self?void 0===e?this:e:self)}).call(this,r(11),r(24))},function(e,t){var r,n,a=e.exports={};function o(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}function l(e){if(r===setTimeout)return setTimeout(e,0);if((r===o||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:o}catch(e){r=o}try{n="function"==typeof clearTimeout?clearTimeout:i}catch(e){n=i}}();var s,p=[],c=!1,u=-1;function d(){c&&s&&(c=!1,s.length?p=s.concat(p):u=-1,p.length&&h())}function h(){if(!c){var e=l(d);c=!0;for(var t=p.length;t;){for(s=p,p=[];++u<t;)s&&s[u].run();u=-1,t=p.length}s=null,c=!1,function(e){if(n===clearTimeout)return clearTimeout(e);if((n===i||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(e);try{n(e)}catch(t){try{return n.call(null,e)}catch(t){return n.call(this,e)}}}(e)}}function b(e,t){this.fun=e,this.array=t}function m(){}a.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];p.push(new b(e,t)),1!==p.length||c||l(h)},b.prototype.run=function(){this.fun.apply(null,this.array)},a.title="browser",a.browser=!0,a.env={},a.argv=[],a.version="",a.versions={},a.on=m,a.addListener=m,a.once=m,a.off=m,a.removeListener=m,a.removeAllListeners=m,a.emit=m,a.prependListener=m,a.prependOnceListener=m,a.listeners=function(e){return[]},a.binding=function(e){throw new Error("process.binding is not supported")},a.cwd=function(){return"/"},a.chdir=function(e){throw new Error("process.chdir is not supported")},a.umask=function(){return 0}},function(e,t,r){"use strict";var n=r(26);function a(){}function o(){}o.resetWarningCache=a,e.exports=function(){function e(e,t,r,a,o,i){if(i!==n){var l=new Error("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");throw l.name="Invariant Violation",l}}function t(){return e}e.isRequired=e;var r={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:o,resetWarningCache:a};return r.PropTypes=r,r}},function(e,t,r){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,r){var n=r(9),a=r(28);"string"==typeof(a=a.__esModule?a.default:a)&&(a=[[e.i,a,""]]);var o={insert:"head",singleton:!1};n(a,o);e.exports=a.locals||{}},function(e,t,r){(t=r(10)(!1)).push([e.i,'.color-picker-container{width:320px;height:300px;background-color:white;display:grid;grid-template-columns:100%;grid-template-rows:50% 50px 60px 40px 1fr;font-family:"acumin-pro-condensed";font-weight:normal;font-size:14px}.color-picker-container .color-picker-saturation{grid-row:1;grid-column:1;display:grid;grid-template-columns:100%;grid-template-rows:100%;position:relative;cursor:pointer}.color-picker-container .color-picker-saturation .color-picker-saturation-white{grid-row:1;grid-column:1;background:-webkit-linear-gradient(to right, #fff, rgba(255,255,255,0));background:linear-gradient(to right, #fff, rgba(255,255,255,0))}.color-picker-container .color-picker-saturation .color-picker-saturation-black{grid-row:1;grid-column:1;background:-webkit-linear-gradient(to top, #000, rgba(0,0,0,0));background:linear-gradient(to top, #000, rgba(0,0,0,0))}.color-picker-container .color-picker-saturation .color-picker-saturation-cursor{pointer-events:none;width:4px;height:4px;box-shadow:0 0 0 1.5px #fff,inset 0 0 1px 1px rgba(0,0,0,0.3),0 0 1px 2px rgba(0,0,0,0.4);border-radius:50%;transform:translate(-2px, -2px);position:absolute}.color-picker-container .color-picker-hue{grid-row:2;grid-column:1;display:grid;margin:10px;grid-template-columns:24% 76%;grid-template-rows:100%}.color-picker-container .color-picker-hue .color-picker-hue-color{grid-row:1;grid-column:1;align-self:center;justify-self:center;width:30px;height:30px;border-radius:15px;border:1px solid black}.color-picker-container .color-picker-hue .color-picker-hue-slider{grid-row:1;grid-column:2;align-self:center;height:16px;position:relative;cursor:pointer;background:linear-gradient(to right, red 0%, #ff0 17%, lime 33%, cyan 50%, blue 67%, #f0f 83%, red 100%);background:-webkit-linear-gradient(to right, red 0%, #ff0 17%, lime 33%, cyan 50%, blue 67%, #f0f 83%, red 100%)}.color-picker-container .color-picker-hue .color-picker-hue-slider .color-picker-hue-cursor{pointer-events:none;width:8px;height:18px;transform:translate(-4px, -2px);background-color:#f8f8f8;box-shadow:0 1px 4px 0 rgba(0,0,0,0.37);position:absolute}.color-picker-container .color-picker-component{display:grid;margin:5px;grid-template-columns:100%;grid-template-rows:50% 50%}.color-picker-container .color-picker-component .color-picker-component-value{justify-self:center;align-self:center;grid-row:1;grid-column:1;margin-bottom:4px}.color-picker-container .color-picker-component .color-picker-component-value input{width:50px}.color-picker-container .color-picker-component .color-picker-component-label{justify-self:center;align-self:center;grid-row:2;grid-column:1;color:black}.color-picker-container .color-picker-rgb{grid-row:3;grid-column:1;display:grid;margin:10px;grid-template-columns:20% 6.66% 20% 6.66% 20% 6.66% 20%;grid-template-rows:100%}.color-picker-container .red{grid-row:1;grid-column:1}.color-picker-container .green{grid-row:1;grid-column:3}.color-picker-container .blue{grid-row:1;grid-column:5}.color-picker-container .alpha{grid-row:1;grid-column:7}.color-picker-container .alpha.grayed{opacity:0.5}.color-picker-container .color-picker-hex{grid-row:4;grid-column:1;display:grid;grid-template-columns:20% 80%;grid-template-rows:100%}.color-picker-container .color-picker-hex .color-picker-hex-label{justify-self:center;align-self:center;grid-row:1;grid-column:1;margin-left:10px;color:black}.color-picker-container .color-picker-hex .color-picker-hex-value{justify-self:left;align-self:center;grid-row:1;grid-column:2;margin-left:10px;margin-right:10px}.color-picker-container .color-picker-hex .color-picker-hex-value input{width:70px}\n',""]),e.exports=t},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M13.45,11.32a.78.78,0,0,0-.77.66v3a.77.77,0,0,0,.66.76h3a.78.78,0,0,0,.77-.77.77.77,0,0,0-.67-.76H15.36a7.43,7.43,0,1,1-2.64,4.38.77.77,0,1,0-1.51-.29,9,9,0,1,0,3-5.13V12.09A.76.76,0,0,0,13.45,11.32Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M13.5,28.5h13a.76.76,0,0,1,.75.75.75.75,0,0,1-.65.74H13.5a.75.75,0,0,1-.1-1.5Zm1-13.28,5-5a.73.73,0,0,1,1-.07l.09.07,5,5a.75.75,0,0,1,0,1.06.75.75,0,0,1-1,.07l-.09-.07-3.72-3.72V26.25a.75.75,0,0,1-.65.74H20a.75.75,0,0,1-.74-.65V12.56l-3.72,3.72a.76.76,0,0,1-1,.07l-.08-.07a.75.75,0,0,1-.07-1l.07-.08,5-5Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M29.36,18.39a2.18,2.18,0,0,1,0,3.08l-7.91,7.91a1.22,1.22,0,0,1-.89.37h-1.7a.85.85,0,0,1-.86-.86v-1.7a1.22,1.22,0,0,1,.37-.89l7.91-7.91A2.18,2.18,0,0,1,29.36,18.39ZM30,23.11V27.5a2.25,2.25,0,0,1-2.25,2.25H23l1.5-1.5h3.25a.76.76,0,0,0,.75-.75v-3ZM23.63,10.25a1.23,1.23,0,0,1,.76.26L29.64,15a1.21,1.21,0,0,1,.36.9v1.23a2.43,2.43,0,0,0-.75-.43,2,2,0,0,0-.74-.1V16L24,12.14V15a1.75,1.75,0,0,1-1.75,1.75h-6A1.75,1.75,0,0,1,14.5,15V11.75H12.25a.75.75,0,0,0-.75.75v15a.75.75,0,0,0,.75.75H13V22.51a1.75,1.75,0,0,1,1.61-1.74H22l-1.55,1.5H14.75a.25.25,0,0,0-.24.2v5.79h2v1.5H12.25A2.25,2.25,0,0,1,10,27.5v-15a2.25,2.25,0,0,1,2.25-2.25Zm3.72,9.21-7.84,7.83v.95h.95l7.83-7.84a.66.66,0,0,0-.94-.94ZM22.5,11.75H16V15a.25.25,0,0,0,.25.25h6A.25.25,0,0,0,22.5,15Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 40 40'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:none;%7D.cls-2%7Bfill:%23e0684b;%7D.cls-3%7Bfill:%23bb464b;%7D.cls-4%7Bfill:%23e0ded8;%7D.cls-5%7Bfill:%23d5d2ca;%7D.cls-6%7Bfill:%23fff;%7D%3C/style%3E%3C/defs%3E%3Cg id='UI'%3E%3Crect class='cls-1' width='40' height='40'/%3E%3Cpolygon class='cls-2' points='32.91 13.78 29.54 11.84 26.29 13.71 29.66 15.65 32.91 13.78'/%3E%3Cpolygon class='cls-2' points='14.61 15.65 25.38 9.44 22.14 7.57 11.37 13.78 14.61 15.65'/%3E%3Cpolygon class='cls-2' points='18.77 21.95 22.14 23.89 25.51 21.95 22.14 20 18.77 21.95'/%3E%3Cpolygon class='cls-3' points='29.66 15.65 29.66 24.34 22.14 28.69 14.61 24.34 14.61 15.65 11.37 13.78 11.37 26.22 22.14 32.44 32.91 26.22 32.91 13.78 29.66 15.65'/%3E%3Cpolygon class='cls-3' points='22.14 16.11 18.77 18.05 18.77 21.95 22.14 20 25.51 21.95 25.51 18.05 22.14 16.11'/%3E%3Cpolygon class='cls-4' points='29.66 15.65 25.51 18.05 25.51 21.95 22.14 23.89 22.14 28.69 29.66 24.34 29.66 15.65'/%3E%3Cpolygon class='cls-5' points='14.61 15.65 18.77 18.05 18.77 21.95 22.14 23.89 22.14 28.69 14.61 24.34 14.61 15.65'/%3E%3Cpolygon class='cls-6' points='25.38 9.44 29.54 11.84 26.29 13.71 29.66 15.65 25.51 18.05 22.14 16.11 18.77 18.05 14.61 15.65 25.38 9.44'/%3E%3C/g%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M12.5,21a.5.5,0,0,1,.5.5V25a2,2,0,0,0,2,2h3.5a.5.5,0,0,1,0,1H15a3,3,0,0,1-3-3V21.5A.5.5,0,0,1,12.5,21Zm15,0a.5.5,0,0,1,.49.41V25a3,3,0,0,1-2.82,3H21.5a.5.5,0,0,1-.09-1H25a2,2,0,0,0,2-1.85V21.5A.5.5,0,0,1,27.5,21Zm-9-9a.5.5,0,0,1,.09,1H15a2,2,0,0,0-2,1.85V18.5a.5.5,0,0,1-1,.09V15a3,3,0,0,1,2.82-3H18.5ZM25,12a3,3,0,0,1,3,2.82V18.5a.5.5,0,0,1-1,.09V15a2,2,0,0,0-1.85-2H21.5a.5.5,0,0,1-.09-1H25Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M15.47,20.28l.08.07a.75.75,0,0,0,1-.07l2.72-2.72v6.79A.75.75,0,0,0,20,25h.1a.75.75,0,0,0,.65-.74V17.56l2.72,2.72.08.07a.75.75,0,0,0,1-1.13l-4-4-.08-.07a.75.75,0,0,0-1,.07l-4,4-.07.08A.75.75,0,0,0,15.47,20.28Z' style='fill:%23fff'/%3E%3Cpath d='M30,20A10,10,0,1,0,20,30,10,10,0,0,0,30,20ZM11.5,20A8.5,8.5,0,1,1,20,28.5,8.51,8.51,0,0,1,11.5,20Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M24.53,19.72l-.08-.07a.75.75,0,0,0-1,.07l-2.72,2.72V15.65A.75.75,0,0,0,20,15h-.1a.75.75,0,0,0-.65.74v6.69l-2.72-2.72-.08-.07a.75.75,0,0,0-1,1.13l4,4,.08.07a.75.75,0,0,0,1-.07l4-4,.07-.08A.75.75,0,0,0,24.53,19.72Z' style='fill:%23fff'/%3E%3Cpath d='M10,20A10,10,0,1,0,20,10,10,10,0,0,0,10,20Zm18.5,0A8.5,8.5,0,1,1,20,11.5,8.51,8.51,0,0,1,28.5,20Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M16.89,16v3h2.82v1.27H16.89v3h-1.3v-3H12.74V19h2.85V16Z' style='fill:%23fff'/%3E%3Cpath d='M25.34,24.62l-1.75-4.21h0L21.8,24.62H20l2.61-5.57-2.51-5.29H22l1.63,3.8h0l1.65-3.8h1.77l-2.49,5.11,2.64,5.75Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M17.75,18.72v1.45H14.33V18.72Z' style='fill:%23fff'/%3E%3Cpath d='M23.75,24.62,22,20.41h0l-1.77,4.21H18.44l2.61-5.57-2.52-5.29h1.93l1.63,3.8h0l1.65-3.8h1.78L23,18.87l2.64,5.75Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M16.84,16v3h2.82v1.27H16.84v3h-1.3v-3H12.69V19h2.85V16Z' style='fill:%23fff'/%3E%3Cpath d='M22.79,24.62V20.68a.63.63,0,0,0-.06-.32L20,13.76h1.87c.66,1.76,1.51,4,1.83,5.13.4-1.24,1.25-3.46,1.84-5.13h1.78l-2.77,6.61a.73.73,0,0,0-.05.34v3.91Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M17.7,18.72v1.45H14.28V18.72Z' style='fill:%23fff'/%3E%3Cpath d='M21.21,24.62V20.68a.63.63,0,0,0-.07-.32l-2.73-6.6h1.87c.66,1.76,1.5,4,1.82,5.13.4-1.24,1.25-3.46,1.84-5.13h1.78L23,20.37a.9.9,0,0,0-.05.34v3.91Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M17.1,16v3h2.82v1.27H17.1v3H15.81v-3H13V19h2.85V16Z' style='fill:%23fff'/%3E%3Cpath d='M20.67,23.43,25,15.25H21V13.76h5.86v1.36l-4.23,8H27l-.22,1.48H20.67Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M18,18.72v1.45H14.54V18.72Z' style='fill:%23fff'/%3E%3Cpath d='M19.09,23.43l4.35-8.18h-4V13.76h5.86v1.36l-4.22,8h4.4l-.23,1.48H19.09Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M20,18.27a3.09,3.09,0,1,1-3.08,3.08A3.09,3.09,0,0,1,20,18.27Zm0,1.15a1.93,1.93,0,1,0,1.93,1.93A1.94,1.94,0,0,0,20,19.42Zm0-3.86a7.71,7.71,0,0,1,7.48,5.84.58.58,0,1,1-1.12.28,6.56,6.56,0,0,0-12.72,0,.58.58,0,0,1-1.12-.28A7.72,7.72,0,0,1,20,15.56Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M12.42,13a.57.57,0,0,0-.06.75l.06.07,3.13,3.13a7.69,7.69,0,0,0-3.07,4.45.58.58,0,0,0,1.13.29,6.6,6.6,0,0,1,2.77-3.91l1.41,1.41a3.1,3.1,0,0,0,4.38,4.38l4.59,4.59a.57.57,0,0,0,.82,0,.58.58,0,0,0,.06-.76l-.06-.06-4.74-4.74h0l-.93-.93-2.22-2.23h0L17.46,17.2h0l-.88-.88L13.24,13A.57.57,0,0,0,12.42,13Zm6.19,7,2.74,2.74A1.94,1.94,0,0,1,18.61,20ZM20,15.53a7.54,7.54,0,0,0-2.24.33l1,1A6.69,6.69,0,0,1,20,16.69a6.59,6.59,0,0,1,6.39,5,.59.59,0,0,0,.71.42.58.58,0,0,0,.42-.7A7.74,7.74,0,0,0,20,15.53Zm.15,2.72,3,2.95A3.11,3.11,0,0,0,20.15,18.25Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t,r){var n=r(9),a=r(45);"string"==typeof(a=a.__esModule?a.default:a)&&(a=[[e.i,a,""]]);var o={insert:"head",singleton:!1};n(a,o);e.exports=a.locals||{}},function(e,t,r){(t=r(10)(!1)).push([e.i,"#texture-editor{height:100%;width:100%;color:white;background-color:#1e1e1e;font-family:'acumin-pro-condensed'}#texture-editor .icon{width:40px;height:40px}#texture-editor .icon.button{background-color:#333333}#texture-editor .icon.button:hover{background-color:#4a4a4a;cursor:pointer}#texture-editor .icon.button.active{background-color:#666666}#texture-editor .icon.button:active{background-color:#837c7c}#texture-editor .has-tooltip{display:inline-block}#texture-editor .has-tooltip .tooltip{visibility:hidden;background-color:#fff;z-index:1;position:absolute;opacity:0;transition:opacity 0.5s;line-height:normal;font-size:14px;padding:0px 5px;color:black}#texture-editor .has-tooltip:hover .tooltip{visibility:visible;opacity:1}#texture-editor #properties{width:100%;height:40px;display:flex;align-items:center;font-size:12px;color:white;user-select:none;background-color:#333333}#texture-editor #properties .tab{display:inline-flex;line-height:40px;height:40px;flex-shrink:0;flex-grow:0;border-right:2px solid #1e1e1e;background-color:#333333}#texture-editor #properties #left{overflow:hidden;height:40px;flex-grow:1;flex-shrink:1;display:flex;flex-wrap:wrap}#texture-editor #properties #left #dimensions-tab form{display:flex}#texture-editor #properties #left #dimensions-tab label{margin-left:15px;font-size:15px;color:#afafaf}#texture-editor #properties #left #dimensions-tab label input{width:40px;height:24px;background-color:#000000;color:#ffffff;border:0;font-size:12px;text-align:'left';font-family:'acumin-pro-condensed';font-size:15px;padding-left:8px}#texture-editor #properties #left #dimensions-tab label:last-of-type{margin-right:8px}#texture-editor #properties #right-tab{margin-right:0;flex-grow:0;flex-shrink:0}#texture-editor #properties #right-tab input[type=\"file\"]{display:none}#texture-editor #properties .pixel-data{width:45px;color:#afafaf;display:flex;justify-content:space-between;font-size:15px}#texture-editor #properties .pixel-data:first-of-type{margin-left:15px}#texture-editor #properties .pixel-data:last-of-type{padding-right:15px}#texture-editor #properties .pixel-data .value{display:inline-block;width:30px;color:white}#texture-editor #toolbar{position:absolute;top:60px;left:0;width:40px;display:flex;flex-direction:column;justify-content:left}#texture-editor #toolbar #tools{display:flex;flex-direction:column}#texture-editor #toolbar #add-tool{position:relative}#texture-editor #toolbar #add-tool #add-tool-popup{background-color:#333333;width:348px;margin-left:40px;position:absolute;top:0px;height:40px;padding-left:4px;line-height:40px;user-select:none}#texture-editor #toolbar #add-tool #add-tool-popup button{background:#222222;border:1px solid #337ab7;margin:5px 10px 5px 10px;color:white;padding:4px 5px;opacity:0.9;cursor:pointer}#texture-editor #toolbar #color{margin-top:8px}#texture-editor #toolbar #color #active-color-bg{border-radius:50%;width:20px;height:20px;margin:10px;position:relative;background-image:linear-gradient(45deg, gray 25%, transparent 25%),linear-gradient(-45deg, gray 25%, transparent 25%),linear-gradient(45deg, transparent 75%, gray 75%),linear-gradient(-45deg, transparent 75%, gray 75%);background-size:20px 20px;background-position:0 0, 0 10px, 10px -10px, -10px 0px}#texture-editor #toolbar #color #active-color{width:20px;height:20px;position:absolute;top:0;left:0;border-radius:50%}#texture-editor #toolbar #color-picker{position:absolute;margin-left:40px}#texture-editor #channels-bar{position:absolute;top:60px;right:0;width:80px;background:#666666;user-select:none}#texture-editor #channels-bar .channel{color:white;border-bottom:2px solid #232323;width:80px;height:40px;font-size:16px;display:flex;align-items:center}#texture-editor #channels-bar .channel.uneditable{background:#333333}#texture-editor #channels-bar .channel:hover{cursor:pointer}#texture-editor #channels-bar .channel:last-of-type{border-bottom:none}#texture-editor #canvas-ui{width:100%;height:calc(100% - 70px);outline:none}#texture-editor #tool-ui{background-color:#333;position:absolute;right:0;bottom:30px}#texture-editor #tool-ui label{display:flex;flex-direction:column;align-items:center}#texture-editor #tool-ui input[type='range']{background:#d3d3d3}#texture-editor #bottom-bar{height:30px;width:100%;background-color:#333333;font-size:14px;user-select:none;line-height:30px;position:relative}#texture-editor #bottom-bar #file-url{left:30px;position:absolute}#texture-editor #bottom-bar #mip-level{right:30px;position:absolute}\n",""]),e.exports=t},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M20,30.5A10.5,10.5,0,1,1,30.5,20,10.51,10.51,0,0,1,20,30.5Zm0-20A9.5,9.5,0,1,0,29.5,20,9.51,9.51,0,0,0,20,10.5Z' style='fill:%23fff'/%3E%3Cpath d='M18.45,20.77v4.14H16.26V14.58h4.55c2.25,0,3.46,1.23,3.46,2.83a2.5,2.5,0,0,1-1.5,2.45c.51.19,1.29.72,1.29,2.58V23a7.77,7.77,0,0,0,.15,2H22.08a7.38,7.38,0,0,1-.21-2.32v-.15c0-1.13-.28-1.67-1.95-1.67Zm0-1.78h1.88c1.21,0,1.69-.47,1.69-1.32s-.55-1.32-1.65-1.32H18.45Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M20,30.5A10.5,10.5,0,1,1,30.5,20,10.51,10.51,0,0,1,20,30.5Zm0-20A9.5,9.5,0,1,0,29.5,20,9.51,9.51,0,0,0,20,10.5Z' style='fill:%23fff'/%3E%3Cpath d='M24.6,24.91H23a5.43,5.43,0,0,1-.18-1,3.5,3.5,0,0,1-3,1.2c-3,0-4.68-2.28-4.68-5.22,0-3.1,1.81-5.44,5.07-5.44,2.65,0,4.23,1.5,4.47,3.25H22.39a2.09,2.09,0,0,0-2.26-1.51c-2.13,0-2.73,1.78-2.73,3.6s.69,3.54,2.74,3.54a2.05,2.05,0,0,0,2.27-2.25V21H20.14V19.12H24.6Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M20,30.5A10.5,10.5,0,1,1,30.5,20,10.51,10.51,0,0,1,20,30.5Zm0-20A9.5,9.5,0,1,0,29.5,20,9.51,9.51,0,0,0,20,10.5Z' style='fill:%23fff'/%3E%3Cpath d='M16.17,14.58h4.51c2.51,0,3.45,1.29,3.45,2.64a2.31,2.31,0,0,1-1.32,2.23,2.48,2.48,0,0,1,1.62,2.37c0,1.77-1.39,3.09-3.58,3.09H16.17Zm4.26,4.08c1.06,0,1.5-.48,1.5-1.22s-.57-1.14-1.43-1.14H18.36v2.36Zm-2.07,4.53h2c1.22,0,1.76-.51,1.76-1.44s-.54-1.37-1.77-1.37h-2Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M20,30.5A10.58,10.58,0,1,1,30.57,19.93,10.58,10.58,0,0,1,20,30.5Zm0-19.9a9.33,9.33,0,1,0,9.33,9.33A9.34,9.34,0,0,0,20,10.6Z' style='fill:%23fff'/%3E%3Cpath d='M16.32,14.54h4.09a4.68,4.68,0,0,1,4.95,5c0,3-1.91,5.27-5.06,5.27h-4ZM18.54,23h1.67c2,0,2.85-1.48,2.85-3.48,0-1.69-.82-3.22-2.83-3.22H18.54Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 40 40'%3E%3Crect width='40' height='40' style='fill:none'/%3E%3Cpath d='M20,30.5A10.5,10.5,0,1,1,30.5,20,10.51,10.51,0,0,1,20,30.5Zm0-20A9.5,9.5,0,1,0,29.5,20,9.51,9.51,0,0,0,20,10.5Z' style='fill:%23fff'/%3E%3Cpath d='M18,22.53l-.79,2.38H15l3.51-10.33h2.81L25,24.91H22.64l-.86-2.38Zm3.3-1.83c-.73-2.19-1.2-3.59-1.45-4.52h0c-.25,1-.76,2.64-1.35,4.52Z' style='fill:%23fff'/%3E%3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg viewBox='0 0 24 24' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='24' height='24'%3E %3C!-- Generator: Sketch 59.1 (86144) - https://sketch.com --%3E %3Ctitle%3Eic_fluent_delete_24_regular%3C/title%3E %3Cdesc%3ECreated with Sketch.%3C/desc%3E %3Cg id='🔍-Product-Icons' stroke='none' stroke-width='1' fill='none' fill-rule='evenodd'%3E %3Cg id='ic_fluent_delete_24_regular' fill='white' fill-rule='nonzero'%3E %3Cpath d='M12,1.75 C13.7330315,1.75 15.1492459,3.10645477 15.2448552,4.81557609 L15.25,5 L20.5,5 C20.9142136,5 21.25,5.33578644 21.25,5.75 C21.25,6.12969577 20.9678461,6.44349096 20.6017706,6.49315338 L20.5,6.5 L19.704,6.5 L18.4238627,19.5191927 C18.2911666,20.8682696 17.1984309,21.9099961 15.8626249,21.9944645 L15.6870698,22 L8.31293022,22 C6.95734302,22 5.81365352,21.0144851 5.59883106,19.6933629 L5.57613734,19.5191927 L4.295,6.5 L3.5,6.5 C3.12030423,6.5 2.80650904,6.21784612 2.75684662,5.85177056 L2.75,5.75 C2.75,5.37030423 3.03215388,5.05650904 3.39822944,5.00684662 L3.5,5 L8.75,5 C8.75,3.20507456 10.2050746,1.75 12,1.75 Z M18.197,6.5 L5.802,6.5 L7.06893346,19.3723603 C7.12767639,19.9695801 7.60033019,20.4342891 8.18584501,20.493596 L8.31293022,20.5 L15.6870698,20.5 C16.2871716,20.5 16.795916,20.0751057 16.9122531,19.4982083 L16.9310665,19.3723603 L18.197,6.5 Z M13.75,9.25 C14.1296958,9.25 14.443491,9.53215388 14.4931534,9.89822944 L14.5,10 L14.5,17 C14.5,17.4142136 14.1642136,17.75 13.75,17.75 C13.3703042,17.75 13.056509,17.4678461 13.0068466,17.1017706 L13,17 L13,10 C13,9.58578644 13.3357864,9.25 13.75,9.25 Z M10.25,9.25 C10.6296958,9.25 10.943491,9.53215388 10.9931534,9.89822944 L11,10 L11,17 C11,17.4142136 10.6642136,17.75 10.25,17.75 C9.87030423,17.75 9.55650904,17.4678461 9.50684662,17.1017706 L9.5,17 L9.5,10 C9.5,9.58578644 9.83578644,9.25 10.25,9.25 Z M12,3.25 C11.0818266,3.25 10.3288077,3.95711027 10.2558012,4.85647279 L10.25,5 L13.75,5 C13.75,4.03350169 12.9664983,3.25 12,3.25 Z' id='🎨-Color'%3E%3C/path%3E %3C/g%3E %3C/g%3E %3C/svg%3E"},function(e,t){e.exports="data:image/svg+xml,%3Csvg viewBox='0 0 24 24' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='24' height='24'%3E %3C!-- Generator: Sketch 59.1 (86144) - https://sketch.com --%3E %3Ctitle%3Eic_fluent_copy_24_regular%3C/title%3E %3Cdesc%3ECreated with Sketch.%3C/desc%3E %3Cg id='🔍-Product-Icons' stroke='none' stroke-width='1' fill='none' fill-rule='evenodd'%3E %3Cg id='ic_fluent_copy_24_regular' fill='white' fill-rule='nonzero'%3E %3Cpath d='M5.50280381,4.62704038 L5.5,6.75 L5.5,17.2542087 C5.5,19.0491342 6.95507456,20.5042087 8.75,20.5042087 L17.3662868,20.5044622 C17.057338,21.3782241 16.2239751,22.0042087 15.2444057,22.0042087 L8.75,22.0042087 C6.12664744,22.0042087 4,19.8775613 4,17.2542087 L4,6.75 C4,5.76928848 4.62744523,4.93512464 5.50280381,4.62704038 Z M17.75,2 C18.9926407,2 20,3.00735931 20,4.25 L20,17.25 C20,18.4926407 18.9926407,19.5 17.75,19.5 L8.75,19.5 C7.50735931,19.5 6.5,18.4926407 6.5,17.25 L6.5,4.25 C6.5,3.00735931 7.50735931,2 8.75,2 L17.75,2 Z M17.75,3.5 L8.75,3.5 C8.33578644,3.5 8,3.83578644 8,4.25 L8,17.25 C8,17.6642136 8.33578644,18 8.75,18 L17.75,18 C18.1642136,18 18.5,17.6642136 18.5,17.25 L18.5,4.25 C18.5,3.83578644 18.1642136,3.5 17.75,3.5 Z' id='🎨-Color'%3E%3C/path%3E %3C/g%3E %3C/g%3E %3C/svg%3E"},function(e,t,r){e.exports=function(e){function t(n){if(r[n])return r[n].exports;var a=r[n]={exports:{},id:n,loaded:!1};return e[n].call(a.exports,a,a.exports,t),a.loaded=!0,a.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){var n,a,o={}.hasOwnProperty,i=[].indexOf||function(e){for(var t=0,r=this.length;t<r;t++)if(t in this&&this[t]===e)return t;return-1};n=r(1).EventEmitter,r(2),a=function(e){function t(e){var t,n,a;for(n in this.running=!1,this.options={},this.frames=[],this.groups=new Map,this.freeWorkers=[],this.activeWorkers=[],this.setOptions(e),r)a=r[n],null==(t=this.options)[n]&&(t[n]=a)}var r,n;return function(e,t){function r(){this.constructor=e}for(var n in t)o.call(t,n)&&(e[n]=t[n]);r.prototype=t.prototype,e.prototype=new r,e.__super__=t.prototype}(t,e),r={workerScript:"gif.worker.js",workers:2,repeat:0,background:"#fff",quality:10,width:null,height:null,transparent:null,debug:!1},n={delay:500,copy:!1},t.prototype.setOption=function(e,t){if(this.options[e]=t,null!=this._canvas&&("width"===e||"height"===e))return this._canvas[e]=t},t.prototype.setOptions=function(e){var t,r,n;for(t in r=[],e)o.call(e,t)&&(n=e[t],r.push(this.setOption(t,n)));return r},t.prototype.addFrame=function(e,t){var r,a,o;for(o in null==t&&(t={}),(r={}).transparent=this.options.transparent,n)r[o]=t[o]||n[o];if(null==this.options.width&&this.setOption("width",e.width),null==this.options.height&&this.setOption("height",e.height),"undefined"!=typeof ImageData&&null!==ImageData&&e instanceof ImageData)r.data=e.data;else if("undefined"!=typeof CanvasRenderingContext2D&&null!==CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!=typeof WebGLRenderingContext&&null!==WebGLRenderingContext&&e instanceof WebGLRenderingContext)t.copy?r.data=this.getContextData(e):r.context=e;else{if(null==e.childNodes)throw new Error("Invalid image");t.copy?r.data=this.getImageData(e):r.image=e}return(a=this.frames.length)>0&&r.data&&(this.groups.has(r.data)?this.groups.get(r.data).push(a):this.groups.set(r.data,[a])),this.frames.push(r)},t.prototype.render=function(){var e,t,r;if(this.running)throw new Error("Already running");if(null==this.options.width||null==this.options.height)throw new Error("Width and height must be set prior to rendering");if(this.running=!0,this.nextFrame=0,this.finishedFrames=0,this.imageParts=function(){var e,t,r;for(r=[],e=0,t=this.frames.length;0<=t?e<t:e>t;0<=t?++e:--e)r.push(null);return r}.call(this),t=this.spawnWorkers(),!0===this.options.globalPalette)this.renderNextFrame();else for(e=0,r=t;0<=r?e<r:e>r;0<=r?++e:--e)this.renderNextFrame();return this.emit("start"),this.emit("progress",0)},t.prototype.abort=function(){for(var e;null!=(e=this.activeWorkers.shift());)this.log("killing active worker"),e.terminate();return this.running=!1,this.emit("abort")},t.prototype.spawnWorkers=function(){var e,t,r;return e=Math.min(this.options.workers,this.frames.length),function(){r=[];for(var n=t=this.freeWorkers.length;t<=e?n<e:n>e;t<=e?n++:n--)r.push(n);return r}.apply(this).forEach(function(e){return function(t){var r;return e.log("spawning worker "+t),(r=new Worker(e.options.workerScript)).onmessage=function(t){return e.activeWorkers.splice(e.activeWorkers.indexOf(r),1),e.freeWorkers.push(r),e.frameFinished(t.data,!1)},e.freeWorkers.push(r)}}(this)),e},t.prototype.frameFinished=function(e,t){var r,n,a,o;if(this.finishedFrames++,t?(r=this.frames.indexOf(e),n=this.groups.get(e.data)[0],this.log("frame "+(r+1)+" is duplicate of "+n+" - "+this.activeWorkers.length+" active"),this.imageParts[r]={indexOfFirstInGroup:n}):(this.log("frame "+(e.index+1)+" finished - "+this.activeWorkers.length+" active"),this.emit("progress",this.finishedFrames/this.frames.length),this.imageParts[e.index]=e),!0===this.options.globalPalette&&!t&&(this.options.globalPalette=e.globalPalette,this.log("global palette analyzed"),this.frames.length>2))for(a=1,o=this.freeWorkers.length;1<=o?a<o:a>o;1<=o?++a:--a)this.renderNextFrame();return i.call(this.imageParts,null)>=0?this.renderNextFrame():this.finishRendering()},t.prototype.finishRendering=function(){var e,t,r,n,a,o,i,l,s,p,c,u,d,h,b,m,g,f,v,y;for(a=o=0,p=(g=this.imageParts).length;o<p;a=++o)(t=g[a]).indexOfFirstInGroup&&(this.imageParts[a]=this.imageParts[t.indexOfFirstInGroup]);for(s=0,i=0,c=(f=this.imageParts).length;i<c;i++)s+=((t=f[i]).data.length-1)*t.pageSize+t.cursor;for(s+=t.pageSize-t.cursor,this.log("rendering finished - filesize "+Math.round(s/1e3)+"kb"),e=new Uint8Array(s),b=0,l=0,u=(v=this.imageParts).length;l<u;l++)for(r=h=0,d=(y=(t=v[l]).data).length;h<d;r=++h)m=y[r],e.set(m,b),b+=r===t.data.length-1?t.cursor:t.pageSize;return n=new Blob([e],{type:"image/gif"}),this.emit("finished",n,e)},t.prototype.renderNextFrame=function(){var e,t,r,n;if(0===this.freeWorkers.length)throw new Error("No free workers");if(!(this.nextFrame>=this.frames.length))return e=this.frames[this.nextFrame++],(t=this.frames.indexOf(e))>0&&this.groups.has(e.data)&&this.groups.get(e.data)[0]!==t?void setTimeout(function(t){return function(){return t.frameFinished(e,!0)}}(this),0):(n=this.freeWorkers.shift(),r=this.getTask(e),this.log("starting frame "+(r.index+1)+" of "+this.frames.length),this.activeWorkers.push(n),n.postMessage(r))},t.prototype.getContextData=function(e){return e.getImageData(0,0,this.options.width,this.options.height).data},t.prototype.getImageData=function(e){var t;return null==this._canvas&&(this._canvas=document.createElement("canvas"),this._canvas.width=this.options.width,this._canvas.height=this.options.height),(t=this._canvas.getContext("2d")).setFill=this.options.background,t.fillRect(0,0,this.options.width,this.options.height),t.drawImage(e,0,0),this.getContextData(t)},t.prototype.getTask=function(e){var t,r;if(r={index:t=this.frames.indexOf(e),last:t===this.frames.length-1,delay:e.delay,transparent:e.transparent,width:this.options.width,height:this.options.height,quality:this.options.quality,dither:this.options.dither,globalPalette:this.options.globalPalette,repeat:this.options.repeat,canTransfer:!0},null!=e.data)r.data=e.data;else if(null!=e.context)r.data=this.getContextData(e.context);else{if(null==e.image)throw new Error("Invalid frame");r.data=this.getImageData(e.image)}return r},t.prototype.log=function(e){if(this.options.debug)return console.log(e)},t}(n),e.exports=a},function(e,t){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function n(e){return"function"==typeof e}function a(e){return"object"==typeof e&&null!==e}function o(e){return void 0===e}e.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!function(e){return"number"==typeof e}(e)||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,r,i,l,s,p;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}if(o(r=this._events[e]))return!1;if(n(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:l=Array.prototype.slice.call(arguments,1),r.apply(this,l)}else if(a(r))for(l=Array.prototype.slice.call(arguments,1),i=(p=r.slice()).length,s=0;s<i;s++)p[s].apply(this,l);return!0},r.prototype.addListener=function(e,t){var i;if(!n(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,n(t.listener)?t.listener:t),this._events[e]?a(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,a(this._events[e])&&!this._events[e].warned&&(i=o(this._maxListeners)?r.defaultMaxListeners:this._maxListeners)&&i>0&&this._events[e].length>i&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function r(){this.removeListener(e,r),a||(a=!0,t.apply(this,arguments))}if(!n(t))throw TypeError("listener must be a function");var a=!1;return r.listener=t,this.on(e,r),this},r.prototype.removeListener=function(e,t){var r,o,i,l;if(!n(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(i=(r=this._events[e]).length,o=-1,r===t||n(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(a(r)){for(l=i;l-- >0;)if(r[l]===t||r[l].listener&&r[l].listener===t){o=l;break}if(o<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(o,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n(r=this._events[e]))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){return this._events&&this._events[e]?n(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(n(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t){var r,n,a,o,i;i=navigator.userAgent.toLowerCase(),o=navigator.platform.toLowerCase(),a="ie"===(r=i.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/)||[null,"unknown",0])[1]&&document.documentMode,(n={name:"version"===r[1]?r[3]:r[1],version:a||parseFloat("opera"===r[1]&&r[4]?r[4]:r[2]),platform:{name:i.match(/ip(?:ad|od|hone)/)?"ios":(i.match(/(?:webos|android)/)||o.match(/mac|win|linux/)||["other"])[0]}})[n.name]=!0,n[n.name+parseInt(n.version,10)]=!0,n.platform[n.platform.name]=!0,e.exports=n}])},function(e,t,r){var n=r(9),a=r(55);"string"==typeof(a=a.__esModule?a.default:a)&&(a=[[e.i,a,""]]);var o={insert:"head",singleton:!1};n(a,o);e.exports=a.locals||{}},function(e,t,r){(t=r(10)(!1)).push([e.i,"#inspector-host{position:absolute;right:0px;top:0px;bottom:0px}#__resizable_base__{display:none}#actionTabs{background:#333333;height:100%;margin:0;padding:0;display:grid;grid-template-rows:auto 1fr;font:14px \"Arial\";overflow:hidden}#actionTabs .hoverIcon:hover{opacity:0.8}#actionTabs #header{height:30px;font-size:16px;color:white;background:#222222;grid-row:1;text-align:center;display:grid;grid-template-columns:30px 1fr 50px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}#actionTabs #header #logo{grid-column:1;width:24px;height:24px;display:flex;align-self:center;justify-self:center}#actionTabs #header #back{grid-column:1;display:grid;align-self:center;justify-self:center;cursor:pointer}#actionTabs #header #title{grid-column:2;display:grid;align-items:center;text-align:center}#actionTabs #header #commands{grid-column:3;display:grid;align-items:center;grid-template-columns:1fr 1fr}#actionTabs #header #commands .expand{grid-column:1;display:grid;align-items:center;justify-items:center;cursor:pointer}#actionTabs #header #commands .close{grid-column:2;display:grid;align-items:center;justify-items:center;cursor:pointer}#actionTabs .tabs{display:grid;grid-row:2;grid-template-rows:40px 1fr;font:14px \"Arial\";overflow:hidden}#actionTabs .tabs .labels{grid-row:1;display:flex;align-items:center;justify-items:center;border-bottom:1px solid #ffffff;margin:0;padding:0}#actionTabs .tabs .labels .label{font-size:24px;color:white;width:40px;display:flex;align-content:center;justify-content:center;border:1px solid transparent;border-bottom:none;background:#333333;padding:5px;height:28px;cursor:pointer}#actionTabs .tabs .labels .label.active{border-color:#ffffff;border-bottom:2px solid transparent;margin-bottom:-2px}#actionTabs .tabs .panes{grid-row:2;display:grid;grid-template-rows:100%;overflow:hidden}#actionTabs .tabs .panes .infoMessage{opacity:0.5;color:white;margin:15px 5px 0px 5px}#actionTabs .tabs .panes .gradient-step{display:grid;grid-template-rows:100%;grid-template-columns:20px 30px 40px auto 20px 30px;padding-top:5px;padding-left:5px;padding-bottom:5px;align-items:center}#actionTabs .tabs .panes .gradient-step .step{grid-row:1;grid-column:1}#actionTabs .tabs .panes .gradient-step .color1{height:100%}#actionTabs .tabs .panes .gradient-step .color2{height:100%;padding-left:5px}#actionTabs .tabs .panes .gradient-step .factor1{grid-row:1;grid-column:2;cursor:pointer}#actionTabs .tabs .panes .gradient-step .factor2{padding-left:5px;grid-row:1;grid-column:3;cursor:pointer}#actionTabs .tabs .panes .gradient-step .factor2 .grayed{background:gray;border-color:gray}#actionTabs .tabs .panes .gradient-step .numeric-input{width:calc(100% - 5px)}#actionTabs .tabs .panes .gradient-step .icon{cursor:pointer}#actionTabs .tabs .panes .gradient-step .step-value{margin-left:5px;grid-row:1;grid-column:3;text-align:right;margin-right:5px}#actionTabs .tabs .panes .gradient-step .step-slider{grid-row:1;grid-column:4;display:grid;justify-content:stretch;align-content:center;margin-right:12px}#actionTabs .tabs .panes .gradient-step .step-slider input{width:100%}#actionTabs .tabs .panes .gradient-step .step-slider .range:hover{opacity:1}#actionTabs .tabs .panes .gradient-step .step-slider .range{-webkit-appearance:none;height:6px;background:#d3d3d3;border-radius:5px;outline:none;opacity:0.7;-webkit-transition:.2s;transition:opacity .2s}#actionTabs .tabs .panes .gradient-step .step-slider .range::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:14px;height:14px;border-radius:50%;background:#337ab7;cursor:pointer}#actionTabs .tabs .panes .gradient-step .step-slider .range::-moz-range-thumb{width:14px;height:14px;border-radius:50%;background:#337ab7;cursor:pointer}#actionTabs .tabs .panes .gradient-step .gradient-copy{grid-row:1;grid-column:5;display:grid;align-content:center;justify-content:center}#actionTabs .tabs .panes .gradient-step .gradient-copy .img{height:20px;width:20px}#actionTabs .tabs .panes .gradient-step .gradient-copy .img:hover{cursor:pointer}#actionTabs .tabs .panes .gradient-step .gradient-delete{grid-row:1;grid-column:6;display:grid;align-content:center;justify-content:center}#actionTabs .tabs .panes .gradient-step .gradient-delete .img{height:20px;width:20px}#actionTabs .tabs .panes .gradient-step .gradient-delete .img:hover{cursor:pointer}#actionTabs .tabs .panes .pane{color:white;overflow-x:hidden;overflow-y:auto;height:100%;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}#actionTabs .tabs .panes .pane .animation-info{border-left:greenyellow 3px solid;margin-left:5px;padding-left:5px !important}#actionTabs .tabs .panes .pane .underline{border-bottom:0.5px solid rgba(255,255,255,0.5)}#actionTabs .tabs .panes .pane .textureLinkLine{display:grid;grid-template-columns:auto 1fr}#actionTabs .tabs .panes .pane .textureLinkLine .debug{grid-column:1;margin-left:5px;margin-right:5px;display:block;align-items:center;justify-items:center;cursor:pointer;opacity:0.5}#actionTabs .tabs .panes .pane .textureLinkLine .debug.selected{opacity:1.0}#actionTabs .tabs .panes .pane .textureLinkLine .textLine{grid-column:2}#actionTabs .tabs .panes .pane .textureLinkLine .actionIcon{display:inline-block;margin-top:6px;margin-right:4px}#actionTabs .tabs .panes .pane .messageLine{text-align:center;font-size:12px;font-style:italic;opacity:0.6}#actionTabs .tabs .panes .pane .iconMessageLine{padding-left:2px;height:30px;display:grid;grid-template-columns:30px 1fr}#actionTabs .tabs .panes .pane .iconMessageLine .icon{grid-column:1;display:grid;align-items:center;justify-items:center}#actionTabs .tabs .panes .pane .iconMessageLine .value{grid-column:2;display:flex;align-items:center}#actionTabs .tabs .panes .pane .color-picker{height:calc(100% - 8px);margin:4px;width:100%}#actionTabs .tabs .panes .pane .color-picker .color-rect{height:calc(100% - 4px);border:2px white solid;cursor:pointer;min-height:18px}#actionTabs .tabs .panes .pane .color-picker .color-picker-cover{position:fixed;top:0px;right:0px;bottom:0px;left:0px;z-index:100}#actionTabs .tabs .panes .pane .color-picker .color-picker-float{position:absolute}#actionTabs .tabs .panes .pane .linkButtonLine{padding-left:2px;height:30px;display:grid;grid-template-columns:1fr auto 20px}#actionTabs .tabs .panes .pane .linkButtonLine .link{grid-column:1;display:flex;align-items:center;text-decoration:underline;cursor:pointer}#actionTabs .tabs .panes .pane .linkButtonLine .link-button{grid-column:2}#actionTabs .tabs .panes .pane .linkButtonLine .link-button button{background:#222222;border:1px solid #337ab7;margin:5px 10px 5px 10px;color:white;padding:4px 5px;opacity:0.9;cursor:pointer}#actionTabs .tabs .panes .pane .linkButtonLine .link-button button:hover{opacity:1.0}#actionTabs .tabs .panes .pane .linkButtonLine .link-button button:active{background:#282828}#actionTabs .tabs .panes .pane .linkButtonLine .link-button button:focus{border:1px solid #337ab7;outline:0px}#actionTabs .tabs .panes .pane .linkButtonLine .link-icon{grid-column:3;display:grid;align-content:center}#actionTabs .tabs .panes .pane .textLine{padding-left:2px;height:30px;display:grid;grid-template-columns:1fr auto}#actionTabs .tabs .panes .pane .textLine.indented{grid-template-columns:100%}#actionTabs .tabs .panes .pane .textLine.indented .link-value{grid-column:1;text-align:start;margin-left:20px;opacity:0.6;max-width:unset}#actionTabs .tabs .panes .pane .textLine.indented .value{grid-column:1;text-align:start;margin-left:20px;opacity:0.6;max-width:unset}#actionTabs .tabs .panes .pane .textLine.reduced-opacity{opacity:0.6;padding-left:25px}#actionTabs .tabs .panes .pane .textLine .label{grid-column:1;display:flex;align-items:center}#actionTabs .tabs .panes .pane .textLine .link-value{grid-column:2;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;text-align:end;opacity:0.8;margin:5px;margin-top:7px;max-width:140px;text-decoration:underline;cursor:pointer}#actionTabs .tabs .panes .pane .textLine .value{grid-column:2;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;text-align:end;opacity:0.8;margin:5px;margin-top:7px;max-width:200px;-webkit-user-select:text;-moz-user-select:text;-ms-user-select:text;user-select:text}#actionTabs .tabs .panes .pane .textLine .value.check{color:green}#actionTabs .tabs .panes .pane .textLine .value.uncheck{color:red}#actionTabs .tabs .panes .pane .gradient-container{margin-top:3px}#actionTabs .tabs .panes .pane .gradient-container .gradient-label{height:30px;display:grid;align-content:center}#actionTabs .tabs .panes .pane .gradient-container .gradient-step{display:grid;grid-template-rows:100%;grid-template-columns:25px 50px 55px 40px auto 20px 5px;padding-top:5px;padding-left:5px;padding-bottom:5px;align-items:center;border-left:orange 3px solid}#actionTabs .tabs .panes .pane .gradient-container .gradient-step .step{grid-row:1;grid-column:1}#actionTabs .tabs .panes .pane .gradient-container .gradient-step .color1{height:100%}#actionTabs .tabs .panes .pane .gradient-container .gradient-step .color2{height:100%;padding-left:5px}#actionTabs .tabs .panes .pane .gradient-container .gradient-step .factor1{grid-row:1;grid-column:2;cursor:pointer}#actionTabs .tabs .panes .pane .gradient-container .gradient-step .factor2{padding-left:5px;grid-row:1;grid-column:3;cursor:pointer}#actionTabs .tabs .panes .pane .gradient-container .gradient-step .factor2 .grayed{background:gray;border-color:gray}#actionTabs .tabs .panes .pane .gradient-container .gradient-step .numeric-input{width:calc(100% - 5px)}#actionTabs .tabs .panes .pane .gradient-container .gradient-step .step-value{margin-left:5px;grid-row:1;grid-column:4;text-align:right;margin-right:5px}#actionTabs .tabs .panes .pane .gradient-container .gradient-step .step-slider{grid-row:1;grid-column:5;display:grid;justify-content:stretch;align-content:center;margin-right:5px}#actionTabs .tabs .panes .pane .gradient-container .gradient-step .step-slider input{width:100%}#actionTabs .tabs .panes .pane .gradient-container .gradient-step .gradient-delete{grid-row:1;grid-column:6;display:grid;align-content:center;justify-content:center}#actionTabs .tabs .panes .pane .textInputLine{padding-left:2px;height:30px;display:grid;grid-template-columns:1fr 120px}#actionTabs .tabs .panes .pane .textInputLine .label{grid-column:1;display:flex;align-items:center}#actionTabs .tabs .panes .pane .textInputLine .value{display:flex;align-items:center;grid-column:2}#actionTabs .tabs .panes .pane .textInputLine .value input{width:110px}#actionTabs .tabs .panes .pane .buttonLine{height:30px;display:grid;align-items:center;justify-items:stretch}#actionTabs .tabs .panes .pane .buttonLine input[type=\"file\"]{display:none}#actionTabs .tabs .panes .pane .buttonLine .file-upload{background:#222222;border:1px solid #337ab7;margin:5px 10px 5px 10px;color:white;padding:4px 5px;font-size:13px;opacity:0.9;cursor:pointer;text-align:center}#actionTabs .tabs .panes .pane .buttonLine .file-upload:hover{opacity:1.0}#actionTabs .tabs .panes .pane .buttonLine .file-upload:active{transform:scale(0.98);transform-origin:0.5 0.5}#actionTabs .tabs .panes .pane .buttonLine button{background:#222222;border:1px solid #337ab7;margin:5px 10px 5px 10px;color:white;padding:4px 5px;opacity:0.9;cursor:pointer}#actionTabs .tabs .panes .pane .buttonLine button:hover{opacity:1.0}#actionTabs .tabs .panes .pane .buttonLine button:active{background:#282828}#actionTabs .tabs .panes .pane .buttonLine button:focus{border:1px solid #337ab7;outline:0px}#actionTabs .tabs .panes .pane .radioLine{padding-left:2px;height:30px;display:grid;grid-template-columns:1fr 24px}#actionTabs .tabs .panes .pane .radioLine .label{grid-column:1;display:flex;align-items:center}#actionTabs .tabs .panes .pane .radioLine .radioContainer{display:flex;align-items:center}#actionTabs .tabs .panes .pane .radioLine .radioContainer .radio{grid-column:2;display:none}#actionTabs .tabs .panes .pane .radioLine .radioContainer .radio:checked+label:before{border-color:#337ab7}#actionTabs .tabs .panes .pane .radioLine .radioContainer .radio:checked+label:after{transform:scale(1)}#actionTabs .tabs .panes .pane .radioLine .radioContainer .labelForRadio{display:inline-block;height:14px;position:relative;padding:0 24px;margin-bottom:0;cursor:pointer;vertical-align:bottom}#actionTabs .tabs .panes .pane .radioLine .radioContainer .labelForRadio:before,#actionTabs .tabs .panes .pane .radioLine .radioContainer .labelForRadio:after{position:absolute;content:'';border-radius:50%;transition:all .3s ease;transition-property:transform, border-color}#actionTabs .tabs .panes .pane .radioLine .radioContainer .labelForRadio:before{left:0px;top:0;width:16px;height:16px;border:2px solid white}#actionTabs .tabs .panes .pane .radioLine .radioContainer .labelForRadio:after{top:6px;left:6px;width:8px;height:8px;transform:scale(0);background:#337ab7}#actionTabs .tabs .panes .pane .vector3Line{padding-left:2px;display:grid}#actionTabs .tabs .panes .pane .vector3Line .firstLine{display:grid;grid-template-columns:1fr auto 20px;height:30px}#actionTabs .tabs .panes .pane .vector3Line .firstLine .label{grid-column:1;display:flex;align-items:center;white-space:nowrap;overflow:hidden}#actionTabs .tabs .panes .pane .vector3Line .firstLine .vector{grid-column:2;display:flex;align-items:center;text-align:right;opacity:0.8;padding-left:5px}#actionTabs .tabs .panes .pane .vector3Line .firstLine .expand{grid-column:3;display:grid;align-items:center;justify-items:center;cursor:pointer}#actionTabs .tabs .panes .pane .vector3Line .secondLine{display:grid;padding-right:5px;border-left:1px solid #337ab7}#actionTabs .tabs .panes .pane .vector3Line .secondLine .numeric{display:grid;grid-template-columns:1fr auto}#actionTabs .tabs .panes .pane .vector3Line .secondLine .numeric-label{text-align:right;grid-column:1;display:flex;align-items:center;justify-self:right;margin-right:10px}#actionTabs .tabs .panes .pane .vector3Line .secondLine .numeric-value{width:120px;grid-column:2;display:flex;align-items:center;border:1px solid #337ab7}#actionTabs .tabs .panes .pane .checkBoxLine{padding-left:2px;height:30px;display:grid;grid-template-columns:1fr auto}#actionTabs .tabs .panes .pane .checkBoxLine .label{grid-column:1;display:flex;align-items:center}#actionTabs .tabs .panes .pane .checkBoxLine .checkBox{grid-column:2;display:flex;align-items:center}#actionTabs .tabs .panes .pane .checkBoxLine .checkBox .lbl{position:relative;display:block;height:14px;width:34px;margin-right:5px;background:#898989;border-radius:100px;cursor:pointer;transition:all 0.3s ease}#actionTabs .tabs .panes .pane .checkBoxLine .checkBox .lbl:after{position:absolute;left:3px;top:2px;display:block;width:10px;height:10px;border-radius:100px;background:#fff;box-shadow:0px 3px 3px rgba(0,0,0,0.05);content:'';transition:all 0.15s ease}#actionTabs .tabs .panes .pane .checkBoxLine .checkBox .lbl:active:after{transform:scale(1.15, 0.85)}#actionTabs .tabs .panes .pane .checkBoxLine .checkBox .cbx:checked ~ label{background:#337ab7}#actionTabs .tabs .panes .pane .checkBoxLine .checkBox .cbx:checked ~ label:after{left:20px;background:#164975}#actionTabs .tabs .panes .pane .checkBoxLine .checkBox .hidden{display:none}#actionTabs .tabs .panes .pane .textureLine{display:grid;grid-template-rows:30px auto}#actionTabs .tabs .panes .pane .textureLine .control{margin-top:2px;grid-row:1;display:grid;grid-template-columns:1fr 40px 40px 40px 40px 40px 1fr}#actionTabs .tabs .panes .pane .textureLine .control .red{grid-column:2}#actionTabs .tabs .panes .pane .textureLine .control .green{grid-column:3}#actionTabs .tabs .panes .pane .textureLine .control .blue{grid-column:4}#actionTabs .tabs .panes .pane .textureLine .control .alpha{grid-column:5}#actionTabs .tabs .panes .pane .textureLine .control .all{grid-column:6}#actionTabs .tabs .panes .pane .textureLine .control3D{margin-top:2px;grid-row:1;display:grid;grid-template-columns:1fr 40px 40px 40px 40px 40px 40px 1fr}#actionTabs .tabs .panes .pane .textureLine .control3D .px{grid-column:2}#actionTabs .tabs .panes .pane .textureLine .control3D .nx{grid-column:3}#actionTabs .tabs .panes .pane .textureLine .control3D .py{grid-column:4}#actionTabs .tabs .panes .pane .textureLine .control3D .ny{grid-column:5}#actionTabs .tabs .panes .pane .textureLine .control3D .pz{grid-column:6}#actionTabs .tabs .panes .pane .textureLine .control3D .nz{grid-column:7}#actionTabs .tabs .panes .pane .textureLine .command{border:1px solid transparent;background:transparent;color:white}#actionTabs .tabs .panes .pane .textureLine .selected{border:1px solid #337ab7}#actionTabs .tabs .panes .pane .textureLine .preview{grid-row:2;display:grid;align-self:center;justify-self:center;height:256px;width:256px;margin-top:5px;margin-bottom:5px;border:1px solid white;background-size:32px 32px;background-color:white;background-image:url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 2 2'%3E%3Cpath fill='rgba(1.0,1.0,1.0,0.3)' fill-rule='evenodd' d='M0 0h1v1H0V0zm1 1h1v1H1V1z'/%3E%3C/svg%3E\")}#actionTabs .tabs .panes .pane .gltf-extension-property{margin-left:30px;border-left:1px solid #337ab7}#actionTabs .tabs .panes .pane .floatLine{padding-left:2px;height:30px;display:grid;grid-template-columns:1fr 120px}#actionTabs .tabs .panes .pane .floatLine .label{grid-column:1;display:flex;align-items:center}#actionTabs .tabs .panes .pane .floatLine .value{grid-column:2;display:flex;align-items:center}#actionTabs .tabs .panes .pane .floatLine .value input{width:110px}#actionTabs .tabs .panes .pane .sliderLine{padding-left:2px;height:30px;display:grid;grid-template-rows:100%;grid-template-columns:1fr 50px}#actionTabs .tabs .panes .pane .sliderLine .label{grid-column:1;display:flex;align-items:center}#actionTabs .tabs .panes .pane .sliderLine .withMargins{margin-left:5px}#actionTabs .tabs .panes .pane .sliderLine .floatLine{padding-left:2px}#actionTabs .tabs .panes .pane .sliderLine .floatLine .short{grid-column:1;display:flex;align-items:center}#actionTabs .tabs .panes .pane .sliderLine .floatLine .short input{width:35px}#actionTabs .tabs .panes .pane .sliderLine .floatLine .short input::-webkit-outer-spin-button,#actionTabs .tabs .panes .pane .sliderLine .floatLine .short input::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}#actionTabs .tabs .panes .pane .sliderLine .floatLine .short input[type=number]{-moz-appearance:textfield}#actionTabs .tabs .panes .pane .sliderLine .slider{grid-column:3;grid-row:1;margin-right:5px;width:90%;display:flex;align-items:center}#actionTabs .tabs .panes .pane .sliderLine .slider .range{-webkit-appearance:none;width:120px;height:6px;background:#d3d3d3;border-radius:5px;outline:none;opacity:0.7;-webkit-transition:.2s;transition:opacity .2s}#actionTabs .tabs .panes .pane .sliderLine .slider .range:hover{opacity:1}#actionTabs .tabs .panes .pane .sliderLine .slider .range::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:14px;height:14px;border-radius:50%;background:#337ab7;cursor:pointer}#actionTabs .tabs .panes .pane .sliderLine .slider .range::-moz-range-thumb{width:14px;height:14px;border-radius:50%;background:#337ab7;cursor:pointer}#actionTabs .tabs .panes .pane .color3Line{padding-left:2px;display:grid}#actionTabs .tabs .panes .pane .color3Line .firstLine{height:30px;display:grid;grid-template-columns:1fr auto 20px 20px}#actionTabs .tabs .panes .pane .color3Line .firstLine .label{grid-column:1;display:flex;align-items:center}#actionTabs .tabs .panes .pane .color3Line .firstLine .color3{grid-column:2;width:50px;display:flex;align-items:center}#actionTabs .tabs .panes .pane .color3Line .firstLine .color3 input[type=\"color\"]{-webkit-appearance:none;border:1px solid rgba(255,255,255,0.5);padding:0;width:30px;height:20px}#actionTabs .tabs .panes .pane .color3Line .firstLine .color3 input[type=\"color\"]::-webkit-color-swatch-wrapper{padding:0}#actionTabs .tabs .panes .pane .color3Line .firstLine .color3 input[type=\"color\"]::-webkit-color-swatch{border:none}#actionTabs .tabs .panes .pane .color3Line .firstLine .color3 input{margin-right:5px}#actionTabs .tabs .panes .pane .color3Line .firstLine .copy{grid-column:3;display:grid;align-items:center;justify-items:center;cursor:pointer}#actionTabs .tabs .panes .pane .color3Line .firstLine .copy img{height:100%}#actionTabs .tabs .panes .pane .color3Line .firstLine .expand{grid-column:4;display:grid;align-items:center;justify-items:center;cursor:pointer}#actionTabs .tabs .panes .pane .color3Line .secondLine{display:grid;padding-right:5px;border-left:1px solid #337ab7}#actionTabs .tabs .panes .pane .color3Line .secondLine .numeric{display:grid;grid-template-columns:1fr auto}#actionTabs .tabs .panes .pane .color3Line .secondLine .numeric-label{text-align:right;grid-column:1;display:flex;align-items:center;justify-self:right;margin-right:10px}#actionTabs .tabs .panes .pane .color3Line .secondLine .numeric-value{width:120px;grid-column:2;display:flex;align-items:center;border:1px solid #337ab7}#actionTabs .tabs .panes .pane .listLine{padding-left:2px;height:30px;display:grid;grid-template-columns:1fr auto}#actionTabs .tabs .panes .pane .listLine .label{grid-column:1;display:flex;align-items:center}#actionTabs .tabs .panes .pane .listLine .options{grid-column:2;display:flex;align-items:center;margin-right:5px}#actionTabs .tabs .panes .pane .listLine .options select{width:115px}#actionTabs .tabs .panes .pane .paneContainer{margin-top:3px;display:grid;grid-template-rows:100%;grid-template-columns:100%}#actionTabs .tabs .panes .pane .paneContainer .paneList{border-left:3px solid transparent}#actionTabs .tabs .panes .pane .paneContainer:hover .paneList{border-left:3px solid rgba(51,122,183,0.8)}#actionTabs .tabs .panes .pane .paneContainer:hover .paneContainer-content .header .title{border-left:3px solid #337ab7}#actionTabs .tabs .panes .pane .paneContainer .paneContainer-highlight-border{grid-row:1;grid-column:1;opacity:1;border:3px solid red;margin-bottom:-5px;z-index:100;transition:opacity 250ms;pointer-events:none}#actionTabs .tabs .panes .pane .paneContainer .paneContainer-highlight-border.transparent{opacity:0}#actionTabs .tabs .panes .pane .paneContainer .paneContainer-content{grid-row:1;grid-column:1}#actionTabs .tabs .panes .pane .paneContainer .paneContainer-content .header{display:grid;grid-template-columns:1fr auto;background:#555555;height:30px;padding-right:5px;cursor:pointer}#actionTabs .tabs .panes .pane .paneContainer .paneContainer-content .header .title{border-left:3px solid transparent;padding-left:5px;grid-column:1;display:flex;align-items:center}#actionTabs .tabs .panes .pane .paneContainer .paneContainer-content .header .collapse{grid-column:2;display:flex;align-items:center;justify-items:center;transform-origin:center}#actionTabs .tabs .panes .pane .paneContainer .paneContainer-content .header .collapse.closed{transform:rotate(180deg)}#actionTabs .tabs .panes .pane .paneContainer .paneContainer-content .paneList>div:not(:last-child){border-bottom:0.5px solid rgba(255,255,255,0.1)}#actionTabs .tabs .panes .pane .paneContainer .paneContainer-content .fragment>div:not(:last-child){border-bottom:0.5px solid rgba(255,255,255,0.1)}\n",""]),e.exports=t},function(e,t,r){var n=r(9),a=r(57);"string"==typeof(a=a.__esModule?a.default:a)&&(a=[[e.i,a,""]]);var o={insert:"head",singleton:!1};n(a,o);e.exports=a.locals||{}},function(e,t,r){(t=r(10)(!1)).push([e.i,'#scene-explorer-host{position:absolute;left:0px;top:0px;bottom:0px}#scene-explorer-host:focus{outline:none}#__resizable_base__{display:none}.context-menu{background:#222222}.context-menu .react-contextmenu-item{padding:10px;cursor:pointer}.context-menu .react-contextmenu-item:hover{background:#555555}.react-contextmenu.context-menu.react-contextmenu--visible{z-index:99;transform:scale(1)}#sceneExplorer{background:#333333;height:100%;margin:0;padding:0;display:grid;grid-template-rows:auto 1fr;font:14px "Arial"}#sceneExplorer:focus{outline:none}#sceneExplorer #header{height:30px;font-size:16px;color:white;background:#222222;grid-row:1;text-align:center;display:grid;grid-template-columns:30px 1fr 50px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}#sceneExplorer #header #logo{position:relative;grid-column:1;width:24px;height:24px;left:0;display:flex;align-self:center;justify-self:center}#sceneExplorer #header #title{grid-column:2;display:grid;align-items:center;text-align:center}#sceneExplorer #header #commands{grid-column:3;display:grid;align-items:center;grid-template-columns:1fr 1fr}#sceneExplorer #header #commands .expand{grid-column:1;display:grid;align-items:center;justify-items:center;cursor:pointer}#sceneExplorer #header #commands .close{grid-column:2;display:grid;align-items:center;justify-items:center;cursor:pointer}#sceneExplorer #tree{grid-row:2;overflow-x:hidden;overflow-y:auto}#sceneExplorer .filter{display:flex;align-items:stretch}#sceneExplorer .filter input{width:100%;margin:10px 40px 5px 40px;display:block;border:none;padding:0;border-bottom:solid 1px #337ab7;background:linear-gradient(to bottom, rgba(255,255,255,0) 96%, #337ab7 4%);background-position:-1000px 0;background-size:1000px 100%;background-repeat:no-repeat;color:white}#sceneExplorer .filter input::placeholder{color:lightgray}#sceneExplorer .filter input:focus{box-shadow:none;outline:none;background-position:0 0}#sceneExplorer .groupContainer{margin-left:0px;color:white;margin-top:0px;margin-bottom:0px;height:24px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;align-self:center;display:grid;align-items:center}#sceneExplorer .groupContainer:hover{background:#444444}#sceneExplorer .groupContainer .expandableHeader{display:grid;grid-template-columns:1fr 20px}#sceneExplorer .groupContainer .expandableHeader .text{grid-column:1;display:grid;grid-template-columns:20px 1fr}#sceneExplorer .groupContainer .expandableHeader .text .arrow{grid-column:1;margin-left:0px;color:white;cursor:pointer;display:inline-block;margin-right:6px;opacity:0.5}#sceneExplorer .groupContainer .expandableHeader .text .text-value{grid-column:2;display:flex;align-items:center}#sceneExplorer .groupContainer .expandableHeader .expandAll{opacity:0.5;grid-column:2;margin-right:10px}#sceneExplorer .icon{display:grid;align-items:center;justify-items:center;cursor:pointer}#sceneExplorer .itemContainer{margin-left:0px;color:white;margin-top:0px;margin-bottom:0px;height:24px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;display:grid;grid-template-columns:20px 1fr}#sceneExplorer .itemContainer:hover{background:#444444}#sceneExplorer .itemContainer.selected{background:#bbbbbb;color:black}#sceneExplorer .itemContainer .isNotActive{opacity:0.3}#sceneExplorer .itemContainer .arrow{grid-column:1;color:white;opacity:0.6}#sceneExplorer .itemContainer .popup{width:200px;visibility:hidden;background-color:#444444;color:#fff;border:1px solid rgba(255,255,255,0.5);position:absolute;z-index:1;margin-left:-180px;box-sizing:border-box}#sceneExplorer .itemContainer .popup.show{visibility:visible}#sceneExplorer .itemContainer .popup:focus{outline:none}#sceneExplorer .itemContainer .popup .popupMenu{padding:6px 5px 5px 10px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;height:18px}#sceneExplorer .itemContainer .popup .popupMenu:hover{background:white;color:#333333}#sceneExplorer .itemContainer .sceneNode{grid-column:2;margin-left:-10px;display:grid;grid-template-columns:1fr 20px 20px 20px 20px 10px 20px 20px auto 5px;align-items:center;cursor:pointer}#sceneExplorer .itemContainer .sceneNode .sceneTitle{grid-column:1;margin-right:5px;display:flex;align-items:center;height:24px}#sceneExplorer .itemContainer .sceneNode .translation{grid-column:2;opacity:0.6}#sceneExplorer .itemContainer .sceneNode .translation.selected{opacity:1}#sceneExplorer .itemContainer .sceneNode .rotation{grid-column:3;opacity:0.6}#sceneExplorer .itemContainer .sceneNode .rotation.selected{opacity:1}#sceneExplorer .itemContainer .sceneNode .scaling{grid-column:4;opacity:0.6}#sceneExplorer .itemContainer .sceneNode .scaling.selected{opacity:1}#sceneExplorer .itemContainer .sceneNode .bounding{grid-column:5;opacity:0.6}#sceneExplorer .itemContainer .sceneNode .bounding.selected{opacity:1}#sceneExplorer .itemContainer .sceneNode .separator{grid-column:6;margin-left:5px;width:5px;display:flex;align-items:center;height:18px;border-left:solid 1px #337ab7}#sceneExplorer .itemContainer .sceneNode .pickingMode{grid-column:7;opacity:0.6}#sceneExplorer .itemContainer .sceneNode .pickingMode.selected{opacity:1}#sceneExplorer .itemContainer .sceneNode .refresh{grid-column:8}#sceneExplorer .itemContainer .sceneNode .extensions{width:20px;grid-column:9}#sceneExplorer .itemContainer .targetedAnimationTools{grid-column:2;width:100%;display:grid;grid-template-columns:1fr auto 5px;align-items:center;min-width:0}#sceneExplorer .itemContainer .targetedAnimationTools .extensions{width:20px;grid-column:2}#sceneExplorer .itemContainer .animationGroupTools{grid-column:2;width:100%;display:grid;grid-template-columns:1fr auto 5px;align-items:center;min-width:0}#sceneExplorer .itemContainer .animationGroupTools .extensions{width:20px;grid-column:2}#sceneExplorer .itemContainer .meshTools{grid-column:2;width:100%;display:grid;grid-template-columns:1fr 20px 20px auto 5px;align-items:center;min-width:0}#sceneExplorer .itemContainer .meshTools .bounding-box{grid-column:2;opacity:0.5}#sceneExplorer .itemContainer .meshTools .bounding-box.selected{opacity:1}#sceneExplorer .itemContainer .meshTools .visibility{grid-column:3}#sceneExplorer .itemContainer .meshTools .extensions{width:20px;grid-column:4}#sceneExplorer .itemContainer .cameraTools{grid-column:2;display:grid;grid-template-columns:1fr 20px 20px auto 5px;align-items:center}#sceneExplorer .itemContainer .cameraTools .activeCamera{grid-column:2}#sceneExplorer .itemContainer .cameraTools .enableGizmo{grid-column:3}#sceneExplorer .itemContainer .cameraTools .extensions{width:20px;grid-column:4}#sceneExplorer .itemContainer .lightTools{grid-column:2;display:grid;grid-template-columns:1fr 20px 20px auto 5px;align-items:center}#sceneExplorer .itemContainer .lightTools .enableLight{grid-column:2}#sceneExplorer .itemContainer .lightTools .extensions{width:20px;grid-column:3}#sceneExplorer .itemContainer .spriteTools{grid-column:2;display:grid;grid-template-columns:1fr auto 5px;align-items:center}#sceneExplorer .itemContainer .spriteTools .extensions{width:20px;grid-column:2}#sceneExplorer .itemContainer .spriteManagerTools{grid-column:2;display:grid;grid-template-columns:1fr auto 5px;align-items:center}#sceneExplorer .itemContainer .spriteManagerTools .extensions{width:20px;grid-column:2}#sceneExplorer .itemContainer .materialTools{grid-column:2;display:grid;grid-template-columns:1fr auto 5px;align-items:center}#sceneExplorer .itemContainer .materialTools .extensions{width:20px;grid-column:2}#sceneExplorer .itemContainer .materialTools .icon{display:grid;align-items:center;justify-items:center;cursor:pointer}#sceneExplorer .itemContainer .particleSystemTools{grid-column:2;display:grid;grid-template-columns:1fr auto 5px;align-items:center}#sceneExplorer .itemContainer .particleSystemTools .extensions{width:20px;grid-column:2}#sceneExplorer .itemContainer .postProcessTools{grid-column:2;display:grid;grid-template-columns:1fr auto 5px;align-items:center}#sceneExplorer .itemContainer .postProcessTools .extensions{width:20px;grid-column:2}#sceneExplorer .itemContainer .renderingPipelineTools{grid-column:2;display:grid;grid-template-columns:1fr auto 5px;align-items:center}#sceneExplorer .itemContainer .renderingPipelineTools .extensions{width:20px;grid-column:2}#sceneExplorer .itemContainer .textureTools{grid-column:2;display:grid;grid-template-columns:1fr auto 5px;align-items:center}#sceneExplorer .itemContainer .textureTools .extensions{width:20px;grid-column:2}#sceneExplorer .itemContainer .adtextureTools{grid-column:2;display:grid;grid-template-columns:1fr 20px auto 5px;align-items:center}#sceneExplorer .itemContainer .adtextureTools .pickingMode{grid-column:2;opacity:0.6}#sceneExplorer .itemContainer .adtextureTools .pickingMode.selected{opacity:1}#sceneExplorer .itemContainer .adtextureTools .extensions{width:20px;grid-column:3}#sceneExplorer .itemContainer .controlTools{grid-column:2;display:grid;grid-template-columns:1fr 20px 20px auto 5px;align-items:center}#sceneExplorer .itemContainer .controlTools .highlight{grid-column:2}#sceneExplorer .itemContainer .controlTools .visibility{grid-column:3}#sceneExplorer .itemContainer .controlTools .extensions{width:20px;grid-column:4}#sceneExplorer .itemContainer .transformNodeTools{grid-column:2;display:grid;grid-template-columns:1fr auto 5px;align-items:center}#sceneExplorer .itemContainer .transformNodeTools .extensions{width:20px;grid-column:2}#sceneExplorer .itemContainer .skeletonTools{grid-column:2;display:grid;grid-template-columns:1fr auto 5px;align-items:center}#sceneExplorer .itemContainer .skeletonTools .extensions{width:20px;grid-column:2}#sceneExplorer .itemContainer .title{grid-column:1;background:transparent;white-space:nowrap;overflow:hidden;min-width:0;margin-right:5px;display:grid;align-items:center;grid-template-columns:25px 1fr;height:24px;cursor:pointer}#sceneExplorer .itemContainer .title .titleIcon{grid-column:1;display:grid;align-items:center;justify-items:center}#sceneExplorer .itemContainer .title .titleText{grid-column:2;white-space:nowrap;text-overflow:ellipsis;overflow:hidden}\n',""]),e.exports=t},function(e,t,r){"use strict";r.r(t);var n="undefined"!=typeof window?window:null,a=null===n,o=a?void 0:n.document,i=function(){return!1},l=a?"calc":["","-webkit-","-moz-","-o-"].filter((function(e){var t=o.createElement("div");return t.style.cssText="width:"+e+"calc(9px)",!!t.style.length})).shift()+"calc",s=function(e){return"string"==typeof e||e instanceof String},p=function(e){if(s(e)){var t=o.querySelector(e);if(!t)throw new Error("Selector "+e+" did not match a DOM element");return t}return e},c=function(e,t,r){var n=e[t];return void 0!==n?n:r},u=function(e,t,r,n){if(t){if("end"===n)return 0;if("center"===n)return e/2}else if(r){if("start"===n)return 0;if("center"===n)return e/2}return e},d=function(e,t){var r=o.createElement("div");return r.className="gutter gutter-"+t,r},h=function(e,t,r){var n={};return s(t)?n[e]=t:n[e]=l+"("+t+"% - "+r+"px)",n},b=function(e,t){var r;return(r={})[e]=t+"px",r};t.default=function(e,t){if(void 0===t&&(t={}),a)return{};var r,l,s,m,g,f,v=e;Array.from&&(v=Array.from(v));var y=p(v[0]).parentNode,C=getComputedStyle?getComputedStyle(y):null,E=C?C.flexDirection:null,O=c(t,"sizes")||v.map((function(){return 100/v.length})),S=c(t,"minSize",100),x=Array.isArray(S)?S:v.map((function(){return S})),P=c(t,"expandToMin",!1),w=c(t,"gutterSize",10),k=c(t,"gutterAlign","center"),N=c(t,"snapOffset",30),T=c(t,"dragInterval",1),_=c(t,"direction","horizontal"),M=c(t,"cursor","horizontal"===_?"col-resize":"row-resize"),L=c(t,"gutter",d),D=c(t,"elementStyle",h),R=c(t,"gutterStyle",b);function A(e,t,n,a){var o=D(r,t,n,a);Object.keys(o).forEach((function(t){e.style[t]=o[t]}))}function I(){return f.map((function(e){return e.size}))}function j(e){return"touches"in e?e.touches[0][l]:e[l]}function z(e){var t=f[this.a],r=f[this.b],n=t.size+r.size;t.size=e/this.size*n,r.size=n-e/this.size*n,A(t.element,t.size,this._b,t.i),A(r.element,r.size,this._c,r.i)}function F(e){var r,n=f[this.a],a=f[this.b];this.dragging&&(r=j(e)-this.start+(this._b-this.dragOffset),T>1&&(r=Math.round(r/T)*T),r<=n.minSize+N+this._b?r=n.minSize+this._b:r>=this.size-(a.minSize+N+this._c)&&(r=this.size-(a.minSize+this._c)),z.call(this,r),c(t,"onDrag",i)(I()))}function G(){var e=f[this.a].element,t=f[this.b].element,n=e.getBoundingClientRect(),a=t.getBoundingClientRect();this.size=n[r]+a[r]+this._b+this._c,this.start=n[s],this.end=n[m]}function V(e){var t=function(e){if(!getComputedStyle)return null;var t=getComputedStyle(e);if(!t)return null;var r=e[g];return 0===r?null:r-="horizontal"===_?parseFloat(t.paddingLeft)+parseFloat(t.paddingRight):parseFloat(t.paddingTop)+parseFloat(t.paddingBottom)}(y);if(null===t)return e;if(x.reduce((function(e,t){return e+t}),0)>t)return e;var r=0,n=[],a=e.map((function(a,o){var i=t*a/100,l=u(w,0===o,o===e.length-1,k),s=x[o]+l;return i<s?(r+=s-i,n.push(0),s):(n.push(i-s),i)}));return 0===r?e:a.map((function(e,a){var o=e;if(r>0&&n[a]-r>0){var i=Math.min(r,n[a]-r);r-=i,o=e-i}return o/t*100}))}function U(){var e=f[this.a].element,r=f[this.b].element;this.dragging&&c(t,"onDragEnd",i)(I()),this.dragging=!1,n.removeEventListener("mouseup",this.stop),n.removeEventListener("touchend",this.stop),n.removeEventListener("touchcancel",this.stop),n.removeEventListener("mousemove",this.move),n.removeEventListener("touchmove",this.move),this.stop=null,this.move=null,e.removeEventListener("selectstart",i),e.removeEventListener("dragstart",i),r.removeEventListener("selectstart",i),r.removeEventListener("dragstart",i),e.style.userSelect="",e.style.webkitUserSelect="",e.style.MozUserSelect="",e.style.pointerEvents="",r.style.userSelect="",r.style.webkitUserSelect="",r.style.MozUserSelect="",r.style.pointerEvents="",this.gutter.style.cursor="",this.parent.style.cursor="",o.body.style.cursor=""}function H(e){if(!("button"in e)||0===e.button){var r=f[this.a].element,a=f[this.b].element;this.dragging||c(t,"onDragStart",i)(I()),e.preventDefault(),this.dragging=!0,this.move=F.bind(this),this.stop=U.bind(this),n.addEventListener("mouseup",this.stop),n.addEventListener("touchend",this.stop),n.addEventListener("touchcancel",this.stop),n.addEventListener("mousemove",this.move),n.addEventListener("touchmove",this.move),r.addEventListener("selectstart",i),r.addEventListener("dragstart",i),a.addEventListener("selectstart",i),a.addEventListener("dragstart",i),r.style.userSelect="none",r.style.webkitUserSelect="none",r.style.MozUserSelect="none",r.style.pointerEvents="none",a.style.userSelect="none",a.style.webkitUserSelect="none",a.style.MozUserSelect="none",a.style.pointerEvents="none",this.gutter.style.cursor=M,this.parent.style.cursor=M,o.body.style.cursor=M,G.call(this),this.dragOffset=j(e)-this.end}}"horizontal"===_?(r="width",l="clientX",s="left",m="right",g="clientWidth"):"vertical"===_&&(r="height",l="clientY",s="top",m="bottom",g="clientHeight"),O=V(O);var B=[];function W(e){var t=e.i===B.length,r=t?B[e.i-1]:B[e.i];G.call(r);var n=t?r.size-e.minSize-r._c:e.minSize+r._b;z.call(r,n)}return(f=v.map((function(e,t){var n,a={element:p(e),size:O[t],minSize:x[t],i:t};if(t>0&&((n={a:t-1,b:t,dragging:!1,direction:_,parent:y})._b=u(w,t-1==0,!1,k),n._c=u(w,!1,t===v.length-1,k),"row-reverse"===E||"column-reverse"===E)){var o=n.a;n.a=n.b,n.b=o}if(t>0){var i=L(t,_,a.element);!function(e,t,n){var a=R(r,t,n);Object.keys(a).forEach((function(t){e.style[t]=a[t]}))}(i,w,t),n._a=H.bind(n),i.addEventListener("mousedown",n._a),i.addEventListener("touchstart",n._a),y.insertBefore(i,a.element),n.gutter=i}return A(a.element,a.size,u(w,0===t,t===v.length-1,k),t),t>0&&B.push(n),a}))).forEach((function(e){var t=e.element.getBoundingClientRect()[r];t<e.minSize&&(P?W(e):e.minSize=t)})),{setSizes:function(e){var t=V(e);t.forEach((function(e,r){if(r>0){var n=B[r-1],a=f[n.a],o=f[n.b];a.size=t[r-1],o.size=e,A(a.element,a.size,n._b,a.i),A(o.element,o.size,n._c,o.i)}}))},getSizes:I,collapse:function(e){W(f[e])},destroy:function(e,t){B.forEach((function(n){if(!0!==t?n.parent.removeChild(n.gutter):(n.gutter.removeEventListener("mousedown",n._a),n.gutter.removeEventListener("touchstart",n._a)),!0!==e){var a=D(r,n.a.size,n._b);Object.keys(a).forEach((function(e){f[n.a].element.style[e]="",f[n.b].element.style[e]=""}))}}))},parent:y,pairs:B}}},function(e,t,r){var n=r(9),a=r(60);"string"==typeof(a=a.__esModule?a.default:a)&&(a=[[e.i,a,""]]);var o={insert:"head",singleton:!1};n(a,o);e.exports=a.locals||{}},function(e,t,r){(t=r(10)(!1)).push([e.i,'#embed-host{position:absolute;right:0px;top:0px;bottom:0px;z-index:10}#__resizable_base__{display:none}#embed{background:#333333;height:100%;margin:0;padding:0;display:grid;grid-template-rows:30px 1fr;font:14px "Arial";overflow:hidden}#embed #header{font-size:16px;color:white;background:#222222;grid-row:1;text-align:center;display:grid;grid-template-columns:30px 1fr 50px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}#embed #header #logo{grid-column:1;width:24px;height:24px;display:flex;align-self:center;justify-self:center}#embed #header #back{grid-column:1;display:grid;align-self:center;justify-self:center;cursor:pointer}#embed #header #title{grid-column:2;display:grid;align-items:center;text-align:center}#embed #header #commands{grid-column:3;display:grid;align-items:center;grid-template-columns:1fr 1fr}#embed #header #commands .expand{grid-column:1;display:grid;align-items:center;justify-items:center;cursor:pointer}#embed #header #commands .close{grid-column:2;display:grid;align-items:center;justify-items:center;cursor:pointer}#embed #split{grid-row:2;overflow:hidden}#embed #split.splitPopup{display:grid;grid-template-rows:300px 2px 1fr}#embed #split.splitPopup .panes{margin-bottom:1px}#embed #split #topPart{grid-row:1;overflow:hidden;display:grid;grid-auto-rows:100%}#embed #split #separator{grid-row:2;background:white;opacity:0.1}#embed #split #bottomPart{overflow:hidden;grid-row:3;display:grid;grid-auto-rows:100%}#embed #split .gutter.gutter-vertical{background-image:none;background:#444444;cursor:row-resize}\n',""]),e.exports=t}])}));
packages/mineral-ui-icons/src/IconGpsNotFixed.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconGpsNotFixed(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M20.94 11A8.994 8.994 0 0 0 13 3.06V1h-2v2.06A8.994 8.994 0 0 0 3.06 11H1v2h2.06A8.994 8.994 0 0 0 11 20.94V23h2v-2.06A8.994 8.994 0 0 0 20.94 13H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/> </g> </Icon> ); } IconGpsNotFixed.displayName = 'IconGpsNotFixed'; IconGpsNotFixed.category = 'device';
src/components/App.js
wdavew/king-pong
import React, { Component } from 'react'; import Leaderboard from './Leaderboard.js'; import LeagueList from './LeagueList.js'; import Login from './Login.js'; import Signup from './Signup.js'; import LeagueForm from './LeagueForm.js'; require('../static/mainstyle.css'); import { Router, Route, Link, browserHistory } from 'react-router' class App extends Component { constructor() { super(); this.state = { isLoggedIn: false, username: '', password: '', newUser: '', newPassword: '', newLeague: '', leagues: [], activeLeague: '', selectedLeague: '', } this.handleLoginSubmit = this.handleLoginSubmit.bind(this); this.handleInputTextChange = this.handleInputTextChange.bind(this); this.enterLeague = this.enterLeague.bind(this); this.postUserData = this.postUserData.bind(this); this.postLeagueData = this.postLeagueData.bind(this); this.joinLeague = this.joinLeague.bind(this); } syncLeagues() { fetch('/data/getAllLeagues/leagues', { method: 'get' }) .then(response => response.json()) .then((jsonLeagueData) => { this.setState({ allLeagues: jsonLeagueData, }) }) } componentDidMount() { console.log('app has mounted and is requesting available leagues'); this.syncLeagues(); } handleInputTextChange(event, stateKey) { console.log(this.state.selectedLeague); const newState = {}; newState[stateKey] = event.target.value; this.setState(newState); } enterLeague(league) { this.setState({ activeLeague: league, isLoggedIn: true, }); } joinLeague(e) { e.preventDefault(); fetch('/data/leagues/join', { method: 'POST', body: JSON.stringify({ username: this.state.username, league: this.state.selectedLeague }), headers: new Headers({ 'Content-Type': 'application/json' }) }).then(() => this.refreshUserLeagues()); } postUserData(e) { e.preventDefault(); const {newUser, newPassword } = this.state; fetch('/data/createNewUser/newUser', { method: 'POST', body: JSON.stringify({ username: newUser, password: newPassword }), headers: new Headers({ 'Content-Type': 'application/json' }) }); } postLeagueData(e) { console.log("posting league data"); e.preventDefault(); fetch('/data/createNewLeague/newLeague', { method: 'POST', body: JSON.stringify({ league: this.state.newLeague }), headers: new Headers({ 'Content-Type': 'application/json' }) }).then(() => this.syncLeagues()); } handleLoginSubmit(e) { e.preventDefault(); fetch(`/data/userLeagues/${this.state.username}`, { method: 'get' }) .then(response => response.json()) .then((jsonData) => { const leagues = jsonData.map(obj => obj.league); this.setState({ leagues: leagues, isLoggedIn: true }) }) } refreshUserLeagues() { fetch(`/data/userLeagues/${this.state.username}`, { method: 'get' }) .then(response => response.json()) .then(jsonData => this.setState({ leagues: jsonData.map(obj => obj.league) })); } render() { const leagues = !this.state.activeLeague && this.state.isLoggedIn ? <LeagueList leagues={this.state.leagues} enterLeague={this.enterLeague} /> : null; const leaderboard = this.state.activeLeague ? <Leaderboard league={this.state.activeLeague} username={this.state.username} /> : null; const login = !this.state.isLoggedIn ? <Login submitLogin={this.handleLoginSubmit} handleInputTextChange={(e) => this.handleInputTextChange(e, 'username')} /> : null; const signup = !this.state.isLoggedIn ? <Signup submit={this.postUserData} handleInputTextChange={this.handleInputTextChange} /> : null; const leagueForm = this.state.isLoggedIn && !this.state.activeLeague ? <LeagueForm chooseLeague={this.joinLeague} submit={this.postLeagueData} joinLeague={this.joinLeague} leagues={this.state.allLeagues} handleInputTextChange={this.handleInputTextChange} /> : null; return ( <div className='container-fluid body-container'> {login} {leagues} {signup} {leagueForm} {leaderboard} </div> ) } }; export default App;
static/src/components/islands/IslandTrees.js
taylorsmcclure/airhornbot-dev
// @flow // jscs:disable maximumLineLength import React from 'react'; type Props = { paused: boolean }; export default ({paused}: Props): React.Element => ( <svg className={`island trees ${paused ? 'paused' : ''}`} xmlns="http://www.w3.org/2000/svg" width="259px" height="276px" viewBox="0 0 259 276"> <g fill="none" fill-rule="evenodd"> <path fill="#FFE6A7" d="M1.5012 148.2279v57.903l118.413 68.367 136.734-78.942v-57.903l-255.147 10.575z"/> <path fill="#EDD194" d="M118.8135 143.3652v130.5l1.101.633 136.734-78.942v-57.903l-137.835 5.712z"/> <path stroke="#5E4634" strokeWidth="3" d="M256.6494 137.6514v57.906l-136.734 78.942-118.416-68.367v-57.906" strokeLinecap="round" strokeLinejoin="round"/> <path fill="#C7E082" d="M1.5012 148.2279v20.403l118.413 68.37 136.734-78.945v-20.403l-255.147 10.575z"/> <path fill="#B0CC64" d="M119.8134 143.3235v93.618l.102.06 136.734-78.945v-20.406l-136.836 5.673z"/> <path stroke="#5E4634" strokeWidth="3" d="M256.6494 140.6514v17.406l-136.734 78.942-118.416-68.367v-20.406" strokeLinecap="round" strokeLinejoin="round"/> <path fill="#B7D86F" d="M1.5012 148.2279l118.413 68.367 136.734-78.942-118.413-68.367-136.734 78.942z"/> <path stroke="#5E4634" strokeWidth="3" d="M119.9151 216.5949l-118.416-68.367 136.734-78.945 118.416 68.37-136.734 78.942zm0 0v57.906" strokeLinecap="round" strokeLinejoin="round"/> <g className="leaves"> <path fill="#C3F270" d="M143.9334 29.8173l-.003-.003v-.006c.69-6.153 7.671-9.375 12.801-5.907l.003.003v.006c-.69 6.156-7.671 9.375-12.801 5.907"/> <path stroke="#5E4634" strokeWidth="3" d="M143.9334 29.8173l-.003-.003v-.006c.69-6.153 7.671-9.375 12.801-5.907l.003.003v.006c-.69 6.156-7.671 9.375-12.801 5.907z" strokeLinecap="round" strokeLinejoin="round"/> <path fill="#C3F270" d="M164.8071 3.9903v-.006l.003-.003c4.515-4.236 11.916-2.163 13.575 3.804v.003l-.003.006c-4.515 4.236-11.916 2.163-13.575-3.804"/> <path stroke="#5E4634" strokeWidth="3" d="M164.8071 3.9903v-.006l.003-.003c4.515-4.236 11.916-2.163 13.575 3.804v.003l-.003.006c-4.515 4.236-11.916 2.163-13.575-3.804z" strokeLinecap="round" strokeLinejoin="round"/> <path fill="#C3F270" d="M230.3529 109.9143l-.006-.003v-.006c-.099-6.192 6.414-10.275 11.943-7.491l.006.003v.006c.099 6.192-6.411 10.275-11.943 7.491"/> <path stroke="#5E4634" strokeWidth="3" d="M230.3529 109.9143l-.006-.003v-.006c-.099-6.192 6.414-10.275 11.943-7.491l.006.003v.006c.099 6.192-6.411 10.275-11.943 7.491z" strokeLinecap="round" strokeLinejoin="round"/> </g> <path fill="#FFE6A7" d="M91.9257 130.8846v26.625c0 2.691 5.289 4.875 11.814 4.875 6.522 0 11.811-2.184 11.811-4.875v-26.625h-23.625z"/> <path fill="#EDD194" d="M103.8012 130.8846v31.497c6.495-.015 11.751-2.19 11.751-4.872v-26.625h-11.751z"/> <path stroke="#5E4634" strokeWidth="3" d="M91.9257 130.8846v26.625c0 2.691 5.289 4.875 11.814 4.875 6.522 0 11.811-2.184 11.811-4.875v-26.625h-23.625z" strokeLinecap="round" strokeLinejoin="round"/> <path stroke="#5E4634" strokeWidth="3" d="M178.3866 112.875zm13.0602 5.5353v3.249M40.1967 137.6514v3.249m75.354 57.9306v3.249m7.5582-9.0015v3.249m0-43.9992v3.249m-38.412-6.4989v3.249m-5.5002.0009v3.249m-51-28.8738v5.523m-4.875-2.3982v5.523m173.3751-16.023v3.75" strokeLinecap="round" strokeLinejoin="round"/> <g className="stretch"> <path fill="#C3F270" d="M109.3728 25.3635l36.129 98.73c1.719 4.695.099 10.05-4.092 12.777-6.051 3.939-17.328 8.265-37.671 8.265s-31.62-4.326-37.671-8.265c-4.191-2.727-5.814-8.082-4.095-12.777l36.132-98.73c1.92-5.25 9.348-5.25 11.268 0"/> <path fill="#B7D86F" d="M145.5027 124.0935l-36.129-98.73c-1.923-5.25-9.348-5.25-11.271 0l-2.88 7.875 31.239 85.365c1.719 4.695.099 10.05-4.095 12.777-6.051 3.939-17.328 8.265-37.671 8.265-5.913 0-11.043-.375-15.519-.99 6.552 3.354 17.274 6.48 34.56 6.48 20.343 0 31.62-4.326 37.671-8.265 4.194-2.727 5.814-8.082 4.095-12.777"/> <path stroke="#5E4634" strokeWidth="3" d="M109.3728 25.3635l36.129 98.73c1.719 4.695.099 10.05-4.092 12.777-6.051 3.939-17.328 8.265-37.671 8.265s-31.62-4.326-37.671-8.265c-4.191-2.727-5.814-8.082-4.095-12.777l36.132-98.73c1.92-5.25 9.348-5.25 11.268 0z" strokeLinecap="round" strokeLinejoin="round"/> </g> <path fill="#FFE6A7" d="M172.7298 96.9837v29.784c0 1.29 2.532 2.334 5.658 2.334 3.123 0 5.655-1.044 5.655-2.334v-29.784h-11.313z"/> <path fill="#EDD194" d="M178.8012 96.9837v32.103c2.928-.09 5.241-1.089 5.241-2.319v-29.784h-5.241z"/> <path stroke="#5E4634" strokeWidth="3" d="M172.7298 96.9837v29.784c0 1.29 2.532 2.334 5.658 2.334 3.123 0 5.655-1.044 5.655-2.334v-29.784h-11.313z" strokeLinecap="round" strokeLinejoin="round"/> <g className="stretch"> <path fill="#C3F270" d="M178.3866 117.543c-14.232 0-25.875-11.643-25.875-25.875v-9.327c0-14.232 11.643-25.875 25.875-25.875s25.875 11.643 25.875 25.875v9.327c0 14.232-11.643 25.875-25.875 25.875"/> <path fill="#B7D86F" d="M179.9904 56.5479c5.655 4.755 9.27 11.871 9.27 19.794v9.327c0 14.232-11.643 25.875-25.875 25.875-.54 0-1.068-.048-1.602-.081 4.503 3.786 10.296 6.081 16.602 6.081 14.232 0 25.875-11.643 25.875-25.875v-9.327c0-13.692-10.782-24.954-24.27-25.794"/> <path stroke="#5E4634" strokeWidth="3" d="M178.3866 117.543c-14.232 0-25.875-11.643-25.875-25.875v-9.327c0-14.232 11.643-25.875 25.875-25.875s25.875 11.643 25.875 25.875v9.327c0 14.232-11.643 25.875-25.875 25.875z" strokeLinecap="round" strokeLinejoin="round"/> </g> <path fill="#EBEBEB" d="M157.9878 164.9463h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338"/> <path stroke="#5E4634" strokeWidth="3" d="M157.9878 164.9463h-6.684c-.735 0-1.335-.6-1.335-1.338v-.555c0-1.776 1.452-3.231 3.231-3.231h2.895c1.776 0 3.231 1.455 3.231 3.231v.555c0 .738-.603 1.338-1.338 1.338z" strokeLinecap="round" strokeLinejoin="round"/> <g className="lines"> <path stroke="#5E4634" strokeWidth="3" d="M132.5016 45.2829c7.356 2.253 15.573 1.536 22.428-1.953s12.267-9.714 14.775-16.983m-66.4152 13.3812c-5.976-4.326-13.56-5.736-20.913-6.324-8.142-.651-16.479-.417-24.258 2.064-7.782 2.481-15.003 7.404-19.056 14.493-4.056 7.089-4.488 16.443-.036 23.289 5.172 7.95 15.288 10.953 24.678 12.303" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="6 12"/> </g> </g> </svg> );
ajax/libs/react-router/0.6.1/react-router.js
athanclark/cdnjs
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.ReactRouter=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){ module.exports = _dereq_('./modules/mixins/ActiveState'); },{"./modules/mixins/ActiveState":33}],2:[function(_dereq_,module,exports){ module.exports = _dereq_('./modules/mixins/AsyncState'); },{"./modules/mixins/AsyncState":34}],3:[function(_dereq_,module,exports){ module.exports = _dereq_('./modules/components/DefaultRoute'); },{"./modules/components/DefaultRoute":13}],4:[function(_dereq_,module,exports){ module.exports = _dereq_('./modules/components/Link'); },{"./modules/components/Link":14}],5:[function(_dereq_,module,exports){ module.exports = _dereq_('./modules/components/NotFoundRoute'); },{"./modules/components/NotFoundRoute":15}],6:[function(_dereq_,module,exports){ module.exports = _dereq_('./modules/components/Redirect'); },{"./modules/components/Redirect":16}],7:[function(_dereq_,module,exports){ module.exports = _dereq_('./modules/components/Route'); },{"./modules/components/Route":17}],8:[function(_dereq_,module,exports){ module.exports = _dereq_('./modules/components/Routes'); },{"./modules/components/Routes":18}],9:[function(_dereq_,module,exports){ module.exports = _dereq_('./modules/actions/LocationActions').goBack; },{"./modules/actions/LocationActions":12}],10:[function(_dereq_,module,exports){ exports.ActiveState = _dereq_('./ActiveState'); exports.AsyncState = _dereq_('./AsyncState'); exports.DefaultRoute = _dereq_('./DefaultRoute'); exports.Link = _dereq_('./Link'); exports.NotFoundRoute = _dereq_('./NotFoundRoute'); exports.Redirect = _dereq_('./Redirect'); exports.Route = _dereq_('./Route'); exports.Routes = _dereq_('./Routes'); exports.goBack = _dereq_('./goBack'); exports.makeHref = _dereq_('./makeHref'); exports.replaceWith = _dereq_('./replaceWith'); exports.transitionTo = _dereq_('./transitionTo'); },{"./ActiveState":1,"./AsyncState":2,"./DefaultRoute":3,"./Link":4,"./NotFoundRoute":5,"./Redirect":6,"./Route":7,"./Routes":8,"./goBack":9,"./makeHref":11,"./replaceWith":62,"./transitionTo":63}],11:[function(_dereq_,module,exports){ module.exports = _dereq_('./modules/helpers/makeHref'); },{"./modules/helpers/makeHref":25}],12:[function(_dereq_,module,exports){ var LocationDispatcher = _dereq_('../dispatchers/LocationDispatcher'); var makePath = _dereq_('../helpers/makePath'); /** * Actions that modify the URL. */ var LocationActions = { PUSH: 'push', REPLACE: 'replace', POP: 'pop', UPDATE_SCROLL: 'update-scroll', /** * Transitions to the URL specified in the arguments by pushing * a new URL onto the history stack. */ transitionTo: function (to, params, query) { LocationDispatcher.handleViewAction({ type: LocationActions.PUSH, path: makePath(to, params, query) }); }, /** * Transitions to the URL specified in the arguments by replacing * the current URL in the history stack. */ replaceWith: function (to, params, query) { LocationDispatcher.handleViewAction({ type: LocationActions.REPLACE, path: makePath(to, params, query) }); }, /** * Transitions to the previous URL. */ goBack: function () { LocationDispatcher.handleViewAction({ type: LocationActions.POP }); }, /** * Updates the window's scroll position to the last known position * for the current URL path. */ updateScroll: function () { LocationDispatcher.handleViewAction({ type: LocationActions.UPDATE_SCROLL }); } }; module.exports = LocationActions; },{"../dispatchers/LocationDispatcher":19,"../helpers/makePath":26}],13:[function(_dereq_,module,exports){ var merge = _dereq_('react/lib/merge'); var Route = _dereq_('./Route'); /** * A <DefaultRoute> component is a special kind of <Route> that * renders when its parent matches but none of its siblings do. * Only one such route may be used at any given level in the * route hierarchy. */ function DefaultRoute(props) { return Route( merge(props, { path: null, isDefault: true }) ); } module.exports = DefaultRoute; },{"./Route":17,"react/lib/merge":52}],14:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); var ActiveState = _dereq_('../mixins/ActiveState'); var transitionTo = _dereq_('../actions/LocationActions').transitionTo; var withoutProperties = _dereq_('../helpers/withoutProperties'); var hasOwnProperty = _dereq_('../helpers/hasOwnProperty'); var makeHref = _dereq_('../helpers/makeHref'); var warning = _dereq_('react/lib/warning'); function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } /** * DEPRECATED: A map of <Link> component props that are reserved for use by the * router and/or React. All other props are used as params that are * interpolated into the link's path. */ var RESERVED_PROPS = { to: true, key: true, className: true, activeClassName: true, query: true, onClick:true, children: true // ReactChildren }; /** * <Link> components are used to create an <a> element that links to a route. * When that route is active, the link gets an "active" class name (or the * value of its `activeClassName` prop). * * For example, assuming you have the following route: * * <Route name="showPost" path="/posts/:postId" handler={Post}/> * * You could use the following component to link to that route: * * <Link to="showPost" params={{postId: "123"}} /> * * In addition to params, links may pass along query string parameters * using the `query` prop. * * <Link to="showPost" params={{postId: "123"}} query={{show:true}}/> */ var Link = React.createClass({ displayName: 'Link', mixins: [ ActiveState ], statics: { // TODO: Deprecate passing props as params in v1.0 getUnreservedProps: function (props) { var props = withoutProperties(props, RESERVED_PROPS); warning( Object.keys(props).length === 0, 'Passing props for params on <Link>s is deprecated, '+ 'please use the `params` property.' ); return props; }, /** * Returns a hash of URL parameters to use in this <Link>'s path. */ getParams: function (props) { return props.params || Link.getUnreservedProps(props); } }, propTypes: { to: React.PropTypes.string.isRequired, activeClassName: React.PropTypes.string.isRequired, params: React.PropTypes.object, query: React.PropTypes.object, onClick: React.PropTypes.func }, getDefaultProps: function () { return { activeClassName: 'active' }; }, getInitialState: function () { return { isActive: false }; }, /** * Returns the value of the "href" attribute to use on the DOM element. */ getHref: function () { return makeHref(this.props.to, Link.getParams(this.props), this.props.query); }, /** * Returns the value of the "class" attribute to use on the DOM element, which contains * the value of the activeClassName property when this <Link> is active. */ getClassName: function () { var className = this.props.className || ''; if (this.state.isActive) return className + ' ' + this.props.activeClassName; return className; }, componentWillReceiveProps: function (nextProps) { var params = Link.getParams(nextProps); this.setState({ isActive: Link.isActive(nextProps.to, params, nextProps.query) }); }, updateActiveState: function () { this.setState({ isActive: Link.isActive(this.props.to, Link.getParams(this.props), this.props.query) }); }, handleClick: function (event) { var allowTransition = true; var ret; if (this.props.onClick) ret = this.props.onClick(event); if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; if (ret === false || event.defaultPrevented === true) allowTransition = false; event.preventDefault(); if (allowTransition) transitionTo(this.props.to, Link.getParams(this.props), this.props.query); }, render: function () { var props = { href: this.getHref(), className: this.getClassName(), onClick: this.handleClick }; // pull in props without overriding for (var propName in this.props) { if (hasOwnProperty(this.props, propName) && hasOwnProperty(props, propName) === false) props[propName] = this.props[propName]; } return React.DOM.a(props, this.props.children); } }); module.exports = Link; },{"../actions/LocationActions":12,"../helpers/hasOwnProperty":24,"../helpers/makeHref":25,"../helpers/withoutProperties":29,"../mixins/ActiveState":33,"react/lib/warning":56}],15:[function(_dereq_,module,exports){ var merge = _dereq_('react/lib/merge'); var Route = _dereq_('./Route'); /** * A <NotFoundRoute> is a special kind of <Route> that * renders when the beginning of its parent's path matches * but none of its siblings do, including any <DefaultRoute>. * Only one such route may be used at any given level in the * route hierarchy. */ function NotFoundRoute(props) { return Route( merge(props, { path: null, catchAll: true }) ); } module.exports = NotFoundRoute; },{"./Route":17,"react/lib/merge":52}],16:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); var Route = _dereq_('./Route'); function createRedirectHandler(to) { return React.createClass({ statics: { willTransitionTo: function (transition, params, query) { transition.redirect(to, params, query); } }, render: function () { return null; } }); } /** * A <Redirect> component is a special kind of <Route> that always * redirects to another route when it matches. */ function Redirect(props) { return Route({ name: props.name, path: props.from || props.path || '*', handler: createRedirectHandler(props.to) }); } module.exports = Redirect; },{"./Route":17}],17:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); var withoutProperties = _dereq_('../helpers/withoutProperties'); /** * A map of <Route> component props that are reserved for use by the * router and/or React. All other props are considered "static" and * are passed through to the route handler. */ var RESERVED_PROPS = { handler: true, path: true, defaultRoute: true, paramNames: true, children: true // ReactChildren }; /** * <Route> components specify components that are rendered to the page when the * URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is requested, * the tree is searched depth-first to find a route whose path matches the URL. * When one is found, all routes in the tree that lead to it are considered * "active" and their components are rendered into the DOM, nested in the same * order as they are in the tree. * * Unlike Ember, a nested route's path does not build upon that of its parents. * This may seem like it creates more work up front in specifying URLs, but it * has the nice benefit of decoupling nested UI from "nested" URLs. * * The preferred way to configure a router is using JSX. The XML-like syntax is * a great way to visualize how routes are laid out in an application. * * React.renderComponent(( * <Routes handler={App}> * <Route name="login" handler={Login}/> * <Route name="logout" handler={Logout}/> * <Route name="about" handler={About}/> * </Routes> * ), document.body); * * If you don't use JSX, you can also assemble a Router programmatically using * the standard React component JavaScript API. * * React.renderComponent(( * Routes({ handler: App }, * Route({ name: 'login', handler: Login }), * Route({ name: 'logout', handler: Logout }), * Route({ name: 'about', handler: About }) * ) * ), document.body); * * Handlers for Route components that contain children can render their active * child route using the activeRouteHandler prop. * * var App = React.createClass({ * render: function () { * return ( * <div class="application"> * {this.props.activeRouteHandler()} * </div> * ); * } * }); */ var Route = React.createClass({ displayName: 'Route', statics: { getUnreservedProps: function (props) { return withoutProperties(props, RESERVED_PROPS); }, }, propTypes: { preserveScrollPosition: React.PropTypes.bool.isRequired, handler: React.PropTypes.any.isRequired, path: React.PropTypes.string, name: React.PropTypes.string }, getDefaultProps: function () { return { preserveScrollPosition: false }; }, render: function () { throw new Error( 'The <Route> component should not be rendered directly. You may be ' + 'missing a <Routes> wrapper around your list of routes.' ); } }); module.exports = Route; },{"../helpers/withoutProperties":29}],18:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); var warning = _dereq_('react/lib/warning'); var copyProperties = _dereq_('react/lib/copyProperties'); var Promise = _dereq_('when/lib/Promise'); var LocationActions = _dereq_('../actions/LocationActions'); var Route = _dereq_('../components/Route'); var Path = _dereq_('../helpers/Path'); var Redirect = _dereq_('../helpers/Redirect'); var Transition = _dereq_('../helpers/Transition'); var HashLocation = _dereq_('../locations/HashLocation'); var HistoryLocation = _dereq_('../locations/HistoryLocation'); var RefreshLocation = _dereq_('../locations/RefreshLocation'); var ActiveStore = _dereq_('../stores/ActiveStore'); var PathStore = _dereq_('../stores/PathStore'); var RouteStore = _dereq_('../stores/RouteStore'); /** * The ref name that can be used to reference the active route component. */ var REF_NAME = '__activeRoute__'; /** * A hash of { name, location } pairs of all locations. */ var NAMED_LOCATIONS = { hash: HashLocation, history: HistoryLocation, refresh: RefreshLocation }; /** * The default handler for aborted transitions. Redirects replace * the current URL and all others roll it back. */ function defaultAbortedTransitionHandler(transition) { var reason = transition.abortReason; if (reason instanceof Redirect) { LocationActions.replaceWith(reason.to, reason.params, reason.query); } else { LocationActions.goBack(); } } /** * The default handler for active state updates. */ function defaultActiveStateChangeHandler(state) { ActiveStore.updateState(state); } /** * The default handler for errors that were thrown asynchronously * while transitioning. The default behavior is to re-throw the * error so that it isn't silently swallowed. */ function defaultTransitionErrorHandler(error) { throw error; // This error probably originated in a transition hook. } function maybeUpdateScroll(routes, rootRoute) { if (!routes.props.preserveScrollPosition && !rootRoute.props.preserveScrollPosition) LocationActions.updateScroll(); } /** * The <Routes> component configures the route hierarchy and renders the * route matching the current location when rendered into a document. * * See the <Route> component for more details. */ var Routes = React.createClass({ displayName: 'Routes', propTypes: { onAbortedTransition: React.PropTypes.func.isRequired, onActiveStateChange: React.PropTypes.func.isRequired, onTransitionError: React.PropTypes.func.isRequired, preserveScrollPosition: React.PropTypes.bool, location: function (props, propName, componentName) { var location = props[propName]; if (typeof location === 'string' && !(location in NAMED_LOCATIONS)) return new Error('Unknown location "' + location + '", see ' + componentName); } }, getDefaultProps: function () { return { onAbortedTransition: defaultAbortedTransitionHandler, onActiveStateChange: defaultActiveStateChangeHandler, onTransitionError: defaultTransitionErrorHandler, preserveScrollPosition: false, location: HashLocation }; }, getInitialState: function () { return { routes: RouteStore.registerChildren(this.props.children, this) }; }, getLocation: function () { var location = this.props.location; if (typeof location === 'string') return NAMED_LOCATIONS[location]; return location; }, componentWillMount: function () { PathStore.setup(this.getLocation()); PathStore.addChangeListener(this.handlePathChange); }, componentDidMount: function () { this.handlePathChange(); }, componentWillUnmount: function () { PathStore.removeChangeListener(this.handlePathChange); }, handlePathChange: function () { this.dispatch(PathStore.getCurrentPath()); }, /** * Performs a depth-first search for the first route in the tree that matches * on the given path. Returns an array of all routes in the tree leading to * the one that matched in the format { route, params } where params is an * object that contains the URL parameters relevant to that route. Returns * null if no route in the tree matches the path. * * React.renderComponent( * <Routes> * <Route handler={App}> * <Route name="posts" handler={Posts}/> * <Route name="post" path="/posts/:id" handler={Post}/> * </Route> * </Routes> * ).match('/posts/123'); => [ { route: <AppRoute>, params: {} }, * { route: <PostRoute>, params: { id: '123' } } ] */ match: function (path) { return findMatches(Path.withoutQuery(path), this.state.routes, this.props.defaultRoute, this.props.notFoundRoute); }, /** * Performs a transition to the given path and returns a promise for the * Transition object that was used. * * In order to do this, the router first determines which routes are involved * in the transition beginning with the current route, up the route tree to * the first parent route that is shared with the destination route, and back * down the tree to the destination route. The willTransitionFrom static * method is invoked on all route handlers we're transitioning away from, in * reverse nesting order. Likewise, the willTransitionTo static method * is invoked on all route handlers we're transitioning to. * * Both willTransitionFrom and willTransitionTo hooks may either abort or * redirect the transition. If they need to resolve asynchronously, they may * return a promise. * * Any error that occurs asynchronously during the transition is re-thrown in * the top-level scope unless returnRejectedPromise is true, in which case a * rejected promise is returned so the caller may handle the error. * * Note: This function does not update the URL in a browser's location bar. * If you want to keep the URL in sync with transitions, use Router.transitionTo, * Router.replaceWith, or Router.goBack instead. */ dispatch: function (path, returnRejectedPromise) { var transition = new Transition(path); var routes = this; var promise = runTransitionHooks(routes, transition).then(function (nextState) { if (transition.isAborted) { routes.props.onAbortedTransition(transition); } else if (nextState) { routes.setState(nextState); routes.props.onActiveStateChange(nextState); // TODO: add functional test var rootMatch = getRootMatch(nextState.matches); if (rootMatch) maybeUpdateScroll(routes, rootMatch.route); } return transition; }); if (!returnRejectedPromise) { promise = promise.then(undefined, function (error) { // Use setTimeout to break the promise chain. setTimeout(function () { routes.props.onTransitionError(error); }); }); } return promise; }, render: function () { if (!this.state.path) return null; var matches = this.state.matches; if (matches.length) { // matches[0] corresponds to the top-most match return matches[0].route.props.handler(computeHandlerProps(matches, this.state.activeQuery)); } else { return null; } } }); function findMatches(path, routes, defaultRoute, notFoundRoute) { var matches = null, route, params; for (var i = 0, len = routes.length; i < len; ++i) { route = routes[i]; // Check the subtree first to find the most deeply-nested match. matches = findMatches(path, route.props.children, route.props.defaultRoute, route.props.notFoundRoute); if (matches != null) { var rootParams = getRootMatch(matches).params; params = route.props.paramNames.reduce(function (params, paramName) { params[paramName] = rootParams[paramName]; return params; }, {}); matches.unshift(makeMatch(route, params)); return matches; } // No routes in the subtree matched, so check this route. params = Path.extractParams(route.props.path, path); if (params) return [ makeMatch(route, params) ]; } // No routes matched, so try the default route if there is one. if (defaultRoute && (params = Path.extractParams(defaultRoute.props.path, path))) return [ makeMatch(defaultRoute, params) ]; // Last attempt: does the "not found" route match? if (notFoundRoute && (params = Path.extractParams(notFoundRoute.props.path, path))) return [ makeMatch(notFoundRoute, params) ]; return matches; } function makeMatch(route, params) { return { route: route, params: params }; } function hasMatch(matches, match) { return matches.some(function (m) { if (m.route !== match.route) return false; for (var property in m.params) { if (m.params[property] !== match.params[property]) return false; } return true; }); } function getRootMatch(matches) { return matches[matches.length - 1]; } function updateMatchComponents(matches, refs) { var i = 0, component; while (component = refs[REF_NAME]) { matches[i++].component = component; refs = component.refs; } } /** * Runs all transition hooks that are required to get from the current state * to the state specified by the given transition and updates the current state * if they all pass successfully. Returns a promise that resolves to the new * state if it needs to be updated, or undefined if not. */ function runTransitionHooks(routes, transition) { if (routes.state.path === transition.path) return Promise.resolve(); // Nothing to do! var currentMatches = routes.state.matches; var nextMatches = routes.match(transition.path); warning( nextMatches, 'No route matches path "' + transition.path + '". Make sure you have ' + '<Route path="' + transition.path + '"> somewhere in your routes' ); if (!nextMatches) nextMatches = []; var fromMatches, toMatches; if (currentMatches) { updateMatchComponents(currentMatches, routes.refs); fromMatches = currentMatches.filter(function (match) { return !hasMatch(nextMatches, match); }); toMatches = nextMatches.filter(function (match) { return !hasMatch(currentMatches, match); }); } else { fromMatches = []; toMatches = nextMatches; } var query = Path.extractQuery(transition.path) || {}; return runTransitionFromHooks(fromMatches, transition).then(function () { if (transition.isAborted) return; // No need to continue. return runTransitionToHooks(toMatches, transition, query).then(function () { if (transition.isAborted) return; // No need to continue. var rootMatch = getRootMatch(nextMatches); var params = (rootMatch && rootMatch.params) || {}; return { path: transition.path, matches: nextMatches, activeParams: params, activeQuery: query, activeRoutes: nextMatches.map(function (match) { return match.route; }) }; }); }); } /** * Calls the willTransitionFrom hook of all handlers in the given matches * serially in reverse with the transition object and the current instance of * the route's handler, so that the deepest nested handlers are called first. * Returns a promise that resolves after the last handler. */ function runTransitionFromHooks(matches, transition) { var promise = Promise.resolve(); reversedArray(matches).forEach(function (match) { promise = promise.then(function () { var handler = match.route.props.handler; if (!transition.isAborted && handler.willTransitionFrom) return handler.willTransitionFrom(transition, match.component); }); }); return promise; } /** * Calls the willTransitionTo hook of all handlers in the given matches serially * with the transition object and any params that apply to that handler. Returns * a promise that resolves after the last handler. */ function runTransitionToHooks(matches, transition, query) { var promise = Promise.resolve(); matches.forEach(function (match) { promise = promise.then(function () { var handler = match.route.props.handler; if (!transition.isAborted && handler.willTransitionTo) return handler.willTransitionTo(transition, match.params, query); }); }); return promise; } /** * Given an array of matches as returned by findMatches, return a descriptor for * the handler hierarchy specified by the route. */ function computeHandlerProps(matches, query) { var props = { ref: null, key: null, params: null, query: null, activeRouteHandler: returnNull }; var childHandler; reversedArray(matches).forEach(function (match) { var route = match.route; props = Route.getUnreservedProps(route.props); props.ref = REF_NAME; props.params = match.params; props.query = query; if (route.props.addHandlerKey) props.key = Path.injectParams(route.props.path, match.params); if (childHandler) { props.activeRouteHandler = childHandler; } else { props.activeRouteHandler = returnNull; } childHandler = function (props, addedProps) { if (arguments.length > 2 && typeof arguments[2] !== 'undefined') throw new Error('Passing children to a route handler is not supported'); return route.props.handler(copyProperties(props, addedProps)); }.bind(this, props); }); return props; } function returnNull() { return null; } function reversedArray(array) { return array.slice(0).reverse(); } module.exports = Routes; },{"../actions/LocationActions":12,"../components/Route":17,"../helpers/Path":20,"../helpers/Redirect":21,"../helpers/Transition":22,"../locations/HashLocation":30,"../locations/HistoryLocation":31,"../locations/RefreshLocation":32,"../stores/ActiveStore":35,"../stores/PathStore":36,"../stores/RouteStore":37,"react/lib/copyProperties":48,"react/lib/warning":56,"when/lib/Promise":57}],19:[function(_dereq_,module,exports){ var copyProperties = _dereq_('react/lib/copyProperties'); var Dispatcher = _dereq_('flux').Dispatcher; /** * Dispatches actions that modify the URL. */ var LocationDispatcher = copyProperties(new Dispatcher, { handleViewAction: function (action) { this.dispatch({ source: 'VIEW_ACTION', action: action }); } }); module.exports = LocationDispatcher; },{"flux":39,"react/lib/copyProperties":48}],20:[function(_dereq_,module,exports){ var invariant = _dereq_('react/lib/invariant'); var merge = _dereq_('qs/lib/utils').merge; var qs = _dereq_('qs'); function encodeURL(url) { return encodeURIComponent(url).replace(/%20/g, '+'); } function decodeURL(url) { return decodeURIComponent(url.replace(/\+/g, ' ')); } function encodeURLPath(path) { return String(path).split('/').map(encodeURL).join('/'); } var paramMatcher = /:([a-zA-Z_$][a-zA-Z0-9_$]*)|[*.()\[\]\\+|{}^$]/g; var queryMatcher = /\?(.+)/; var _compiledPatterns = {}; function compilePattern(pattern) { if (!(pattern in _compiledPatterns)) { var paramNames = []; var source = pattern.replace(paramMatcher, function (match, paramName) { if (paramName) { paramNames.push(paramName); return '([^./?#]+)'; } else if (match === '*') { paramNames.push('splat'); return '(.*?)'; } else { return '\\' + match; } }); _compiledPatterns[pattern] = { matcher: new RegExp('^' + source + '$', 'i'), paramNames: paramNames }; } return _compiledPatterns[pattern]; } var Path = { /** * Returns an array of the names of all parameters in the given pattern. */ extractParamNames: function (pattern) { return compilePattern(pattern).paramNames; }, /** * Extracts the portions of the given URL path that match the given pattern * and returns an object of param name => value pairs. Returns null if the * pattern does not match the given path. */ extractParams: function (pattern, path) { var object = compilePattern(pattern); var match = decodeURL(path).match(object.matcher); if (!match) return null; var params = {}; object.paramNames.forEach(function (paramName, index) { params[paramName] = match[index + 1]; }); return params; }, /** * Returns a version of the given route path with params interpolated. Throws * if there is a dynamic segment of the route path for which there is no param. */ injectParams: function (pattern, params) { params = params || {}; var splatIndex = 0; return pattern.replace(paramMatcher, function (match, paramName) { paramName = paramName || 'splat'; invariant( params[paramName] != null, 'Missing "' + paramName + '" parameter for path "' + pattern + '"' ); var segment; if (paramName === 'splat' && Array.isArray(params[paramName])) { segment = params[paramName][splatIndex++]; invariant( segment != null, 'Missing splat # ' + splatIndex + ' for path "' + pattern + '"' ); } else { segment = params[paramName]; } return encodeURLPath(segment); }); }, /** * Returns an object that is the result of parsing any query string contained * in the given path, null if the path contains no query string. */ extractQuery: function (path) { var match = decodeURL(path).match(queryMatcher); return match && qs.parse(match[1]); }, /** * Returns a version of the given path without the query string. */ withoutQuery: function (path) { return path.replace(queryMatcher, ''); }, /** * Returns a version of the given path with the parameters in the given * query merged into the query string. */ withQuery: function (path, query) { var existingQuery = Path.extractQuery(path); if (existingQuery) query = query ? merge(existingQuery, query) : existingQuery; var queryString = query && qs.stringify(query); if (queryString) return Path.withoutQuery(path) + '?' + queryString; return path; }, /** * Returns true if the given path is absolute. */ isAbsolute: function (path) { return path.charAt(0) === '/'; }, /** * Returns a normalized version of the given path. */ normalize: function (path, parentRoute) { return path.replace(/^\/*/, '/'); }, /** * Joins two URL paths together. */ join: function (a, b) { return a.replace(/\/*$/, '/') + b; } }; module.exports = Path; },{"qs":42,"qs/lib/utils":46,"react/lib/invariant":50}],21:[function(_dereq_,module,exports){ /** * Encapsulates a redirect to the given route. */ function Redirect(to, params, query) { this.to = to; this.params = params; this.query = query; } module.exports = Redirect; },{}],22:[function(_dereq_,module,exports){ var mixInto = _dereq_('react/lib/mixInto'); var transitionTo = _dereq_('../actions/LocationActions').transitionTo; var Redirect = _dereq_('./Redirect'); /** * Encapsulates a transition to a given path. * * The willTransitionTo and willTransitionFrom handlers receive * an instance of this class as their first argument. */ function Transition(path) { this.path = path; this.abortReason = null; this.isAborted = false; } mixInto(Transition, { abort: function (reason) { this.abortReason = reason; this.isAborted = true; }, redirect: function (to, params, query) { this.abort(new Redirect(to, params, query)); }, retry: function () { transitionTo(this.path); } }); module.exports = Transition; },{"../actions/LocationActions":12,"./Redirect":21,"react/lib/mixInto":55}],23:[function(_dereq_,module,exports){ /** * Returns the current URL path from `window.location`, including query string */ function getWindowPath() { return window.location.pathname + window.location.search; } module.exports = getWindowPath; },{}],24:[function(_dereq_,module,exports){ module.exports = Function.prototype.call.bind(Object.prototype.hasOwnProperty); },{}],25:[function(_dereq_,module,exports){ var HashLocation = _dereq_('../locations/HashLocation'); var PathStore = _dereq_('../stores/PathStore'); var makePath = _dereq_('./makePath'); /** * Returns a string that may safely be used as the href of a * link to the route with the given name. */ function makeHref(to, params, query) { var path = makePath(to, params, query); if (PathStore.getLocation() === HashLocation) return '#' + path; return path; } module.exports = makeHref; },{"../locations/HashLocation":30,"../stores/PathStore":36,"./makePath":26}],26:[function(_dereq_,module,exports){ var invariant = _dereq_('react/lib/invariant'); var RouteStore = _dereq_('../stores/RouteStore'); var Path = _dereq_('./Path'); /** * Returns an absolute URL path created from the given route name, URL * parameters, and query values. */ function makePath(to, params, query) { var path; if (Path.isAbsolute(to)) { path = Path.normalize(to); } else { var route = RouteStore.getRouteByName(to); invariant( route, 'Unable to find a route named "' + to + '". Make sure you have ' + 'a <Route name="' + to + '"> defined somewhere in your routes' ); path = route.props.path; } return Path.withQuery(Path.injectParams(path, params), query); } module.exports = makePath; },{"../stores/RouteStore":37,"./Path":20,"react/lib/invariant":50}],27:[function(_dereq_,module,exports){ var Promise = _dereq_('when/lib/Promise'); /** * Resolves all values in asyncState and calls the setState * function with new state as they resolve. Returns a promise * that resolves after all values are resolved. */ function resolveAsyncState(asyncState, setState) { if (asyncState == null) return Promise.resolve(); var keys = Object.keys(asyncState); return Promise.all( keys.map(function (key) { return Promise.resolve(asyncState[key]).then(function (value) { var newState = {}; newState[key] = value; setState(newState); }); }) ); } module.exports = resolveAsyncState; },{"when/lib/Promise":57}],28:[function(_dereq_,module,exports){ function supportsHistory() { /*! taken from modernizr * https://github.com/Modernizr/Modernizr/blob/master/LICENSE * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js */ var ua = navigator.userAgent; if ((ua.indexOf('Android 2.') !== -1 || (ua.indexOf('Android 4.0') !== -1)) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1) { return false; } return (window.history && 'pushState' in window.history); } module.exports = supportsHistory; },{}],29:[function(_dereq_,module,exports){ function withoutProperties(object, properties) { var result = {}; for (var property in object) { if (object.hasOwnProperty(property) && !properties[property]) result[property] = object[property]; } return result; } module.exports = withoutProperties; },{}],30:[function(_dereq_,module,exports){ var invariant = _dereq_('react/lib/invariant'); var ExecutionEnvironment = _dereq_('react/lib/ExecutionEnvironment'); var getWindowPath = _dereq_('../helpers/getWindowPath'); function getHashPath() { return window.location.hash.substr(1); } function ensureSlash() { var path = getHashPath(); if (path.charAt(0) === '/') return true; HashLocation.replace('/' + path); return false; } var _onChange; function handleHashChange() { if (ensureSlash()) _onChange(); } /** * A Location that uses `window.location.hash`. */ var HashLocation = { setup: function (onChange) { invariant( ExecutionEnvironment.canUseDOM, 'You cannot use HashLocation in an environment with no DOM' ); _onChange = onChange; ensureSlash(); if (window.addEventListener) { window.addEventListener('hashchange', handleHashChange, false); } else { window.attachEvent('onhashchange', handleHashChange); } }, teardown: function () { if (window.removeEventListener) { window.removeEventListener('hashchange', handleHashChange, false); } else { window.detachEvent('onhashchange', handleHashChange); } }, push: function (path) { window.location.hash = path; }, replace: function (path) { window.location.replace(getWindowPath() + '#' + path); }, pop: function () { window.history.back(); }, getCurrentPath: getHashPath, toString: function () { return '<HashLocation>'; } }; module.exports = HashLocation; },{"../helpers/getWindowPath":23,"react/lib/ExecutionEnvironment":47,"react/lib/invariant":50}],31:[function(_dereq_,module,exports){ var invariant = _dereq_('react/lib/invariant'); var ExecutionEnvironment = _dereq_('react/lib/ExecutionEnvironment'); var getWindowPath = _dereq_('../helpers/getWindowPath'); var _onChange; /** * A Location that uses HTML5 history. */ var HistoryLocation = { setup: function (onChange) { invariant( ExecutionEnvironment.canUseDOM, 'You cannot use HistoryLocation in an environment with no DOM' ); _onChange = onChange; if (window.addEventListener) { window.addEventListener('popstate', _onChange, false); } else { window.attachEvent('popstate', _onChange); } }, teardown: function () { if (window.removeEventListener) { window.removeEventListener('popstate', _onChange, false); } else { window.detachEvent('popstate', _onChange); } }, push: function (path) { window.history.pushState({ path: path }, '', path); _onChange(); }, replace: function (path) { window.history.replaceState({ path: path }, '', path); _onChange(); }, pop: function () { window.history.back(); }, getCurrentPath: getWindowPath, toString: function () { return '<HistoryLocation>'; } }; module.exports = HistoryLocation; },{"../helpers/getWindowPath":23,"react/lib/ExecutionEnvironment":47,"react/lib/invariant":50}],32:[function(_dereq_,module,exports){ var invariant = _dereq_('react/lib/invariant'); var ExecutionEnvironment = _dereq_('react/lib/ExecutionEnvironment'); var getWindowPath = _dereq_('../helpers/getWindowPath'); /** * A Location that uses full page refreshes. This is used as * the fallback for HistoryLocation in browsers that do not * support the HTML5 history API. */ var RefreshLocation = { setup: function () { invariant( ExecutionEnvironment.canUseDOM, 'You cannot use RefreshLocation in an environment with no DOM' ); }, push: function (path) { window.location = path; }, replace: function (path) { window.location.replace(path); }, pop: function () { window.history.back(); }, getCurrentPath: getWindowPath, toString: function () { return '<RefreshLocation>'; } }; module.exports = RefreshLocation; },{"../helpers/getWindowPath":23,"react/lib/ExecutionEnvironment":47,"react/lib/invariant":50}],33:[function(_dereq_,module,exports){ var ActiveStore = _dereq_('../stores/ActiveStore'); /** * A mixin for components that need to know about the routes, params, * and query that are currently active. Components that use it get two * things: * * 1. An `isActive` static method they can use to check if a route, * params, and query are active. * 2. An `updateActiveState` instance method that is called when the * active state changes. * * Example: * * var Tab = React.createClass({ * * mixins: [ Router.ActiveState ], * * getInitialState: function () { * return { * isActive: false * }; * }, * * updateActiveState: function () { * this.setState({ * isActive: Tab.isActive(routeName, params, query) * }) * } * * }); */ var ActiveState = { statics: { /** * Returns true if the route with the given name, URL parameters, and query * are all currently active. */ isActive: ActiveStore.isActive }, componentWillMount: function () { ActiveStore.addChangeListener(this.handleActiveStateChange); }, componentDidMount: function () { if (this.updateActiveState) this.updateActiveState(); }, componentWillUnmount: function () { ActiveStore.removeChangeListener(this.handleActiveStateChange); }, handleActiveStateChange: function () { if (this.isMounted() && typeof this.updateActiveState === 'function') this.updateActiveState(); } }; module.exports = ActiveState; },{"../stores/ActiveStore":35}],34:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); var resolveAsyncState = _dereq_('../helpers/resolveAsyncState'); /** * A mixin for route handler component classes that fetch at least * part of their state asynchronously. Classes that use it should * declare a static `getInitialAsyncState` method that fetches state * for a component after it mounts. This function is given three * arguments: 1) the current route params, 2) the current query and * 3) a function that can be used to set state as it is received. * * Much like the familiar `getInitialState` method, `getInitialAsyncState` * should return a hash of key/value pairs to use in the component's * state. The difference is that the values may be promises. As these * values resolve, the component's state is updated. You should only * ever need to use the setState function for doing things like * streaming data and/or updating progress. * * Example: * * var User = React.createClass({ * * statics: { * * getInitialAsyncState: function (params, query, setState) { * // Return a hash with keys named after the state variables * // you want to set, as you normally do in getInitialState, * // except the values may be immediate values or promises. * // The state is automatically updated as promises resolve. * return { * user: getUserByID(params.userID) // may be a promise * }; * * // Or, use the setState function to stream data! * var buffer = ''; * * return { * * // Same as above, the stream state variable is set to the * // value returned by this promise when it resolves. * stream: getStreamingData(params.userID, function (chunk) { * buffer += chunk; * * // Notify of progress. * setState({ * streamBuffer: buffer * }); * }) * * }; * } * * }, * * getInitialState: function () { * return { * user: null, // Receives a value when getUserByID resolves. * stream: null, // Receives a value when getStreamingData resolves. * streamBuffer: '' // Used to track data as it loads. * }; * }, * * render: function () { * if (!this.state.user) * return <LoadingUser/>; * * return ( * <div> * <p>Welcome {this.state.user.name}!</p> * <p>So far, you've received {this.state.streamBuffer.length} data!</p> * </div> * ); * } * * }); * * When testing, use the `initialAsyncState` prop to simulate asynchronous * data fetching. When this prop is present, no attempt is made to retrieve * additional state via `getInitialAsyncState`. */ var AsyncState = { propTypes: { initialAsyncState: React.PropTypes.object }, getInitialState: function () { return this.props.initialAsyncState || null; }, updateAsyncState: function (state) { if (this.isMounted()) this.setState(state); }, componentDidMount: function () { if (this.props.initialAsyncState || typeof this.constructor.getInitialAsyncState !== 'function') return; resolveAsyncState( this.constructor.getInitialAsyncState(this.props.params, this.props.query, this.updateAsyncState), this.updateAsyncState ); } }; module.exports = AsyncState; },{"../helpers/resolveAsyncState":27}],35:[function(_dereq_,module,exports){ var EventEmitter = _dereq_('events').EventEmitter; var CHANGE_EVENT = 'change'; var _events = new EventEmitter; _events.setMaxListeners(0); function notifyChange() { _events.emit(CHANGE_EVENT); } var _activeRoutes = []; var _activeParams = {}; var _activeQuery = {}; function routeIsActive(routeName) { return _activeRoutes.some(function (route) { return route.props.name === routeName; }); } function paramsAreActive(params) { for (var property in params) { if (_activeParams[property] !== String(params[property])) return false; } return true; } function queryIsActive(query) { for (var property in query) { if (_activeQuery[property] !== String(query[property])) return false; } return true; } /** * The ActiveStore keeps track of which routes, URL and query parameters are * currently active on a page. <Link>s subscribe to the ActiveStore to know * whether or not they are active. */ var ActiveStore = { addChangeListener: function (listener) { _events.on(CHANGE_EVENT, listener); }, removeChangeListener: function (listener) { _events.removeListener(CHANGE_EVENT, listener); }, /** * Updates the currently active state and notifies all listeners. * This is automatically called by routes as they become active. */ updateState: function (state) { state = state || {}; _activeRoutes = state.activeRoutes || []; _activeParams = state.activeParams || {}; _activeQuery = state.activeQuery || {}; notifyChange(); }, /** * Returns true if the route with the given name, URL parameters, and query * are all currently active. */ isActive: function (routeName, params, query) { var isActive = routeIsActive(routeName) && paramsAreActive(params); if (query) return isActive && queryIsActive(query); return isActive; } }; module.exports = ActiveStore; },{"events":38}],36:[function(_dereq_,module,exports){ var warning = _dereq_('react/lib/warning'); var EventEmitter = _dereq_('events').EventEmitter; var LocationActions = _dereq_('../actions/LocationActions'); var LocationDispatcher = _dereq_('../dispatchers/LocationDispatcher'); var supportsHistory = _dereq_('../helpers/supportsHistory'); var HistoryLocation = _dereq_('../locations/HistoryLocation'); var RefreshLocation = _dereq_('../locations/RefreshLocation'); var CHANGE_EVENT = 'change'; var _events = new EventEmitter; function notifyChange() { _events.emit(CHANGE_EVENT); } var _scrollPositions = {}; function recordScrollPosition(path) { _scrollPositions[path] = { x: window.scrollX, y: window.scrollY }; } function updateScrollPosition(path) { var p = PathStore.getScrollPosition(path); window.scrollTo(p.x, p.y); } var _location; /** * The PathStore keeps track of the current URL path and manages * the location strategy that is used to update the URL. */ var PathStore = { addChangeListener: function (listener) { _events.on(CHANGE_EVENT, listener); }, removeChangeListener: function (listener) { _events.removeListener(CHANGE_EVENT, listener); // Automatically teardown when the last listener is removed. if (EventEmitter.listenerCount(_events, CHANGE_EVENT) === 0) PathStore.teardown(); }, setup: function (location) { // When using HistoryLocation, automatically fallback // to RefreshLocation in browsers that do not support // the HTML5 history API. if (location === HistoryLocation && !supportsHistory()) location = RefreshLocation; if (_location == null) { _location = location; if (_location && typeof _location.setup === 'function') _location.setup(notifyChange); } else { warning( _location === location, 'Cannot use location %s, already using %s', location, _location ); } }, teardown: function () { if (_location && typeof _location.teardown === 'function') _location.teardown(); _location = null; }, /** * Returns the location object currently in use. */ getLocation: function () { return _location; }, /** * Returns the current URL path. */ getCurrentPath: function () { return _location.getCurrentPath(); }, /** * Returns the last known scroll position for the given path. */ getScrollPosition: function (path) { return _scrollPositions[path] || { x: 0, y: 0 }; }, dispatchToken: LocationDispatcher.register(function (payload) { var action = payload.action; var currentPath = _location.getCurrentPath(); switch (action.type) { case LocationActions.PUSH: if (currentPath !== action.path) { recordScrollPosition(currentPath); _location.push(action.path); } break; case LocationActions.REPLACE: if (currentPath !== action.path) { recordScrollPosition(currentPath); _location.replace(action.path); } break; case LocationActions.POP: recordScrollPosition(currentPath); _location.pop(); break; case LocationActions.UPDATE_SCROLL: updateScrollPosition(currentPath); break; } }) }; module.exports = PathStore; },{"../actions/LocationActions":12,"../dispatchers/LocationDispatcher":19,"../helpers/supportsHistory":28,"../locations/HistoryLocation":31,"../locations/RefreshLocation":32,"events":38,"react/lib/warning":56}],37:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); var invariant = _dereq_('react/lib/invariant'); var warning = _dereq_('react/lib/warning'); var Path = _dereq_('../helpers/Path'); var _namedRoutes = {}; /** * The RouteStore contains a directory of all <Route>s in the system. It is * used primarily for looking up routes by name so that <Link>s can use a * route name in the "to" prop and users can use route names in `Router.transitionTo` * and other high-level utility methods. */ var RouteStore = { /** * Removes all references to <Route>s from the store. Should only ever * really be used in tests to clear the store between test runs. */ unregisterAllRoutes: function () { _namedRoutes = {}; }, /** * Removes the reference to the given <Route> and all of its children * from the store. */ unregisterRoute: function (route) { var props = route.props; if (props.name) delete _namedRoutes[props.name]; React.Children.forEach(props.children, RouteStore.unregisterRoute); }, /** * Registers a <Route> and all of its children with the store. Also, * does some normalization and validation on route props. */ registerRoute: function (route, parentRoute) { // Note: parentRoute may be a <Route> _or_ a <Routes>. var props = route.props; invariant( React.isValidClass(props.handler), 'The handler for the "%s" route must be a valid React class', props.name || props.path ); var parentPath = (parentRoute && parentRoute.props.path) || '/'; if ((props.path || props.name) && !props.isDefault && !props.catchAll) { var path = props.path || props.name; // Relative paths extend their parent. if (!Path.isAbsolute(path)) path = Path.join(parentPath, path); props.path = Path.normalize(path); } else { props.path = parentPath; if (props.catchAll) props.path += '*'; } props.paramNames = Path.extractParamNames(props.path); // Make sure the route's path has all params its parent needs. if (parentRoute && Array.isArray(parentRoute.props.paramNames)) { parentRoute.props.paramNames.forEach(function (paramName) { invariant( props.paramNames.indexOf(paramName) !== -1, 'The nested route path "%s" is missing the "%s" parameter of its parent path "%s"', props.path, paramName, parentRoute.props.path ); }); } // Make sure the route can be looked up by <Link>s. if (props.name) { var existingRoute = _namedRoutes[props.name]; invariant( !existingRoute || route === existingRoute, 'You cannot use the name "%s" for more than one route', props.name ); _namedRoutes[props.name] = route; } if (props.catchAll) { invariant( parentRoute, '<NotFoundRoute> must have a parent <Route>' ); invariant( parentRoute.props.notFoundRoute == null, 'You may not have more than one <NotFoundRoute> per <Route>' ); parentRoute.props.notFoundRoute = route; return null; } if (props.isDefault) { invariant( parentRoute, '<DefaultRoute> must have a parent <Route>' ); invariant( parentRoute.props.defaultRoute == null, 'You may not have more than one <DefaultRoute> per <Route>' ); parentRoute.props.defaultRoute = route; return null; } // Make sure children is an array. props.children = RouteStore.registerChildren(props.children, route); return route; }, /** * Registers many children routes at once, always returning an array. */ registerChildren: function (children, parentRoute) { var routes = []; React.Children.forEach(children, function (child) { // Exclude <DefaultRoute>s. if (child = RouteStore.registerRoute(child, parentRoute)) routes.push(child); }); return routes; }, /** * Returns the Route object with the given name, if one exists. */ getRouteByName: function (routeName) { return _namedRoutes[routeName] || null; } }; module.exports = RouteStore; },{"../helpers/Path":20,"react/lib/invariant":50,"react/lib/warning":56}],38:[function(_dereq_,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { throw TypeError('Uncaught, unspecified "error" event.'); } return false; } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { var m; if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],39:[function(_dereq_,module,exports){ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ module.exports.Dispatcher = _dereq_('./lib/Dispatcher') },{"./lib/Dispatcher":40}],40:[function(_dereq_,module,exports){ /* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Dispatcher * @typechecks */ var invariant = _dereq_('./invariant'); var _lastID = 1; var _prefix = 'ID_'; /** * Dispatcher is used to broadcast payloads to registered callbacks. This is * different from generic pub-sub systems in two ways: * * 1) Callbacks are not subscribed to particular events. Every payload is * dispatched to every registered callback. * 2) Callbacks can be deferred in whole or part until other callbacks have * been executed. * * For example, consider this hypothetical flight destination form, which * selects a default city when a country is selected: * * var flightDispatcher = new Dispatcher(); * * // Keeps track of which country is selected * var CountryStore = {country: null}; * * // Keeps track of which city is selected * var CityStore = {city: null}; * * // Keeps track of the base flight price of the selected city * var FlightPriceStore = {price: null} * * When a user changes the selected city, we dispatch the payload: * * flightDispatcher.dispatch({ * actionType: 'city-update', * selectedCity: 'paris' * }); * * This payload is digested by `CityStore`: * * flightDispatcher.register(function(payload) { * if (payload.actionType === 'city-update') { * CityStore.city = payload.selectedCity; * } * }); * * When the user selects a country, we dispatch the payload: * * flightDispatcher.dispatch({ * actionType: 'country-update', * selectedCountry: 'australia' * }); * * This payload is digested by both stores: * * CountryStore.dispatchToken = flightDispatcher.register(function(payload) { * if (payload.actionType === 'country-update') { * CountryStore.country = payload.selectedCountry; * } * }); * * When the callback to update `CountryStore` is registered, we save a reference * to the returned token. Using this token with `waitFor()`, we can guarantee * that `CountryStore` is updated before the callback that updates `CityStore` * needs to query its data. * * CityStore.dispatchToken = flightDispatcher.register(function(payload) { * if (payload.actionType === 'country-update') { * // `CountryStore.country` may not be updated. * flightDispatcher.waitFor([CountryStore.dispatchToken]); * // `CountryStore.country` is now guaranteed to be updated. * * // Select the default city for the new country * CityStore.city = getDefaultCityForCountry(CountryStore.country); * } * }); * * The usage of `waitFor()` can be chained, for example: * * FlightPriceStore.dispatchToken = * flightDispatcher.register(function(payload) { * switch (payload.actionType) { * case 'country-update': * flightDispatcher.waitFor([CityStore.dispatchToken]); * FlightPriceStore.price = * getFlightPriceStore(CountryStore.country, CityStore.city); * break; * * case 'city-update': * FlightPriceStore.price = * FlightPriceStore(CountryStore.country, CityStore.city); * break; * } * }); * * The `country-update` payload will be guaranteed to invoke the stores' * registered callbacks in order: `CountryStore`, `CityStore`, then * `FlightPriceStore`. */ function Dispatcher() {"use strict"; this.$Dispatcher_callbacks = {}; this.$Dispatcher_isPending = {}; this.$Dispatcher_isHandled = {}; this.$Dispatcher_isDispatching = false; this.$Dispatcher_pendingPayload = null; } /** * Registers a callback to be invoked with every dispatched payload. Returns * a token that can be used with `waitFor()`. * * @param {function} callback * @return {string} */ Dispatcher.prototype.register=function(callback) {"use strict"; var id = _prefix + _lastID++; this.$Dispatcher_callbacks[id] = callback; return id; }; /** * Removes a callback based on its token. * * @param {string} id */ Dispatcher.prototype.unregister=function(id) {"use strict"; invariant( this.$Dispatcher_callbacks[id], 'Dispatcher.unregister(...): `%s` does not map to a registered callback.', id ); delete this.$Dispatcher_callbacks[id]; }; /** * Waits for the callbacks specified to be invoked before continuing execution * of the current callback. This method should only be used by a callback in * response to a dispatched payload. * * @param {array<string>} ids */ Dispatcher.prototype.waitFor=function(ids) {"use strict"; invariant( this.$Dispatcher_isDispatching, 'Dispatcher.waitFor(...): Must be invoked while dispatching.' ); for (var ii = 0; ii < ids.length; ii++) { var id = ids[ii]; if (this.$Dispatcher_isPending[id]) { invariant( this.$Dispatcher_isHandled[id], 'Dispatcher.waitFor(...): Circular dependency detected while ' + 'waiting for `%s`.', id ); continue; } invariant( this.$Dispatcher_callbacks[id], 'Dispatcher.waitFor(...): `%s` does not map to a registered callback.', id ); this.$Dispatcher_invokeCallback(id); } }; /** * Dispatches a payload to all registered callbacks. * * @param {object} payload */ Dispatcher.prototype.dispatch=function(payload) {"use strict"; invariant( !this.$Dispatcher_isDispatching, 'Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.' ); this.$Dispatcher_startDispatching(payload); try { for (var id in this.$Dispatcher_callbacks) { if (this.$Dispatcher_isPending[id]) { continue; } this.$Dispatcher_invokeCallback(id); } } finally { this.$Dispatcher_stopDispatching(); } }; /** * Is this Dispatcher currently dispatching. * * @return {boolean} */ Dispatcher.prototype.isDispatching=function() {"use strict"; return this.$Dispatcher_isDispatching; }; /** * Call the callback stored with the given id. Also do some internal * bookkeeping. * * @param {string} id * @internal */ Dispatcher.prototype.$Dispatcher_invokeCallback=function(id) {"use strict"; this.$Dispatcher_isPending[id] = true; this.$Dispatcher_callbacks[id](this.$Dispatcher_pendingPayload); this.$Dispatcher_isHandled[id] = true; }; /** * Set up bookkeeping needed when dispatching. * * @param {object} payload * @internal */ Dispatcher.prototype.$Dispatcher_startDispatching=function(payload) {"use strict"; for (var id in this.$Dispatcher_callbacks) { this.$Dispatcher_isPending[id] = false; this.$Dispatcher_isHandled[id] = false; } this.$Dispatcher_pendingPayload = payload; this.$Dispatcher_isDispatching = true; }; /** * Clear bookkeeping used for dispatching. * * @internal */ Dispatcher.prototype.$Dispatcher_stopDispatching=function() {"use strict"; this.$Dispatcher_pendingPayload = null; this.$Dispatcher_isDispatching = false; }; module.exports = Dispatcher; },{"./invariant":41}],41:[function(_dereq_,module,exports){ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @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, 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( '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; },{}],42:[function(_dereq_,module,exports){ module.exports = _dereq_('./lib'); },{"./lib":43}],43:[function(_dereq_,module,exports){ // Load modules var Stringify = _dereq_('./stringify'); var Parse = _dereq_('./parse'); // Declare internals var internals = {}; module.exports = { stringify: Stringify, parse: Parse }; },{"./parse":44,"./stringify":45}],44:[function(_dereq_,module,exports){ // Load modules var Utils = _dereq_('./utils'); // Declare internals var internals = { delimiter: '&', depth: 5, arrayLimit: 20, parametersLimit: 1000 }; internals.parseValues = function (str, delimiter) { delimiter = typeof delimiter === 'string' ? delimiter : internals.delimiter; var obj = {}; var parts = str.split(delimiter, internals.parametersLimit); for (var i = 0, il = parts.length; i < il; ++i) { var part = parts[i]; var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; if (pos === -1) { obj[Utils.decode(part)] = ''; } else { var key = Utils.decode(part.slice(0, pos)); var val = Utils.decode(part.slice(pos + 1)); if (!obj[key]) { obj[key] = val; } else { obj[key] = [].concat(obj[key]).concat(val); } } } return obj; }; internals.parseObject = function (chain, val) { if (!chain.length) { return val; } var root = chain.shift(); var obj = {}; if (root === '[]') { obj = []; obj = obj.concat(internals.parseObject(chain, val)); } else { var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; var index = parseInt(cleanRoot, 10); if (!isNaN(index) && root !== cleanRoot && index <= internals.arrayLimit) { obj = []; obj[index] = internals.parseObject(chain, val); } else { obj[cleanRoot] = internals.parseObject(chain, val); } } return obj; }; internals.parseKeys = function (key, val, depth) { if (!key) { return; } // The regex chunks var parent = /^([^\[\]]*)/; var child = /(\[[^\[\]]*\])/g; // Get the parent var segment = parent.exec(key); // Don't allow them to overwrite object prototype properties if (Object.prototype.hasOwnProperty(segment[1])) { return; } // Stash the parent if it exists var keys = []; if (segment[1]) { keys.push(segment[1]); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < depth) { ++i; if (!Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) { keys.push(segment[1]); } } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return internals.parseObject(keys, val); }; module.exports = function (str, depth, delimiter) { if (str === '' || str === null || typeof str === 'undefined') { return {}; } if (typeof depth !== 'number') { delimiter = depth; depth = internals.depth; } var tempObj = typeof str === 'string' ? internals.parseValues(str, delimiter) : Utils.clone(str); var obj = {}; // Iterate over the keys and setup the new object // for (var key in tempObj) { if (tempObj.hasOwnProperty(key)) { var newObj = internals.parseKeys(key, tempObj[key], depth); obj = Utils.merge(obj, newObj); } } return Utils.compact(obj); }; },{"./utils":46}],45:[function(_dereq_,module,exports){ // Load modules // Declare internals var internals = { delimiter: '&' }; internals.stringify = function (obj, prefix) { if (Buffer.isBuffer(obj)) { obj = obj.toString(); } else if (obj instanceof Date) { obj = obj.toISOString(); } else if (obj === null) { obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') { return [encodeURIComponent(prefix) + '=' + encodeURIComponent(obj)]; } var values = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']')); } } return values; }; module.exports = function (obj, delimiter) { delimiter = typeof delimiter === 'undefined' ? internals.delimiter : delimiter; var keys = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keys = keys.concat(internals.stringify(obj[key], key)); } } return keys.join(delimiter); }; },{}],46:[function(_dereq_,module,exports){ // Load modules // Declare internals var internals = {}; exports.arrayToObject = function (source) { var obj = {}; for (var i = 0, il = source.length; i < il; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; exports.clone = function (source) { if (typeof source !== 'object' || source === null) { return source; } if (Buffer.isBuffer(source)) { return source.toString(); } var obj = Array.isArray(source) ? [] : {}; for (var i in source) { if (source.hasOwnProperty(i)) { obj[i] = exports.clone(source[i]); } } return obj; }; exports.merge = function (target, source) { if (!source) { return target; } var obj = exports.clone(target); if (Array.isArray(source)) { for (var i = 0, il = source.length; i < il; ++i) { if (typeof source[i] !== 'undefined') { if (typeof obj[i] === 'object') { obj[i] = exports.merge(obj[i], source[i]); } else { obj[i] = source[i]; } } } return obj; } if (Array.isArray(obj)) { obj = exports.arrayToObject(obj); } var keys = Object.keys(source); for (var k = 0, kl = keys.length; k < kl; ++k) { var key = keys[k]; var value = source[key]; if (value && typeof value === 'object') { if (!obj[key]) { obj[key] = exports.clone(value); } else { obj[key] = exports.merge(obj[key], value); } } else { obj[key] = value; } } return obj; }; exports.decode = function (str) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; exports.compact = function (obj) { if (typeof obj !== 'object' || obj === null) { return obj; } var compacted = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { if (Array.isArray(obj[key])) { compacted[key] = []; for (var i = 0, l = obj[key].length; i < l; i++) { if (typeof obj[key][i] !== 'undefined') { compacted[key].push(obj[key][i]); } } } else { compacted[key] = exports.compact(obj[key]); } } } return compacted; }; },{}],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 ExecutionEnvironment */ /*jslint evil: true */ "use strict"; var canUseDOM = !!( typeof window !== 'undefined' && window.document && window.document.createElement ); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; },{}],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 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" !== "production") { 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; },{}],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 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":48}],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 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, format, a, b, c, d, e, f) { if ("production" !== "production") { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( '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; },{}],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 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" !== "production" ? 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":50}],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 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":54}],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 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" !== "production" ? 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" !== "production" ? invariant( !isTerminal(arg) && !Array.isArray(arg), 'Tried to merge an object, instead got %s.', arg ) : invariant(!isTerminal(arg) && !Array.isArray(arg))); }, /** * @param {*} arg */ checkMergeIntoObjectArg: function(arg) { ("production" !== "production" ? invariant( (!isTerminal(arg) || typeof arg === 'function') && !Array.isArray(arg), 'Tried to merge into an object, instead got %s.', arg ) : invariant((!isTerminal(arg) || typeof arg === 'function') && !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" !== "production" ? 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" !== "production" ? 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":50,"./keyMirror":51}],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 mergeInto * @typechecks static-only */ "use strict"; var mergeHelpers = _dereq_("./mergeHelpers"); var checkMergeObjectArg = mergeHelpers.checkMergeObjectArg; var checkMergeIntoObjectArg = mergeHelpers.checkMergeIntoObjectArg; /** * Shallow merges two structures by mutating the first parameter. * * @param {object|function} one Object to be merged into. * @param {?object} two Optional object with properties to merge from. */ function mergeInto(one, two) { checkMergeIntoObjectArg(one); if (two != null) { checkMergeObjectArg(two); for (var key in two) { if (!two.hasOwnProperty(key)) { continue; } one[key] = two[key]; } } } module.exports = mergeInto; },{"./mergeHelpers":53}],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 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; },{}],56:[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" !== "production") { 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":49}],57:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function (_dereq_) { var makePromise = _dereq_('./makePromise'); var Scheduler = _dereq_('./Scheduler'); var async = _dereq_('./async'); return makePromise({ scheduler: new Scheduler(async) }); }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); }); },{"./Scheduler":59,"./async":60,"./makePromise":61}],58:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { /** * Circular queue * @param {number} capacityPow2 power of 2 to which this queue's capacity * will be set initially. eg when capacityPow2 == 3, queue capacity * will be 8. * @constructor */ function Queue(capacityPow2) { this.head = this.tail = this.length = 0; this.buffer = new Array(1 << capacityPow2); } Queue.prototype.push = function(x) { if(this.length === this.buffer.length) { this._ensureCapacity(this.length * 2); } this.buffer[this.tail] = x; this.tail = (this.tail + 1) & (this.buffer.length - 1); ++this.length; return this.length; }; Queue.prototype.shift = function() { var x = this.buffer[this.head]; this.buffer[this.head] = void 0; this.head = (this.head + 1) & (this.buffer.length - 1); --this.length; return x; }; Queue.prototype._ensureCapacity = function(capacity) { var head = this.head; var buffer = this.buffer; var newBuffer = new Array(capacity); var i = 0; var len; if(head === 0) { len = this.length; for(; i<len; ++i) { newBuffer[i] = buffer[i]; } } else { capacity = buffer.length; len = this.tail; for(; head<capacity; ++i, ++head) { newBuffer[i] = buffer[head]; } for(head=0; head<len; ++i, ++head) { newBuffer[i] = buffer[head]; } } this.buffer = newBuffer; this.head = 0; this.tail = this.length; }; return Queue; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],59:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(_dereq_) { var Queue = _dereq_('./Queue'); // Credit to Twisol (https://github.com/Twisol) for suggesting // this type of extensible queue + trampoline approach for next-tick conflation. /** * Async task scheduler * @param {function} async function to schedule a single async function * @constructor */ function Scheduler(async) { this._async = async; this._queue = new Queue(15); this._afterQueue = new Queue(5); this._running = false; var self = this; this.drain = function() { self._drain(); }; } /** * Enqueue a task * @param {{ run:function }} task */ Scheduler.prototype.enqueue = function(task) { this._add(this._queue, task); }; /** * Enqueue a task to run after the main task queue * @param {{ run:function }} task */ Scheduler.prototype.afterQueue = function(task) { this._add(this._afterQueue, task); }; /** * Drain the handler queue entirely, and then the after queue */ Scheduler.prototype._drain = function() { runQueue(this._queue); this._running = false; runQueue(this._afterQueue); }; /** * Add a task to the q, and schedule drain if not already scheduled * @param {Queue} queue * @param {{run:function}} task * @private */ Scheduler.prototype._add = function(queue, task) { queue.push(task); if(!this._running) { this._running = true; this._async(this.drain); } }; /** * Run all the tasks in the q * @param queue */ function runQueue(queue) { while(queue.length > 0) { queue.shift().run(); } } return Scheduler; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); })); },{"./Queue":58}],60:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(_dereq_) { // Sniff "best" async scheduling option // Prefer process.nextTick or MutationObserver, then check for // vertx and finally fall back to setTimeout /*jshint maxcomplexity:6*/ /*global process,document,setTimeout,MutationObserver,WebKitMutationObserver*/ var nextTick, MutationObs; if (typeof process !== 'undefined' && process !== null && typeof process.nextTick === 'function') { nextTick = function(f) { process.nextTick(f); }; } else if (MutationObs = (typeof MutationObserver === 'function' && MutationObserver) || (typeof WebKitMutationObserver === 'function' && WebKitMutationObserver)) { nextTick = (function (document, MutationObserver) { var scheduled; var el = document.createElement('div'); var o = new MutationObserver(run); o.observe(el, { attributes: true }); function run() { var f = scheduled; scheduled = void 0; f(); } return function (f) { scheduled = f; el.setAttribute('class', 'x'); }; }(document, MutationObs)); } else { nextTick = (function(cjsRequire) { try { // vert.x 1.x || 2.x return cjsRequire('vertx').runOnLoop || cjsRequire('vertx').runOnContext; } catch (ignore) {} // capture setTimeout to avoid being caught by fake timers // used in time based tests var capturedSetTimeout = setTimeout; return function (t) { capturedSetTimeout(t, 0); }; }(_dereq_)); } return nextTick; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); })); },{}],61:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function makePromise(environment) { var tasks = environment.scheduler; var objectCreate = Object.create || function(proto) { function Child() {} Child.prototype = proto; return new Child(); }; /** * Create a promise whose fate is determined by resolver * @constructor * @returns {Promise} promise * @name Promise */ function Promise(resolver, handler) { this._handler = resolver === Handler ? handler : init(resolver); } /** * Run the supplied resolver * @param resolver * @returns {Pending} */ function init(resolver) { var handler = new Pending(); try { resolver(promiseResolve, promiseReject, promiseNotify); } catch (e) { promiseReject(e); } return handler; /** * Transition from pre-resolution state to post-resolution state, notifying * all listeners of the ultimate fulfillment or rejection * @param {*} x resolution value */ function promiseResolve (x) { handler.resolve(x); } /** * Reject this promise with reason, which will be used verbatim * @param {Error|*} reason rejection reason, strongly suggested * to be an Error type */ function promiseReject (reason) { handler.reject(reason); } /** * Issue a progress event, notifying all progress listeners * @param {*} x progress event payload to pass to all listeners */ function promiseNotify (x) { handler.notify(x); } } // Creation Promise.resolve = resolve; Promise.reject = reject; Promise.never = never; Promise._defer = defer; Promise._handler = getHandler; /** * Returns a trusted promise. If x is already a trusted promise, it is * returned, otherwise returns a new trusted Promise which follows x. * @param {*} x * @return {Promise} promise */ function resolve(x) { return isPromise(x) ? x : new Promise(Handler, new Async(getHandler(x))); } /** * Return a reject promise with x as its reason (x is used verbatim) * @param {*} x * @returns {Promise} rejected promise */ function reject(x) { return new Promise(Handler, new Async(new Rejected(x))); } /** * Return a promise that remains pending forever * @returns {Promise} forever-pending promise. */ function never() { return foreverPendingPromise; // Should be frozen } /** * Creates an internal {promise, resolver} pair * @private * @returns {Promise} */ function defer() { return new Promise(Handler, new Pending()); } // Transformation and flow control /** * Transform this promise's fulfillment value, returning a new Promise * for the transformed result. If the promise cannot be fulfilled, onRejected * is called with the reason. onProgress *may* be called with updates toward * this promise's fulfillment. * @param {function=} onFulfilled fulfillment handler * @param {function=} onRejected rejection handler * @deprecated @param {function=} onProgress progress handler * @return {Promise} new promise */ Promise.prototype.then = function(onFulfilled, onRejected) { var parent = this._handler; if (typeof onFulfilled !== 'function' && parent.join().state() > 0) { // Short circuit: value will not change, simply share handler return new Promise(Handler, parent); } var p = this._beget(); var child = p._handler; parent.chain(child, parent.receiver, onFulfilled, onRejected, arguments.length > 2 ? arguments[2] : void 0); return p; }; /** * If this promise cannot be fulfilled due to an error, call onRejected to * handle the error. Shortcut for .then(undefined, onRejected) * @param {function?} onRejected * @return {Promise} */ Promise.prototype['catch'] = function(onRejected) { return this.then(void 0, onRejected); }; /** * Creates a new, pending promise of the same type as this promise * @private * @returns {Promise} */ Promise.prototype._beget = function() { var parent = this._handler; var child = new Pending(parent.receiver, parent.join().context); return new this.constructor(Handler, child); }; // Array combinators Promise.all = all; Promise.race = race; /** * Return a promise that will fulfill when all promises in the * input array have fulfilled, or will reject when one of the * promises rejects. * @param {array} promises array of promises * @returns {Promise} promise for array of fulfillment values */ function all(promises) { /*jshint maxcomplexity:8*/ var resolver = new Pending(); var pending = promises.length >>> 0; var results = new Array(pending); var i, h, x, s; for (i = 0; i < promises.length; ++i) { x = promises[i]; if (x === void 0 && !(i in promises)) { --pending; continue; } if (maybeThenable(x)) { h = isPromise(x) ? x._handler.join() : getHandlerUntrusted(x); s = h.state(); if (s === 0) { h.fold(settleAt, i, results, resolver); } else if (s > 0) { results[i] = h.value; --pending; } else { resolver.become(h); break; } } else { results[i] = x; --pending; } } if(pending === 0) { resolver.become(new Fulfilled(results)); } return new Promise(Handler, resolver); function settleAt(i, x, resolver) { /*jshint validthis:true*/ this[i] = x; if(--pending === 0) { resolver.become(new Fulfilled(this)); } } } /** * Fulfill-reject competitive race. Return a promise that will settle * to the same state as the earliest input promise to settle. * * WARNING: The ES6 Promise spec requires that race()ing an empty array * must return a promise that is pending forever. This implementation * returns a singleton forever-pending promise, the same singleton that is * returned by Promise.never(), thus can be checked with === * * @param {array} promises array of promises to race * @returns {Promise} if input is non-empty, a promise that will settle * to the same outcome as the earliest input promise to settle. if empty * is empty, returns a promise that will never settle. */ function race(promises) { // Sigh, race([]) is untestable unless we return *something* // that is recognizable without calling .then() on it. if(Object(promises) === promises && promises.length === 0) { return never(); } var h = new Pending(); var i, x; for(i=0; i<promises.length; ++i) { x = promises[i]; if (x !== void 0 && i in promises) { getHandler(x).visit(h, h.resolve, h.reject); } } return new Promise(Handler, h); } // Promise internals // Below this, everything is @private /** * Get an appropriate handler for x, without checking for cycles * @param {*} x * @returns {object} handler */ function getHandler(x) { if(isPromise(x)) { return x._handler.join(); } return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x); } /** * Get a handler for potentially untrusted thenable x * @param {*} x * @returns {object} handler */ function getHandlerUntrusted(x) { try { var untrustedThen = x.then; return typeof untrustedThen === 'function' ? new Thenable(untrustedThen, x) : new Fulfilled(x); } catch(e) { return new Rejected(e); } } /** * Handler for a promise that is pending forever * @constructor */ function Handler() {} Handler.prototype.when = Handler.prototype.become = Handler.prototype.notify = Handler.prototype.fail = Handler.prototype._unreport = Handler.prototype._report = noop; Handler.prototype._state = 0; Handler.prototype.state = function() { return this._state; }; /** * Recursively collapse handler chain to find the handler * nearest to the fully resolved value. * @returns {object} handler nearest the fully resolved value */ Handler.prototype.join = function() { var h = this; while(h.handler !== void 0) { h = h.handler; } return h; }; Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) { this.when({ resolver: to, receiver: receiver, fulfilled: fulfilled, rejected: rejected, progress: progress }); }; Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) { this.chain(failIfRejected, receiver, fulfilled, rejected, progress); }; Handler.prototype.fold = function(f, z, c, to) { this.visit(to, function(x) { f.call(c, z, x, this); }, to.reject, to.notify); }; /** * Handler that invokes fail() on any handler it becomes * @constructor */ function FailIfRejected() {} inherit(Handler, FailIfRejected); FailIfRejected.prototype.become = function(h) { h.fail(); }; var failIfRejected = new FailIfRejected(); /** * Handler that manages a queue of consumers waiting on a pending promise * @constructor */ function Pending(receiver, inheritedContext) { Promise.createContext(this, inheritedContext); this.consumers = void 0; this.receiver = receiver; this.handler = void 0; this.resolved = false; } inherit(Handler, Pending); Pending.prototype._state = 0; Pending.prototype.resolve = function(x) { this.become(getHandler(x)); }; Pending.prototype.reject = function(x) { if(this.resolved) { return; } this.become(new Rejected(x)); }; Pending.prototype.join = function() { if (!this.resolved) { return this; } var h = this; while (h.handler !== void 0) { h = h.handler; if (h === this) { return this.handler = cycle(); } } return h; }; Pending.prototype.run = function() { var q = this.consumers; var handler = this.join(); this.consumers = void 0; for (var i = 0; i < q.length; ++i) { handler.when(q[i]); } }; Pending.prototype.become = function(handler) { if(this.resolved) { return; } this.resolved = true; this.handler = handler; if(this.consumers !== void 0) { tasks.enqueue(this); } if(this.context !== void 0) { handler._report(this.context); } }; Pending.prototype.when = function(continuation) { if(this.resolved) { tasks.enqueue(new ContinuationTask(continuation, this.handler)); } else { if(this.consumers === void 0) { this.consumers = [continuation]; } else { this.consumers.push(continuation); } } }; Pending.prototype.notify = function(x) { if(!this.resolved) { tasks.enqueue(new ProgressTask(x, this)); } }; Pending.prototype.fail = function(context) { var c = typeof context === 'undefined' ? this.context : context; this.resolved && this.handler.join().fail(c); }; Pending.prototype._report = function(context) { this.resolved && this.handler.join()._report(context); }; Pending.prototype._unreport = function() { this.resolved && this.handler.join()._unreport(); }; /** * Wrap another handler and force it into a future stack * @param {object} handler * @constructor */ function Async(handler) { this.handler = handler; } inherit(Handler, Async); Async.prototype.when = function(continuation) { tasks.enqueue(new ContinuationTask(continuation, this)); }; Async.prototype._report = function(context) { this.join()._report(context); }; Async.prototype._unreport = function() { this.join()._unreport(); }; /** * Handler that wraps an untrusted thenable and assimilates it in a future stack * @param {function} then * @param {{then: function}} thenable * @constructor */ function Thenable(then, thenable) { Pending.call(this); tasks.enqueue(new AssimilateTask(then, thenable, this)); } inherit(Pending, Thenable); /** * Handler for a fulfilled promise * @param {*} x fulfillment value * @constructor */ function Fulfilled(x) { Promise.createContext(this); this.value = x; } inherit(Handler, Fulfilled); Fulfilled.prototype._state = 1; Fulfilled.prototype.fold = function(f, z, c, to) { runContinuation3(f, z, this, c, to); }; Fulfilled.prototype.when = function(cont) { runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver); }; var errorId = 0; /** * Handler for a rejected promise * @param {*} x rejection reason * @constructor */ function Rejected(x) { Promise.createContext(this); this.id = ++errorId; this.value = x; this.handled = false; this.reported = false; this._report(); } inherit(Handler, Rejected); Rejected.prototype._state = -1; Rejected.prototype.fold = function(f, z, c, to) { to.become(this); }; Rejected.prototype.when = function(cont) { if(typeof cont.rejected === 'function') { this._unreport(); } runContinuation1(cont.rejected, this, cont.receiver, cont.resolver); }; Rejected.prototype._report = function(context) { tasks.afterQueue(new ReportTask(this, context)); }; Rejected.prototype._unreport = function() { this.handled = true; tasks.afterQueue(new UnreportTask(this)); }; Rejected.prototype.fail = function(context) { Promise.onFatalRejection(this, context === void 0 ? this.context : context); }; function ReportTask(rejection, context) { this.rejection = rejection; this.context = context; } ReportTask.prototype.run = function() { if(!this.rejection.handled) { this.rejection.reported = true; Promise.onPotentiallyUnhandledRejection(this.rejection, this.context); } }; function UnreportTask(rejection) { this.rejection = rejection; } UnreportTask.prototype.run = function() { if(this.rejection.reported) { Promise.onPotentiallyUnhandledRejectionHandled(this.rejection); } }; // Unhandled rejection hooks // By default, everything is a noop // TODO: Better names: "annotate"? Promise.createContext = Promise.enterContext = Promise.exitContext = Promise.onPotentiallyUnhandledRejection = Promise.onPotentiallyUnhandledRejectionHandled = Promise.onFatalRejection = noop; // Errors and singletons var foreverPendingHandler = new Handler(); var foreverPendingPromise = new Promise(Handler, foreverPendingHandler); function cycle() { return new Rejected(new TypeError('Promise cycle')); } // Task runners /** * Run a single consumer * @constructor */ function ContinuationTask(continuation, handler) { this.continuation = continuation; this.handler = handler; } ContinuationTask.prototype.run = function() { this.handler.join().when(this.continuation); }; /** * Run a queue of progress handlers * @constructor */ function ProgressTask(value, handler) { this.handler = handler; this.value = value; } ProgressTask.prototype.run = function() { var q = this.handler.consumers; if(q === void 0) { return; } for (var c, i = 0; i < q.length; ++i) { c = q[i]; runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver); } }; /** * Assimilate a thenable, sending it's value to resolver * @param {function} then * @param {object|function} thenable * @param {object} resolver * @constructor */ function AssimilateTask(then, thenable, resolver) { this._then = then; this.thenable = thenable; this.resolver = resolver; } AssimilateTask.prototype.run = function() { var h = this.resolver; tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify); function _resolve(x) { h.resolve(x); } function _reject(x) { h.reject(x); } function _notify(x) { h.notify(x); } }; function tryAssimilate(then, thenable, resolve, reject, notify) { try { then.call(thenable, resolve, reject, notify); } catch (e) { reject(e); } } // Other helpers /** * @param {*} x * @returns {boolean} true iff x is a trusted Promise */ function isPromise(x) { return x instanceof Promise; } /** * Test just enough to rule out primitives, in order to take faster * paths in some code * @param {*} x * @returns {boolean} false iff x is guaranteed *not* to be a thenable */ function maybeThenable(x) { return (typeof x === 'object' || typeof x === 'function') && x !== null; } function runContinuation1(f, h, receiver, next) { if(typeof f !== 'function') { return next.become(h); } Promise.enterContext(h); tryCatchReject(f, h.value, receiver, next); Promise.exitContext(); } function runContinuation3(f, x, h, receiver, next) { if(typeof f !== 'function') { return next.become(h); } Promise.enterContext(h); tryCatchReject3(f, x, h.value, receiver, next); Promise.exitContext(); } function runNotify(f, x, h, receiver, next) { if(typeof f !== 'function') { return next.notify(x); } Promise.enterContext(h); tryCatchReturn(f, x, receiver, next); Promise.exitContext(); } /** * Return f.call(thisArg, x), or if it throws return a rejected promise for * the thrown exception */ function tryCatchReject(f, x, thisArg, next) { try { next.become(getHandler(f.call(thisArg, x))); } catch(e) { next.become(new Rejected(e)); } } /** * Same as above, but includes the extra argument parameter. */ function tryCatchReject3(f, x, y, thisArg, next) { try { f.call(thisArg, x, y, next); } catch(e) { next.become(new Rejected(e)); } } /** * Return f.call(thisArg, x), or if it throws, *return* the exception */ function tryCatchReturn(f, x, thisArg, next) { try { next.notify(f.call(thisArg, x)); } catch(e) { next.notify(e); } } function inherit(Parent, Child) { Child.prototype = objectCreate(Parent.prototype); Child.prototype.constructor = Child; } function noop() {} return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],62:[function(_dereq_,module,exports){ module.exports = _dereq_('./modules/actions/LocationActions').replaceWith; },{"./modules/actions/LocationActions":12}],63:[function(_dereq_,module,exports){ module.exports = _dereq_('./modules/actions/LocationActions').transitionTo; },{"./modules/actions/LocationActions":12}]},{},[10]) (10) });
client/render/render.dev.js
ADI-Labs/calendar-web
import React from 'react' import ReactDOM from 'react-dom' import { match, browserHistory } from 'react-router' import { syncHistoryWithStore } from 'react-router-redux' import DevTools from 'app/containers/DevTools' import configureStore from 'app/store/configureStore' import routes from 'app/routes' let render = (rootElement = 'root', devElement = 'dev-tools') => { const App = require('app').default const store = configureStore(window.__INITIAL_STATE__) const history = syncHistoryWithStore( browserHistory, store, { selectLocationState: state => state.get('routing') } ) const appMountNode = document.getElementById(rootElement) const devToolsMountNode = document.getElementById(devElement) match({ history, routes }, (error, redirectLocation, renderProps) => { ReactDOM.render(<App store={ store } { ...renderProps } />, appMountNode) ReactDOM.render(<DevTools store={ store } />, devToolsMountNode) }) } if (module.hot) { // Support hot reloading of components // and display an overlay for runtime errors const renderApp = render const renderError = (error, rootElement = 'root') => { const RedBox = require('redbox-react').default const mountNode = document.getElementById(rootElement) ReactDOM.render( <RedBox error={ error } />, mountNode ) } render = () => { try { renderApp() } catch (error) { renderError(error) } } module.hot.accept('app', render) } export default render
files/popcorn.js/1.3/popcorn.js
bzmwillemsen/jsdelivr
/* * popcorn.js version 1.3 * http://popcornjs.org * * Copyright 2011, Mozilla Foundation * Licensed under the MIT license */ (function(global, document) { // Popcorn.js does not support archaic browsers if ( !document.addEventListener ) { global.Popcorn = { isSupported: false }; var methods = ( "byId forEach extend effects error guid sizeOf isArray nop position disable enable destroy" + "addTrackEvent removeTrackEvent getTrackEvents getTrackEvent getLastTrackEventId " + "timeUpdate plugin removePlugin compose effect xhr getJSONP getScript" ).split(/\s+/); while ( methods.length ) { global.Popcorn[ methods.shift() ] = function() {}; } return; } var AP = Array.prototype, OP = Object.prototype, forEach = AP.forEach, slice = AP.slice, hasOwn = OP.hasOwnProperty, toString = OP.toString, // Copy global Popcorn (may not exist) _Popcorn = global.Popcorn, // Ready fn cache readyStack = [], readyBound = false, readyFired = false, // Non-public internal data object internal = { events: { hash: {}, apis: {} } }, // Non-public `requestAnimFrame` // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ requestAnimFrame = (function(){ return global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame || global.msRequestAnimationFrame || function( callback, element ) { global.setTimeout( callback, 16 ); }; }()), // Non-public `getKeys`, return an object's keys as an array getKeys = function( obj ) { return Object.keys ? Object.keys( obj ) : (function( obj ) { var item, list = []; for ( item in obj ) { if ( hasOwn.call( obj, item ) ) { list.push( item ); } } return list; })( obj ); }, // Declare constructor // Returns an instance object. Popcorn = function( entity, options ) { // Return new Popcorn object return new Popcorn.p.init( entity, options || null ); }; // Popcorn API version, automatically inserted via build system. Popcorn.version = "1.3"; // Boolean flag allowing a client to determine if Popcorn can be supported Popcorn.isSupported = true; // Instance caching Popcorn.instances = []; // Declare a shortcut (Popcorn.p) to and a definition of // the new prototype for our Popcorn constructor Popcorn.p = Popcorn.prototype = { init: function( entity, options ) { var matches, nodeName, self = this; // Supports Popcorn(function () { /../ }) // Originally proposed by Daniel Brooks if ( typeof entity === "function" ) { // If document ready has already fired if ( document.readyState === "complete" ) { entity( document, Popcorn ); return; } // Add `entity` fn to ready stack readyStack.push( entity ); // This process should happen once per page load if ( !readyBound ) { // set readyBound flag readyBound = true; var DOMContentLoaded = function() { readyFired = true; // Remove global DOM ready listener document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // Execute all ready function in the stack for ( var i = 0, readyStackLength = readyStack.length; i < readyStackLength; i++ ) { readyStack[ i ].call( document, Popcorn ); } // GC readyStack readyStack = null; }; // Register global DOM ready listener document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); } return; } if ( typeof entity === "string" ) { try { matches = document.querySelector( entity ); } catch( e ) { throw new Error( "Popcorn.js Error: Invalid media element selector: " + entity ); } } // Get media element by id or object reference this.media = matches || entity; // inner reference to this media element's nodeName string value nodeName = ( this.media.nodeName && this.media.nodeName.toLowerCase() ) || "video"; // Create an audio or video element property reference this[ nodeName ] = this.media; this.options = options || {}; // Resolve custom ID or default prefixed ID this.id = this.options.id || Popcorn.guid( nodeName ); // Throw if an attempt is made to use an ID that already exists if ( Popcorn.byId( this.id ) ) { throw new Error( "Popcorn.js Error: Cannot use duplicate ID (" + this.id + ")" ); } this.isDestroyed = false; this.data = { // data structure of all running: { cue: [] }, // Executed by either timeupdate event or in rAF loop timeUpdate: Popcorn.nop, // Allows disabling a plugin per instance disabled: {}, // Stores DOM event queues by type events: {}, // Stores Special event hooks data hooks: {}, // Store track event history data history: [], // Stores ad-hoc state related data] state: { volume: this.media.volume }, // Store track event object references by trackId trackRefs: {}, // Playback track event queues trackEvents: { byStart: [{ start: -1, end: -1 }], byEnd: [{ start: -1, end: -1 }], animating: [], startIndex: 0, endIndex: 0, previousUpdateTime: -1 } }; // Register new instance Popcorn.instances.push( this ); // function to fire when video is ready var isReady = function() { // chrome bug: http://code.google.com/p/chromium/issues/detail?id=119598 // it is possible the video's time is less than 0 // this has the potential to call track events more than once, when they should not // start: 0, end: 1 will start, end, start again, when it should just start // just setting it to 0 if it is below 0 fixes this issue if ( self.media.currentTime < 0 ) { self.media.currentTime = 0; } self.media.removeEventListener( "loadeddata", isReady, false ); var duration, videoDurationPlus, runningPlugins, runningPlugin, rpLength, rpNatives; // Adding padding to the front and end of the arrays // this is so we do not fall off either end duration = self.media.duration; // Check for no duration info (NaN) videoDurationPlus = duration != duration ? Number.MAX_VALUE : duration + 1; Popcorn.addTrackEvent( self, { start: videoDurationPlus, end: videoDurationPlus }); if ( self.options.frameAnimation ) { // if Popcorn is created with frameAnimation option set to true, // requestAnimFrame is used instead of "timeupdate" media event. // This is for greater frame time accuracy, theoretically up to // 60 frames per second as opposed to ~4 ( ~every 15-250ms) self.data.timeUpdate = function () { Popcorn.timeUpdate( self, {} ); // fire frame for each enabled active plugin of every type Popcorn.forEach( Popcorn.manifest, function( key, val ) { runningPlugins = self.data.running[ val ]; // ensure there are running plugins on this type on this instance if ( runningPlugins ) { rpLength = runningPlugins.length; for ( var i = 0; i < rpLength; i++ ) { runningPlugin = runningPlugins[ i ]; rpNatives = runningPlugin._natives; rpNatives && rpNatives.frame && rpNatives.frame.call( self, {}, runningPlugin, self.currentTime() ); } } }); self.emit( "timeupdate" ); !self.isDestroyed && requestAnimFrame( self.data.timeUpdate ); }; !self.isDestroyed && requestAnimFrame( self.data.timeUpdate ); } else { self.data.timeUpdate = function( event ) { Popcorn.timeUpdate( self, event ); }; if ( !self.isDestroyed ) { self.media.addEventListener( "timeupdate", self.data.timeUpdate, false ); } } }; Object.defineProperty( this, "error", { get: function() { return self.media.error; } }); if ( self.media.readyState >= 2 ) { isReady(); } else { self.media.addEventListener( "loadeddata", isReady, false ); } return this; } }; // Extend constructor prototype to instance prototype // Allows chaining methods to instances Popcorn.p.init.prototype = Popcorn.p; Popcorn.byId = function( str ) { var instances = Popcorn.instances, length = instances.length, i = 0; for ( ; i < length; i++ ) { if ( instances[ i ].id === str ) { return instances[ i ]; } } return null; }; Popcorn.forEach = function( obj, fn, context ) { if ( !obj || !fn ) { return {}; } context = context || this; var key, len; // Use native whenever possible if ( forEach && obj.forEach === forEach ) { return obj.forEach( fn, context ); } if ( toString.call( obj ) === "[object NodeList]" ) { for ( key = 0, len = obj.length; key < len; key++ ) { fn.call( context, obj[ key ], key, obj ); } return obj; } for ( key in obj ) { if ( hasOwn.call( obj, key ) ) { fn.call( context, obj[ key ], key, obj ); } } return obj; }; Popcorn.extend = function( obj ) { var dest = obj, src = slice.call( arguments, 1 ); Popcorn.forEach( src, function( copy ) { for ( var prop in copy ) { dest[ prop ] = copy[ prop ]; } }); return dest; }; // A Few reusable utils, memoized onto Popcorn Popcorn.extend( Popcorn, { noConflict: function( deep ) { if ( deep ) { global.Popcorn = _Popcorn; } return Popcorn; }, error: function( msg ) { throw new Error( msg ); }, guid: function( prefix ) { Popcorn.guid.counter++; return ( prefix ? prefix : "" ) + ( +new Date() + Popcorn.guid.counter ); }, sizeOf: function( obj ) { var size = 0; for ( var prop in obj ) { size++; } return size; }, isArray: Array.isArray || function( array ) { return toString.call( array ) === "[object Array]"; }, nop: function() {}, position: function( elem ) { var clientRect = elem.getBoundingClientRect(), bounds = {}, doc = elem.ownerDocument, docElem = document.documentElement, body = document.body, clientTop, clientLeft, scrollTop, scrollLeft, top, left; // Determine correct clientTop/Left clientTop = docElem.clientTop || body.clientTop || 0; clientLeft = docElem.clientLeft || body.clientLeft || 0; // Determine correct scrollTop/Left scrollTop = ( global.pageYOffset && docElem.scrollTop || body.scrollTop ); scrollLeft = ( global.pageXOffset && docElem.scrollLeft || body.scrollLeft ); // Temp top/left top = Math.ceil( clientRect.top + scrollTop - clientTop ); left = Math.ceil( clientRect.left + scrollLeft - clientLeft ); for ( var p in clientRect ) { bounds[ p ] = Math.round( clientRect[ p ] ); } return Popcorn.extend({}, bounds, { top: top, left: left }); }, disable: function( instance, plugin ) { if ( !instance.data.disabled[ plugin ] ) { instance.data.disabled[ plugin ] = true; for ( var i = instance.data.running[ plugin ].length - 1, event; i >= 0; i-- ) { event = instance.data.running[ plugin ][ i ]; event._natives.end.call( instance, null, event ); } } return instance; }, enable: function( instance, plugin ) { if ( instance.data.disabled[ plugin ] ) { instance.data.disabled[ plugin ] = false; for ( var i = instance.data.running[ plugin ].length - 1, event; i >= 0; i-- ) { event = instance.data.running[ plugin ][ i ]; event._natives.start.call( instance, null, event ); } } return instance; }, destroy: function( instance ) { var events = instance.data.events, trackEvents = instance.data.trackEvents, singleEvent, item, fn, plugin; // Iterate through all events and remove them for ( item in events ) { singleEvent = events[ item ]; for ( fn in singleEvent ) { delete singleEvent[ fn ]; } events[ item ] = null; } // remove all plugins off the given instance for ( plugin in Popcorn.registryByName ) { Popcorn.removePlugin( instance, plugin ); } // Remove all data.trackEvents #1178 trackEvents.byStart.length = 0; trackEvents.byEnd.length = 0; if ( !instance.isDestroyed ) { instance.data.timeUpdate && instance.media.removeEventListener( "timeupdate", instance.data.timeUpdate, false ); instance.isDestroyed = true; } } }); // Memoized GUID Counter Popcorn.guid.counter = 1; // Factory to implement getters, setters and controllers // as Popcorn instance methods. The IIFE will create and return // an object with defined methods Popcorn.extend(Popcorn.p, (function() { var methods = "load play pause currentTime playbackRate volume duration preload playbackRate " + "autoplay loop controls muted buffered readyState seeking paused played seekable ended", ret = {}; // Build methods, store in object that is returned and passed to extend Popcorn.forEach( methods.split( /\s+/g ), function( name ) { ret[ name ] = function( arg ) { var previous; if ( typeof this.media[ name ] === "function" ) { // Support for shorthanded play(n)/pause(n) jump to currentTime // If arg is not null or undefined and called by one of the // allowed shorthandable methods, then set the currentTime // Supports time as seconds or SMPTE if ( arg != null && /play|pause/.test( name ) ) { this.media.currentTime = Popcorn.util.toSeconds( arg ); } this.media[ name ](); return this; } if ( arg != null ) { // Capture the current value of the attribute property previous = this.media[ name ]; // Set the attribute property with the new value this.media[ name ] = arg; // If the new value is not the same as the old value // emit an "attrchanged event" if ( previous !== arg ) { this.emit( "attrchange", { attribute: name, previousValue: previous, currentValue: arg }); } return this; } return this.media[ name ]; }; }); return ret; })() ); Popcorn.forEach( "enable disable".split(" "), function( method ) { Popcorn.p[ method ] = function( plugin ) { return Popcorn[ method ]( this, plugin ); }; }); Popcorn.extend(Popcorn.p, { // Rounded currentTime roundTime: function() { return Math.round( this.media.currentTime ); }, // Attach an event to a single point in time exec: function( id, time, fn ) { var length = arguments.length, trackEvent, sec; // Check if first could possibly be a SMPTE string // p.cue( "smpte string", fn ); // try/catch avoid awful throw in Popcorn.util.toSeconds // TODO: Get rid of that, replace with NaN return? try { sec = Popcorn.util.toSeconds( id ); } catch ( e ) {} // If it can be converted into a number then // it's safe to assume that the string was SMPTE if ( typeof sec === "number" ) { id = sec; } // Shift arguments based on use case // // Back compat for: // p.cue( time, fn ); if ( typeof id === "number" && length === 2 ) { fn = time; time = id; id = Popcorn.guid( "cue" ); } else { // Support for new forms // p.cue( "empty-cue" ); if ( length === 1 ) { // Set a time for an empty cue. It's not important what // the time actually is, because the cue is a no-op time = -1; } else { // Get the trackEvent that matches the given id. trackEvent = this.getTrackEvent( id ); if ( trackEvent ) { // p.cue( "my-id", 12 ); // p.cue( "my-id", function() { ... }); if ( typeof id === "string" && length === 2 ) { // p.cue( "my-id", 12 ); // The path will update the cue time. if ( typeof time === "number" ) { // Re-use existing trackEvent start callback fn = trackEvent._natives.start; } // p.cue( "my-id", function() { ... }); // The path will update the cue function if ( typeof time === "function" ) { fn = time; // Re-use existing trackEvent start time time = trackEvent.start; } } } else { if ( length >= 2 ) { // p.cue( "a", "00:00:00"); if ( typeof time === "string" ) { try { sec = Popcorn.util.toSeconds( time ); } catch ( e ) {} time = sec; } // p.cue( "b", 11 ); if ( typeof time === "number" ) { fn = Popcorn.nop(); } // p.cue( "c", function() {}); if ( typeof time === "function" ) { fn = time; time = -1; } } } } } // Creating a one second track event with an empty end // Or update an existing track event with new values Popcorn.addTrackEvent( this, { id: id, start: time, end: time + 1, _running: false, _natives: { start: fn || Popcorn.nop, end: Popcorn.nop, type: "cue" } }); return this; }, // Mute the calling media, optionally toggle mute: function( toggle ) { var event = toggle == null || toggle === true ? "muted" : "unmuted"; // If `toggle` is explicitly `false`, // unmute the media and restore the volume level if ( event === "unmuted" ) { this.media.muted = false; this.media.volume = this.data.state.volume; } // If `toggle` is either null or undefined, // save the current volume and mute the media element if ( event === "muted" ) { this.data.state.volume = this.media.volume; this.media.muted = true; } // Trigger either muted|unmuted event this.emit( event ); return this; }, // Convenience method, unmute the calling media unmute: function( toggle ) { return this.mute( toggle == null ? false : !toggle ); }, // Get the client bounding box of an instance element position: function() { return Popcorn.position( this.media ); }, // Toggle a plugin's playback behaviour (on or off) per instance toggle: function( plugin ) { return Popcorn[ this.data.disabled[ plugin ] ? "enable" : "disable" ]( this, plugin ); }, // Set default values for plugin options objects per instance defaults: function( plugin, defaults ) { // If an array of default configurations is provided, // iterate and apply each to this instance if ( Popcorn.isArray( plugin ) ) { Popcorn.forEach( plugin, function( obj ) { for ( var name in obj ) { this.defaults( name, obj[ name ] ); } }, this ); return this; } if ( !this.options.defaults ) { this.options.defaults = {}; } if ( !this.options.defaults[ plugin ] ) { this.options.defaults[ plugin ] = {}; } Popcorn.extend( this.options.defaults[ plugin ], defaults ); return this; } }); Popcorn.Events = { UIEvents: "blur focus focusin focusout load resize scroll unload", MouseEvents: "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave click dblclick", Events: "loadstart progress suspend emptied stalled play pause error " + "loadedmetadata loadeddata waiting playing canplay canplaythrough " + "seeking seeked timeupdate ended ratechange durationchange volumechange" }; Popcorn.Events.Natives = Popcorn.Events.UIEvents + " " + Popcorn.Events.MouseEvents + " " + Popcorn.Events.Events; internal.events.apiTypes = [ "UIEvents", "MouseEvents", "Events" ]; // Privately compile events table at load time (function( events, data ) { var apis = internal.events.apiTypes, eventsList = events.Natives.split( /\s+/g ), idx = 0, len = eventsList.length, prop; for( ; idx < len; idx++ ) { data.hash[ eventsList[idx] ] = true; } apis.forEach(function( val, idx ) { data.apis[ val ] = {}; var apiEvents = events[ val ].split( /\s+/g ), len = apiEvents.length, k = 0; for ( ; k < len; k++ ) { data.apis[ val ][ apiEvents[ k ] ] = true; } }); })( Popcorn.Events, internal.events ); Popcorn.events = { isNative: function( type ) { return !!internal.events.hash[ type ]; }, getInterface: function( type ) { if ( !Popcorn.events.isNative( type ) ) { return false; } var eventApi = internal.events, apis = eventApi.apiTypes, apihash = eventApi.apis, idx = 0, len = apis.length, api, tmp; for ( ; idx < len; idx++ ) { tmp = apis[ idx ]; if ( apihash[ tmp ][ type ] ) { api = tmp; break; } } return api; }, // Compile all native events to single array all: Popcorn.Events.Natives.split( /\s+/g ), // Defines all Event handling static functions fn: { trigger: function( type, data ) { var eventInterface, evt; // setup checks for custom event system if ( this.data.events[ type ] && Popcorn.sizeOf( this.data.events[ type ] ) ) { eventInterface = Popcorn.events.getInterface( type ); if ( eventInterface ) { evt = document.createEvent( eventInterface ); evt.initEvent( type, true, true, global, 1 ); this.media.dispatchEvent( evt ); return this; } // Custom events Popcorn.forEach( this.data.events[ type ], function( obj, key ) { obj.call( this, data ); }, this ); } return this; }, listen: function( type, fn ) { var self = this, hasEvents = true, eventHook = Popcorn.events.hooks[ type ], origType = type, tmp; if ( !this.data.events[ type ] ) { this.data.events[ type ] = {}; hasEvents = false; } // Check and setup event hooks if ( eventHook ) { // Execute hook add method if defined if ( eventHook.add ) { eventHook.add.call( this, {}, fn ); } // Reassign event type to our piggyback event type if defined if ( eventHook.bind ) { type = eventHook.bind; } // Reassign handler if defined if ( eventHook.handler ) { tmp = fn; fn = function wrapper( event ) { eventHook.handler.call( self, event, tmp ); }; } // assume the piggy back event is registered hasEvents = true; // Setup event registry entry if ( !this.data.events[ type ] ) { this.data.events[ type ] = {}; // Toggle if the previous assumption was untrue hasEvents = false; } } // Register event and handler this.data.events[ type ][ fn.name || ( fn.toString() + Popcorn.guid() ) ] = fn; // only attach one event of any type if ( !hasEvents && Popcorn.events.all.indexOf( type ) > -1 ) { this.media.addEventListener( type, function( event ) { Popcorn.forEach( self.data.events[ type ], function( obj, key ) { if ( typeof obj === "function" ) { obj.call( self, event ); } }); }, false); } return this; }, unlisten: function( type, fn ) { if ( this.data.events[ type ] && this.data.events[ type ][ fn ] ) { delete this.data.events[ type ][ fn ]; return this; } this.data.events[ type ] = null; return this; } }, hooks: { canplayall: { bind: "canplaythrough", add: function( event, callback ) { var state = false; if ( this.media.readyState ) { callback.call( this, event ); state = true; } this.data.hooks.canplayall = { fired: state }; }, // declare special handling instructions handler: function canplayall( event, callback ) { if ( !this.data.hooks.canplayall.fired ) { // trigger original user callback once callback.call( this, event ); this.data.hooks.canplayall.fired = true; } } } } }; // Extend Popcorn.events.fns (listen, unlisten, trigger) to all Popcorn instances // Extend aliases (on, off, emit) Popcorn.forEach( [ [ "trigger", "emit" ], [ "listen", "on" ], [ "unlisten", "off" ] ], function( key ) { Popcorn.p[ key[ 0 ] ] = Popcorn.p[ key[ 1 ] ] = Popcorn.events.fn[ key[ 0 ] ]; }); // Internal Only - Adds track events to the instance object Popcorn.addTrackEvent = function( obj, track ) { var trackEvent, isUpdate, eventType; // Do a lookup for existing trackevents with this id if ( track.id ) { trackEvent = obj.getTrackEvent( track.id ); } // If a track event by this id currently exists, modify it if ( trackEvent ) { isUpdate = true; // Create a new object with the existing trackEvent // Extend with new track properties track = Popcorn.extend( {}, trackEvent, track ); // Remove the existing track from the instance obj.removeTrackEvent( track.id ); } // Determine if this track has default options set for it // If so, apply them to the track object if ( track && track._natives && track._natives.type && ( obj.options.defaults && obj.options.defaults[ track._natives.type ] ) ) { track = Popcorn.extend( {}, obj.options.defaults[ track._natives.type ], track ); } if ( track._natives ) { // Supports user defined track event id track._id = track.id || track._id || Popcorn.guid( track._natives.type ); // Push track event ids into the history obj.data.history.push( track._id ); } track.start = Popcorn.util.toSeconds( track.start, obj.options.framerate ); track.end = Popcorn.util.toSeconds( track.end, obj.options.framerate ); // Store this definition in an array sorted by times var byStart = obj.data.trackEvents.byStart, byEnd = obj.data.trackEvents.byEnd, startIndex, endIndex; for ( startIndex = byStart.length - 1; startIndex >= 0; startIndex-- ) { if ( track.start >= byStart[ startIndex ].start ) { byStart.splice( startIndex + 1, 0, track ); break; } } for ( endIndex = byEnd.length - 1; endIndex >= 0; endIndex-- ) { if ( track.end > byEnd[ endIndex ].end ) { byEnd.splice( endIndex + 1, 0, track ); break; } } // Display track event immediately if it's enabled and current if ( track.end > obj.media.currentTime && track.start <= obj.media.currentTime ) { track._running = true; obj.data.running[ track._natives.type ].push( track ); if ( !obj.data.disabled[ track._natives.type ] ) { track._natives.start.call( obj, null, track ); } } // update startIndex and endIndex if ( startIndex <= obj.data.trackEvents.startIndex && track.start <= obj.data.trackEvents.previousUpdateTime ) { obj.data.trackEvents.startIndex++; } if ( endIndex <= obj.data.trackEvents.endIndex && track.end < obj.data.trackEvents.previousUpdateTime ) { obj.data.trackEvents.endIndex++; } this.timeUpdate( obj, null, true ); // Store references to user added trackevents in ref table if ( track._id ) { Popcorn.addTrackEvent.ref( obj, track ); } // If the call to addTrackEvent was an update/modify call, fire an event if ( isUpdate ) { // Determine appropriate event type to trigger // they are identical in function, but the naming // adds some level of intuition for the end developer // to rely on if ( track._natives.type === "cue" ) { eventType = "cuechange"; } else { eventType = "trackchange"; } // Fire an event with change information obj.emit( eventType, { id: track.id, previousValue: { time: trackEvent.start, fn: trackEvent._natives.start }, currentValue: { time: track.start, fn: track._natives.start } }); } }; // Internal Only - Adds track event references to the instance object's trackRefs hash table Popcorn.addTrackEvent.ref = function( obj, track ) { obj.data.trackRefs[ track._id ] = track; return obj; }; Popcorn.removeTrackEvent = function( obj, removeId ) { var start, end, animate, historyLen = obj.data.history.length, length = obj.data.trackEvents.byStart.length, index = 0, indexWasAt = 0, byStart = [], byEnd = [], animating = [], history = []; while ( --length > -1 ) { start = obj.data.trackEvents.byStart[ index ]; end = obj.data.trackEvents.byEnd[ index ]; // Padding events will not have _id properties. // These should be safely pushed onto the front and back of the // track event array if ( !start._id ) { byStart.push( start ); byEnd.push( end ); } // Filter for user track events (vs system track events) if ( start._id ) { // If not a matching start event for removal if ( start._id !== removeId ) { byStart.push( start ); } // If not a matching end event for removal if ( end._id !== removeId ) { byEnd.push( end ); } // If the _id is matched, capture the current index if ( start._id === removeId ) { indexWasAt = index; // If a _teardown function was defined, // enforce for track event removals if ( start._natives._teardown ) { start._natives._teardown.call( obj, start ); } } } // Increment the track index index++; } // Reset length to be used by the condition below to determine // if animating track events should also be filtered for removal. // Reset index below to be used by the reverse while as an // incrementing counter length = obj.data.trackEvents.animating.length; index = 0; if ( length ) { while ( --length > -1 ) { animate = obj.data.trackEvents.animating[ index ]; // Padding events will not have _id properties. // These should be safely pushed onto the front and back of the // track event array if ( !animate._id ) { animating.push( animate ); } // If not a matching animate event for removal if ( animate._id && animate._id !== removeId ) { animating.push( animate ); } // Increment the track index index++; } } // Update if ( indexWasAt <= obj.data.trackEvents.startIndex ) { obj.data.trackEvents.startIndex--; } if ( indexWasAt <= obj.data.trackEvents.endIndex ) { obj.data.trackEvents.endIndex--; } obj.data.trackEvents.byStart = byStart; obj.data.trackEvents.byEnd = byEnd; obj.data.trackEvents.animating = animating; for ( var i = 0; i < historyLen; i++ ) { if ( obj.data.history[ i ] !== removeId ) { history.push( obj.data.history[ i ] ); } } // Update ordered history array obj.data.history = history; // Update track event references Popcorn.removeTrackEvent.ref( obj, removeId ); }; // Internal Only - Removes track event references from instance object's trackRefs hash table Popcorn.removeTrackEvent.ref = function( obj, removeId ) { delete obj.data.trackRefs[ removeId ]; return obj; }; // Return an array of track events bound to this instance object Popcorn.getTrackEvents = function( obj ) { var trackevents = [], refs = obj.data.trackEvents.byStart, length = refs.length, idx = 0, ref; for ( ; idx < length; idx++ ) { ref = refs[ idx ]; // Return only user attributed track event references if ( ref._id ) { trackevents.push( ref ); } } return trackevents; }; // Internal Only - Returns an instance object's trackRefs hash table Popcorn.getTrackEvents.ref = function( obj ) { return obj.data.trackRefs; }; // Return a single track event bound to this instance object Popcorn.getTrackEvent = function( obj, trackId ) { return obj.data.trackRefs[ trackId ]; }; // Internal Only - Returns an instance object's track reference by track id Popcorn.getTrackEvent.ref = function( obj, trackId ) { return obj.data.trackRefs[ trackId ]; }; Popcorn.getLastTrackEventId = function( obj ) { return obj.data.history[ obj.data.history.length - 1 ]; }; Popcorn.timeUpdate = function( obj, event ) { var currentTime = obj.media.currentTime, previousTime = obj.data.trackEvents.previousUpdateTime, tracks = obj.data.trackEvents, end = tracks.endIndex, start = tracks.startIndex, byStartLen = tracks.byStart.length, byEndLen = tracks.byEnd.length, registryByName = Popcorn.registryByName, trackstart = "trackstart", trackend = "trackend", byEnd, byStart, byAnimate, natives, type, runningPlugins; // Playbar advancing if ( previousTime <= currentTime ) { while ( tracks.byEnd[ end ] && tracks.byEnd[ end ].end <= currentTime ) { byEnd = tracks.byEnd[ end ]; natives = byEnd._natives; type = natives && natives.type; // If plugin does not exist on this instance, remove it if ( !natives || ( !!registryByName[ type ] || !!obj[ type ] ) ) { if ( byEnd._running === true ) { byEnd._running = false; runningPlugins = obj.data.running[ type ]; runningPlugins.splice( runningPlugins.indexOf( byEnd ), 1 ); if ( !obj.data.disabled[ type ] ) { natives.end.call( obj, event, byEnd ); obj.emit( trackend, Popcorn.extend({}, byEnd, { plugin: type, type: trackend }) ); } } end++; } else { // remove track event Popcorn.removeTrackEvent( obj, byEnd._id ); return; } } while ( tracks.byStart[ start ] && tracks.byStart[ start ].start <= currentTime ) { byStart = tracks.byStart[ start ]; natives = byStart._natives; type = natives && natives.type; // If plugin does not exist on this instance, remove it if ( !natives || ( !!registryByName[ type ] || !!obj[ type ] ) ) { if ( byStart.end > currentTime && byStart._running === false ) { byStart._running = true; obj.data.running[ type ].push( byStart ); if ( !obj.data.disabled[ type ] ) { natives.start.call( obj, event, byStart ); obj.emit( trackstart, Popcorn.extend({}, byStart, { plugin: type, type: trackstart }) ); } } start++; } else { // remove track event Popcorn.removeTrackEvent( obj, byStart._id ); return; } } // Playbar receding } else if ( previousTime > currentTime ) { while ( tracks.byStart[ start ] && tracks.byStart[ start ].start > currentTime ) { byStart = tracks.byStart[ start ]; natives = byStart._natives; type = natives && natives.type; // if plugin does not exist on this instance, remove it if ( !natives || ( !!registryByName[ type ] || !!obj[ type ] ) ) { if ( byStart._running === true ) { byStart._running = false; runningPlugins = obj.data.running[ type ]; runningPlugins.splice( runningPlugins.indexOf( byStart ), 1 ); if ( !obj.data.disabled[ type ] ) { natives.end.call( obj, event, byStart ); obj.emit( trackend, Popcorn.extend({}, byStart, { plugin: type, type: trackend }) ); } } start--; } else { // remove track event Popcorn.removeTrackEvent( obj, byStart._id ); return; } } while ( tracks.byEnd[ end ] && tracks.byEnd[ end ].end > currentTime ) { byEnd = tracks.byEnd[ end ]; natives = byEnd._natives; type = natives && natives.type; // if plugin does not exist on this instance, remove it if ( !natives || ( !!registryByName[ type ] || !!obj[ type ] ) ) { if ( byEnd.start <= currentTime && byEnd._running === false ) { byEnd._running = true; obj.data.running[ type ].push( byEnd ); if ( !obj.data.disabled[ type ] ) { natives.start.call( obj, event, byEnd ); obj.emit( trackstart, Popcorn.extend({}, byEnd, { plugin: type, type: trackstart }) ); } } end--; } else { // remove track event Popcorn.removeTrackEvent( obj, byEnd._id ); return; } } } tracks.endIndex = end; tracks.startIndex = start; tracks.previousUpdateTime = currentTime; //enforce index integrity if trackRemoved tracks.byStart.length < byStartLen && tracks.startIndex--; tracks.byEnd.length < byEndLen && tracks.endIndex--; }; // Map and Extend TrackEvent functions to all Popcorn instances Popcorn.extend( Popcorn.p, { getTrackEvents: function() { return Popcorn.getTrackEvents.call( null, this ); }, getTrackEvent: function( id ) { return Popcorn.getTrackEvent.call( null, this, id ); }, getLastTrackEventId: function() { return Popcorn.getLastTrackEventId.call( null, this ); }, removeTrackEvent: function( id ) { Popcorn.removeTrackEvent.call( null, this, id ); return this; }, removePlugin: function( name ) { Popcorn.removePlugin.call( null, this, name ); return this; }, timeUpdate: function( event ) { Popcorn.timeUpdate.call( null, this, event ); return this; }, destroy: function() { Popcorn.destroy.call( null, this ); return this; } }); // Plugin manifests Popcorn.manifest = {}; // Plugins are registered Popcorn.registry = []; Popcorn.registryByName = {}; // An interface for extending Popcorn // with plugin functionality Popcorn.plugin = function( name, definition, manifest ) { if ( Popcorn.protect.natives.indexOf( name.toLowerCase() ) >= 0 ) { Popcorn.error( "'" + name + "' is a protected function name" ); return; } // Provides some sugar, but ultimately extends // the definition into Popcorn.p var reserved = [ "start", "end" ], plugin = {}, setup, isfn = typeof definition === "function", methods = [ "_setup", "_teardown", "start", "end", "frame" ]; // combines calls of two function calls into one var combineFn = function( first, second ) { first = first || Popcorn.nop; second = second || Popcorn.nop; return function() { first.apply( this, arguments ); second.apply( this, arguments ); }; }; // If `manifest` arg is undefined, check for manifest within the `definition` object // If no `definition.manifest`, an empty object is a sufficient fallback Popcorn.manifest[ name ] = manifest = manifest || definition.manifest || {}; // apply safe, and empty default functions methods.forEach(function( method ) { definition[ method ] = safeTry( definition[ method ] || Popcorn.nop, name ); }); var pluginFn = function( setup, options ) { if ( !options ) { return this; } // When the "ranges" property is set and its value is an array, short-circuit // the pluginFn definition to recall itself with an options object generated from // each range object in the ranges array. (eg. { start: 15, end: 16 } ) if ( options.ranges && Popcorn.isArray(options.ranges) ) { Popcorn.forEach( options.ranges, function( range ) { // Create a fresh object, extend with current options // and start/end range object's properties // Works with in/out as well. var opts = Popcorn.extend( {}, options, range ); // Remove the ranges property to prevent infinitely // entering this condition delete opts.ranges; // Call the plugin with the newly created opts object this[ name ]( opts ); }, this); // Return the Popcorn instance to avoid creating an empty track event return this; } // Storing the plugin natives var natives = options._natives = {}, compose = "", originalOpts, manifestOpts; Popcorn.extend( natives, setup ); options._natives.type = name; options._running = false; natives.start = natives.start || natives[ "in" ]; natives.end = natives.end || natives[ "out" ]; if ( options.once ) { natives.end = combineFn( natives.end, function() { this.removeTrackEvent( options._id ); }); } // extend teardown to always call end if running natives._teardown = combineFn(function() { var args = slice.call( arguments ), runningPlugins = this.data.running[ natives.type ]; // end function signature is not the same as teardown, // put null on the front of arguments for the event parameter args.unshift( null ); // only call end if event is running args[ 1 ]._running && runningPlugins.splice( runningPlugins.indexOf( options ), 1 ) && natives.end.apply( this, args ); }, natives._teardown ); // default to an empty string if no effect exists // split string into an array of effects options.compose = options.compose && options.compose.split( " " ) || []; options.effect = options.effect && options.effect.split( " " ) || []; // join the two arrays together options.compose = options.compose.concat( options.effect ); options.compose.forEach(function( composeOption ) { // if the requested compose is garbage, throw it away compose = Popcorn.compositions[ composeOption ] || {}; // extends previous functions with compose function methods.forEach(function( method ) { natives[ method ] = combineFn( natives[ method ], compose[ method ] ); }); }); // Ensure a manifest object, an empty object is a sufficient fallback options._natives.manifest = manifest; // Checks for expected properties if ( !( "start" in options ) ) { options.start = options[ "in" ] || 0; } if ( !options.end && options.end !== 0 ) { options.end = options[ "out" ] || Number.MAX_VALUE; } // Use hasOwn to detect non-inherited toString, since all // objects will receive a toString - its otherwise undetectable if ( !hasOwn.call( options, "toString" ) ) { options.toString = function() { var props = [ "start: " + options.start, "end: " + options.end, "id: " + (options.id || options._id) ]; // Matches null and undefined, allows: false, 0, "" and truthy if ( options.target != null ) { props.push( "target: " + options.target ); } return name + " ( " + props.join(", ") + " )"; }; } // Resolves 239, 241, 242 if ( !options.target ) { // Sometimes the manifest may be missing entirely // or it has an options object that doesn't have a `target` property manifestOpts = "options" in manifest && manifest.options; options.target = manifestOpts && "target" in manifestOpts && manifestOpts.target; } if ( options._natives ) { // ensure an initial id is there before setup is called options._id = Popcorn.guid( options._natives.type ); } // Trigger _setup method if exists options._natives._setup && options._natives._setup.call( this, options ); // Create new track event for this instance Popcorn.addTrackEvent( this, options ); // Future support for plugin event definitions // for all of the native events Popcorn.forEach( setup, function( callback, type ) { if ( type !== "type" ) { if ( reserved.indexOf( type ) === -1 ) { this.on( type, callback ); } } }, this ); return this; }; // Extend Popcorn.p with new named definition // Assign new named definition Popcorn.p[ name ] = plugin[ name ] = function( id, options ) { var length = arguments.length, trackEvent, defaults, mergedSetupOpts; // Shift arguments based on use case // // Back compat for: // p.plugin( options ); if ( id && !options ) { options = id; id = null; } else { // Get the trackEvent that matches the given id. trackEvent = this.getTrackEvent( id ); // If the track event does not exist, ensure that the options // object has a proper id if ( !trackEvent ) { options.id = id; // If the track event does exist, merge the updated properties } else { options = Popcorn.extend( {}, trackEvent, options ); Popcorn.addTrackEvent( this, options ); return this; } } this.data.running[ name ] = this.data.running[ name ] || []; // Merge with defaults if they exist, make sure per call is prioritized defaults = ( this.options.defaults && this.options.defaults[ name ] ) || {}; mergedSetupOpts = Popcorn.extend( {}, defaults, options ); return pluginFn.call( this, isfn ? definition.call( this, mergedSetupOpts ) : definition, mergedSetupOpts ); }; // if the manifest parameter exists we should extend it onto the definition object // so that it shows up when calling Popcorn.registry and Popcorn.registryByName if ( manifest ) { Popcorn.extend( definition, { manifest: manifest }); } // Push into the registry var entry = { fn: plugin[ name ], definition: definition, base: definition, parents: [], name: name }; Popcorn.registry.push( Popcorn.extend( plugin, entry, { type: name }) ); Popcorn.registryByName[ name ] = entry; return plugin; }; // Storage for plugin function errors Popcorn.plugin.errors = []; // Returns wrapped plugin function function safeTry( fn, pluginName ) { return function() { // When Popcorn.plugin.debug is true, do not suppress errors if ( Popcorn.plugin.debug ) { return fn.apply( this, arguments ); } try { return fn.apply( this, arguments ); } catch ( ex ) { // Push plugin function errors into logging queue Popcorn.plugin.errors.push({ plugin: pluginName, thrown: ex, source: fn.toString() }); // Trigger an error that the instance can listen for // and react to this.emit( "pluginerror", Popcorn.plugin.errors ); } }; } // Debug-mode flag for plugin development // True for Popcorn development versions, false for stable/tagged versions Popcorn.plugin.debug = ( Popcorn.version === "@" + "VERSION" ); // removePlugin( type ) removes all tracks of that from all instances of popcorn // removePlugin( obj, type ) removes all tracks of type from obj, where obj is a single instance of popcorn Popcorn.removePlugin = function( obj, name ) { // Check if we are removing plugin from an instance or from all of Popcorn if ( !name ) { // Fix the order name = obj; obj = Popcorn.p; if ( Popcorn.protect.natives.indexOf( name.toLowerCase() ) >= 0 ) { Popcorn.error( "'" + name + "' is a protected function name" ); return; } var registryLen = Popcorn.registry.length, registryIdx; // remove plugin reference from registry for ( registryIdx = 0; registryIdx < registryLen; registryIdx++ ) { if ( Popcorn.registry[ registryIdx ].name === name ) { Popcorn.registry.splice( registryIdx, 1 ); delete Popcorn.registryByName[ name ]; delete Popcorn.manifest[ name ]; // delete the plugin delete obj[ name ]; // plugin found and removed, stop checking, we are done return; } } } var byStart = obj.data.trackEvents.byStart, byEnd = obj.data.trackEvents.byEnd, animating = obj.data.trackEvents.animating, idx, sl; // remove all trackEvents for ( idx = 0, sl = byStart.length; idx < sl; idx++ ) { if ( byStart[ idx ] && byStart[ idx ]._natives && byStart[ idx ]._natives.type === name ) { byStart[ idx ]._natives._teardown && byStart[ idx ]._natives._teardown.call( obj, byStart[ idx ] ); byStart.splice( idx, 1 ); // update for loop if something removed, but keep checking idx--; sl--; if ( obj.data.trackEvents.startIndex <= idx ) { obj.data.trackEvents.startIndex--; obj.data.trackEvents.endIndex--; } } // clean any remaining references in the end index // we do this seperate from the above check because they might not be in the same order if ( byEnd[ idx ] && byEnd[ idx ]._natives && byEnd[ idx ]._natives.type === name ) { byEnd.splice( idx, 1 ); } } //remove all animating events for ( idx = 0, sl = animating.length; idx < sl; idx++ ) { if ( animating[ idx ] && animating[ idx ]._natives && animating[ idx ]._natives.type === name ) { animating.splice( idx, 1 ); // update for loop if something removed, but keep checking idx--; sl--; } } }; Popcorn.compositions = {}; // Plugin inheritance Popcorn.compose = function( name, definition, manifest ) { // If `manifest` arg is undefined, check for manifest within the `definition` object // If no `definition.manifest`, an empty object is a sufficient fallback Popcorn.manifest[ name ] = manifest = manifest || definition.manifest || {}; // register the effect by name Popcorn.compositions[ name ] = definition; }; Popcorn.plugin.effect = Popcorn.effect = Popcorn.compose; var rnaiveExpr = /^(?:\.|#|\[)/; // Basic DOM utilities and helpers API. See #1037 Popcorn.dom = { debug: false, // Popcorn.dom.find( selector, context ) // // Returns the first element that matches the specified selector // Optionally provide a context element, defaults to `document` // // eg. // Popcorn.dom.find("video") returns the first video element // Popcorn.dom.find("#foo") returns the first element with `id="foo"` // Popcorn.dom.find("foo") returns the first element with `id="foo"` // Note: Popcorn.dom.find("foo") is the only allowed deviation // from valid querySelector selector syntax // // Popcorn.dom.find(".baz") returns the first element with `class="baz"` // Popcorn.dom.find("[preload]") returns the first element with `preload="..."` // ... // See https://developer.mozilla.org/En/DOM/Document.querySelector // // find: function( selector, context ) { var node = null; // Trim leading/trailing whitespace to avoid false negatives selector = selector.trim(); // Default context is the `document` context = context || document; if ( selector ) { // If the selector does not begin with "#", "." or "[", // it could be either a nodeName or ID w/o "#" if ( !rnaiveExpr.test( selector ) ) { // Try finding an element that matches by ID first node = document.getElementById( selector ); // If a match was found by ID, return the element if ( node !== null ) { return node; } } // Assume no elements have been found yet // Catch any invalid selector syntax errors and bury them. try { node = context.querySelector( selector ); } catch ( e ) { if ( Popcorn.dom.debug ) { throw new Error(e); } } } return node; } }; // Cache references to reused RegExps var rparams = /\?/, // XHR Setup object setup = { url: "", data: "", dataType: "", success: Popcorn.nop, type: "GET", async: true, xhr: function() { return new global.XMLHttpRequest(); } }; Popcorn.xhr = function( options ) { options.dataType = options.dataType && options.dataType.toLowerCase() || null; if ( options.dataType && ( options.dataType === "jsonp" || options.dataType === "script" ) ) { Popcorn.xhr.getJSONP( options.url, options.success, options.dataType === "script" ); return; } var settings = Popcorn.extend( {}, setup, options ); // Create new XMLHttpRequest object settings.ajax = settings.xhr(); if ( settings.ajax ) { if ( settings.type === "GET" && settings.data ) { // append query string settings.url += ( rparams.test( settings.url ) ? "&" : "?" ) + settings.data; // Garbage collect and reset settings.data settings.data = null; } settings.ajax.open( settings.type, settings.url, settings.async ); settings.ajax.send( settings.data || null ); return Popcorn.xhr.httpData( settings ); } }; Popcorn.xhr.httpData = function( settings ) { var data, json = null, parser, xml = null; settings.ajax.onreadystatechange = function() { if ( settings.ajax.readyState === 4 ) { try { json = JSON.parse( settings.ajax.responseText ); } catch( e ) { //suppress } data = { xml: settings.ajax.responseXML, text: settings.ajax.responseText, json: json }; // Normalize: data.xml is non-null in IE9 regardless of if response is valid xml if ( !data.xml || !data.xml.documentElement ) { data.xml = null; try { parser = new DOMParser(); xml = parser.parseFromString( settings.ajax.responseText, "text/xml" ); if ( !xml.getElementsByTagName( "parsererror" ).length ) { data.xml = xml; } } catch ( e ) { // data.xml remains null } } // If a dataType was specified, return that type of data if ( settings.dataType ) { data = data[ settings.dataType ]; } settings.success.call( settings.ajax, data ); } }; return data; }; Popcorn.xhr.getJSONP = function( url, success, isScript ) { var head = document.head || document.getElementsByTagName( "head" )[ 0 ] || document.documentElement, script = document.createElement( "script" ), isFired = false, params = [], rjsonp = /(=)\?(?=&|$)|\?\?/, replaceInUrl, prefix, paramStr, callback, callparam; if ( !isScript ) { // is there a calback already in the url callparam = url.match( /(callback=[^&]*)/ ); if ( callparam !== null && callparam.length ) { prefix = callparam[ 1 ].split( "=" )[ 1 ]; // Since we need to support developer specified callbacks // and placeholders in harmony, make sure matches to "callback=" // aren't just placeholders. // We coded ourselves into a corner here. // JSONP callbacks should never have been // allowed to have developer specified callbacks if ( prefix === "?" ) { prefix = "jsonp"; } // get the callback name callback = Popcorn.guid( prefix ); // replace existing callback name with unique callback name url = url.replace( /(callback=[^&]*)/, "callback=" + callback ); } else { callback = Popcorn.guid( "jsonp" ); if ( rjsonp.test( url ) ) { url = url.replace( rjsonp, "$1" + callback ); } // split on first question mark, // this is to capture the query string params = url.split( /\?(.+)?/ ); // rebuild url with callback url = params[ 0 ] + "?"; if ( params[ 1 ] ) { url += params[ 1 ] + "&"; } url += "callback=" + callback; } // Define the JSONP success callback globally window[ callback ] = function( data ) { // Fire success callbacks success && success( data ); isFired = true; }; } script.addEventListener( "load", function() { // Handling remote script loading callbacks if ( isScript ) { // getScript success && success(); } // Executing for JSONP requests if ( isFired ) { // Garbage collect the callback delete window[ callback ]; } // Garbage collect the script resource head.removeChild( script ); }, false ); script.src = url; head.insertBefore( script, head.firstChild ); return; }; Popcorn.getJSONP = Popcorn.xhr.getJSONP; Popcorn.getScript = Popcorn.xhr.getScript = function( url, success ) { return Popcorn.xhr.getJSONP( url, success, true ); }; Popcorn.util = { // Simple function to parse a timestamp into seconds // Acceptable formats are: // HH:MM:SS.MMM // HH:MM:SS;FF // Hours and minutes are optional. They default to 0 toSeconds: function( timeStr, framerate ) { // Hours and minutes are optional // Seconds must be specified // Seconds can be followed by milliseconds OR by the frame information var validTimeFormat = /^([0-9]+:){0,2}[0-9]+([.;][0-9]+)?$/, errorMessage = "Invalid time format", digitPairs, lastIndex, lastPair, firstPair, frameInfo, frameTime; if ( typeof timeStr === "number" ) { return timeStr; } if ( typeof timeStr === "string" && !validTimeFormat.test( timeStr ) ) { Popcorn.error( errorMessage ); } digitPairs = timeStr.split( ":" ); lastIndex = digitPairs.length - 1; lastPair = digitPairs[ lastIndex ]; // Fix last element: if ( lastPair.indexOf( ";" ) > -1 ) { frameInfo = lastPair.split( ";" ); frameTime = 0; if ( framerate && ( typeof framerate === "number" ) ) { frameTime = parseFloat( frameInfo[ 1 ], 10 ) / framerate; } digitPairs[ lastIndex ] = parseInt( frameInfo[ 0 ], 10 ) + frameTime; } firstPair = digitPairs[ 0 ]; return { 1: parseFloat( firstPair, 10 ), 2: ( parseInt( firstPair, 10 ) * 60 ) + parseFloat( digitPairs[ 1 ], 10 ), 3: ( parseInt( firstPair, 10 ) * 3600 ) + ( parseInt( digitPairs[ 1 ], 10 ) * 60 ) + parseFloat( digitPairs[ 2 ], 10 ) }[ digitPairs.length || 1 ]; } }; // alias for exec function Popcorn.p.cue = Popcorn.p.exec; // Protected API methods Popcorn.protect = { natives: getKeys( Popcorn.p ).map(function( val ) { return val.toLowerCase(); }) }; // Setup logging for deprecated methods Popcorn.forEach({ // Deprecated: Recommended "listen": "on", "unlisten": "off", "trigger": "emit", "exec": "cue" }, function( recommend, api ) { var original = Popcorn.p[ api ]; // Override the deprecated api method with a method of the same name // that logs a warning and defers to the new recommended method Popcorn.p[ api ] = function() { if ( typeof console !== "undefined" && console.warn ) { console.warn( "Deprecated method '" + api + "', " + (recommend == null ? "do not use." : "use '" + recommend + "' instead." ) ); // Restore api after first warning Popcorn.p[ api ] = original; } return Popcorn.p[ recommend ].apply( this, [].slice.call( arguments ) ); }; }); // Exposes Popcorn to global context global.Popcorn = Popcorn; })(window, window.document);
docs/src/app/pages/Home/Page.js
GetAmbassador/react-ions
import React from 'react' import classNames from 'classnames/bind' import baseStyles from 'private/css/content' import localStyles from './styles' import ButtonAnchor from 'react-ions/lib/components/Button/ButtonAnchor' import Icon from 'react-ions/lib/components/Icon' const HomePage = () => { const cx = classNames.bind(baseStyles) var heroClass = cx(baseStyles.block, localStyles.hero) var secondaryClass = cx(baseStyles.block, localStyles.secondary) return ( <div> <div className={heroClass}> <div className={localStyles.skew}> <h1>React &#123;ions&#125;</h1> <h3>A suite of React components that implement Ambassador's Design and UX patterns.</h3> <ButtonAnchor path='/components' internal={true} size='lg' optClass='inverted'>Get Started</ButtonAnchor> <ButtonAnchor path='https://github.com/GetAmbassador/react-ions' external={true} target='_blank' size='lg' optClass='inverted'>Github</ButtonAnchor> </div> </div> </div> ) } export default HomePage
ajax/libs/react-ios-switch/0.1.5-rc5/bundle.js
Amomo/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else { var a = factory(); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _Switch = __webpack_require__(1); Object.defineProperty(exports, 'default', { enumerable: true, get: function get() { return _interopRequireDefault(_Switch).default; } }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _dynamics = __webpack_require__(2); var _dynamics2 = _interopRequireDefault(_dynamics); var _d3Interpolate = __webpack_require__(3); var _classnames = __webpack_require__(5); var _classnames2 = _interopRequireDefault(_classnames); var _invariant = __webpack_require__(6); var _invariant2 = _interopRequireDefault(_invariant); var _react = __webpack_require__(8); var _react2 = _interopRequireDefault(_react); var _Switch = __webpack_require__(164); var _Switch2 = _interopRequireDefault(_Switch); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Switch = function (_React$Component) { _inherits(Switch, _React$Component); function Switch(props) { _classCallCheck(this, Switch); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Switch).call(this, props)); var offset = _this.getCheckedStateOffset(props); // During a drag, we track the starting mouse position and the current mouse position. // This allows us to avoid accumulating deltas, and thus avoid accumulating errors. _this.state = { currentClientX: 0, dragging: false, offset: offset, startClientX: 0 }; // The state offset should always eventually match the animated properties offset. // The component should interact with the state offset, while dynamics should interact with // the animated properties offset. _this.animatedProperties = { offset: offset }; _this.handleAnimationChange = _this.handleAnimationChange.bind(_this); _this.handleClick = _this.handleClick.bind(_this); _this.handleHandleClick = _this.handleHandleClick.bind(_this); _this.handleInputChange = _this.handleInputChange.bind(_this); _this.handleMouseDown = _this.handleMouseDown.bind(_this); _this.handleMouseMove = _this.handleMouseMove.bind(_this); _this.handleMouseUp = _this.handleMouseUp.bind(_this); return _this; } _createClass(Switch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { // Assume the props change occurred because the checked state changed. Animate back to the // rest state. this.startAnimation(nextProps); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { var dragging = this.state.dragging; this.cancelAnimation(); if (dragging) { this.removeListeners(); } } // We should be able to compute the offset from the checked state. }, { key: 'getCheckedStateOffset', value: function getCheckedStateOffset(props) { var checked = props.checked; var maxOffset = props.maxOffset; return checked ? maxOffset : 0; } }, { key: 'addListeners', value: function addListeners() { document.addEventListener('mousemove', this.handleMouseMove); document.addEventListener('mouseup', this.handleMouseUp); } }, { key: 'cancelAnimation', value: function cancelAnimation() { _dynamics2.default.stop(this.animatedProperties); } }, { key: 'handleAnimationChange', value: function handleAnimationChange() { this.setState({ offset: this.animatedProperties.offset }); } }, { key: 'handleClick', value: function handleClick(e) { var _props = this.props; var checked = _props.checked; var onChange = _props.onChange; // Prevent the outer label from receiving the event. e.preventDefault(); onChange(!checked); } // If a click event occurs on the handle, drop the event. The mouseup handler will decide // whether to consider the mouseup event a "click to toggle" interaction or a "drag end" // interaction. }, { key: 'handleHandleClick', value: function handleHandleClick(e) { // Prevent the outer label from receiving the event. e.preventDefault(); // Prevent the switch click handler from receiving the event. e.stopPropagation(); } // If there is an outer label, and it is clicked, the input receives a click event and a change // event. Because we use the click event to set the checked state (the click event propagates to // the switch), we can ignore the change event. }, { key: 'handleInputChange', value: function handleInputChange() {} }, { key: 'handleMouseDown', value: function handleMouseDown(e) { var dragging = this.state.dragging; (0, _invariant2.default)(!dragging, 'Mouse down handler called inside of a drag'); // Left click only if (e.button !== 0) { return; } this.cancelAnimation(); this.setState({ currentClientX: e.clientX, dragging: true, startClientX: e.clientX }); // While the drag is ongoing, we set document-level event handlers to capture mousemove and // mouseup. This way, the drag doesn't end if the user mouses off the handle. These event // handlers are expensive and global, so we need to make sure we remove them when the drag ends. this.addListeners(); } }, { key: 'handleMouseMove', value: function handleMouseMove(e) { var dragging = this.state.dragging; (0, _invariant2.default)(dragging, 'Mouse move handler called outside of a drag'); this.setState({ currentClientX: e.clientX }); } }, { key: 'handleMouseUp', value: function handleMouseUp() { var _props2 = this.props; var checked = _props2.checked; var maxOffset = _props2.maxOffset; var onChange = _props2.onChange; var _state = this.state; var currentClientX = _state.currentClientX; var dragging = _state.dragging; var offset = _state.offset; var startClientX = _state.startClientX; (0, _invariant2.default)(dragging, 'Mouse up handler called outside of a drag'); this.removeListeners(); // If the mouse hasn't changed position by the end of a drag, treat it as a click on the handle. var deltaX = currentClientX - startClientX; if (!deltaX) { this.setState({ dragging: false }); onChange(!checked); return; } // The checked state is a function of the mouse offset. var newOffset = offset + deltaX; var newChecked = newOffset > maxOffset / 2; this.setState({ dragging: false, offset: newOffset }); onChange(newChecked); } }, { key: 'removeListeners', value: function removeListeners() { document.removeEventListener('mousemove', this.handleMouseMove); document.removeEventListener('mouseup', this.handleMouseUp); } }, { key: 'startAnimation', value: function startAnimation(props) { var offset = this.state.offset; this.animatedProperties.offset = offset; // Note that spring animation always results in a bounce at the end. Choose parameters to // minimize this bounce. _dynamics2.default.animate(this.animatedProperties, { offset: this.getCheckedStateOffset(props) }, { change: this.handleAnimationChange, frequency: 200, friction: 400, type: _dynamics2.default.spring }); } }, { key: 'render', value: function render() { var _props3 = this.props; var checked = _props3.checked; var disabled = _props3.disabled; var handleColor = _props3.handleColor; var maxOffset = _props3.maxOffset; var offColor = _props3.offColor; var onColor = _props3.onColor; var pendingOffColor = _props3.pendingOffColor; var _state2 = this.state; var currentClientX = _state2.currentClientX; var dragging = _state2.dragging; var offset = _state2.offset; var startClientX = _state2.startClientX; // The handle position is a function of the mouse offset. var deltaX = dragging ? currentClientX - startClientX : 0; var clampedOffset = Math.min(maxOffset, Math.max(0, offset + deltaX)); var handleTransform = 'translateX(' + clampedOffset + 'px)'; // The interpolation parameter is a function of the mouse offset. var t = clampedOffset / maxOffset; // The switch color is a function of the interpolation parameter. var color = (0, _d3Interpolate.interpolate)(pendingOffColor, onColor)(t); // The off state size is a function of the interpolation parameter. var offStateTransform = 'scale(' + (1 - t) + ')'; return _react2.default.createElement( 'div', { className: (0, _classnames2.default)(_Switch2.default.switch, disabled && _Switch2.default['switch--disabled']), onClick: this.handleClick, style: { backgroundColor: color } }, _react2.default.createElement('div', { className: _Switch2.default.offState, style: { backgroundColor: offColor, msTransform: offStateTransform, transform: offStateTransform, WebkitTransform: offStateTransform } }), _react2.default.createElement('div', { className: _Switch2.default.handle, onClick: this.handleHandleClick, onMouseDown: !disabled && this.handleMouseDown, style: { backgroundColor: handleColor, msTransform: handleTransform, transform: handleTransform, WebkitTransform: handleTransform } }), _react2.default.createElement('input', { className: _Switch2.default.input, checked: checked, disabled: disabled, onChange: this.handleInputChange, type: 'checkbox' }) ); } }]); return Switch; }(_react2.default.Component); Switch.defaultProps = { disabled: false, handleColor: 'white', maxOffset: 20, offColor: 'white', onColor: '#4cd964', pendingOffColor: '#e5e5e5' }; exports.default = Switch; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;// Generated by CoffeeScript 1.7.1 (function() { var Color, DecomposedMatrix, DecomposedMatrix2D, InterpolableArray, InterpolableColor, InterpolableObject, InterpolableWithUnit, Matrix, Matrix2D, Set, Vector, addTimeout, animationTick, animations, animationsTimeouts, applyDefaults, applyFrame, applyProperties, baseSVG, cacheFn, cancelTimeout, clone, createInterpolable, defaultValueForKey, degProperties, dynamics, getCurrentProperties, interpolate, isDocumentVisible, isSVGElement, lastTime, leftDelayForTimeout, makeArrayFn, observeVisibilityChange, parseProperties, prefixFor, propertyWithPrefix, pxProperties, rAF, roundf, runLoopPaused, runLoopRunning, runLoopTick, setRealTimeout, slow, slowRatio, startAnimation, startRunLoop, svgProperties, timeBeforeVisibilityChange, timeoutLastId, timeouts, toDashed, transformProperties, transformValueForProperty, unitForProperty, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; isDocumentVisible = function() { return document.visibilityState === "visible" || (dynamics.tests != null); }; observeVisibilityChange = (function() { var fns; fns = []; if (typeof document !== "undefined" && document !== null) { document.addEventListener("visibilitychange", function() { var fn, _i, _len, _results; _results = []; for (_i = 0, _len = fns.length; _i < _len; _i++) { fn = fns[_i]; _results.push(fn(isDocumentVisible())); } return _results; }); } return function(fn) { return fns.push(fn); }; })(); clone = function(o) { var k, newO, v; newO = {}; for (k in o) { v = o[k]; newO[k] = v; } return newO; }; cacheFn = function(func) { var data; data = {}; return function() { var k, key, result, _i, _len; key = ""; for (_i = 0, _len = arguments.length; _i < _len; _i++) { k = arguments[_i]; key += k.toString() + ","; } result = data[key]; if (!result) { data[key] = result = func.apply(this, arguments); } return result; }; }; makeArrayFn = function(fn) { return function(el) { var args, i, res; if (el instanceof Array || el instanceof NodeList || el instanceof HTMLCollection) { res = (function() { var _i, _ref, _results; _results = []; for (i = _i = 0, _ref = el.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { args = Array.prototype.slice.call(arguments, 1); args.splice(0, 0, el[i]); _results.push(fn.apply(this, args)); } return _results; }).apply(this, arguments); return res; } return fn.apply(this, arguments); }; }; applyDefaults = function(options, defaults) { var k, v, _results; _results = []; for (k in defaults) { v = defaults[k]; _results.push(options[k] != null ? options[k] : options[k] = v); } return _results; }; applyFrame = function(el, properties) { var k, v, _results; if ((el.style != null)) { return applyProperties(el, properties); } else { _results = []; for (k in properties) { v = properties[k]; _results.push(el[k] = v.format()); } return _results; } }; applyProperties = function(el, properties) { var isSVG, k, matrix, transforms, v; properties = parseProperties(properties); transforms = []; isSVG = isSVGElement(el); for (k in properties) { v = properties[k]; if (transformProperties.contains(k)) { transforms.push([k, v]); } else { if (v.format != null) { v = v.format(); } else { v = "" + v + (unitForProperty(k, v)); } if (isSVG && svgProperties.contains(k)) { el.setAttribute(k, v); } else { el.style[propertyWithPrefix(k)] = v; } } } if (transforms.length > 0) { if (isSVG) { matrix = new Matrix2D(); matrix.applyProperties(transforms); return el.setAttribute("transform", matrix.decompose().format()); } else { v = (transforms.map(function(transform) { return transformValueForProperty(transform[0], transform[1]); })).join(" "); return el.style[propertyWithPrefix("transform")] = v; } } }; isSVGElement = function(el) { var _ref, _ref1; if ((typeof SVGElement !== "undefined" && SVGElement !== null) && (typeof SVGSVGElement !== "undefined" && SVGSVGElement !== null)) { return el instanceof SVGElement && !(el instanceof SVGSVGElement); } else { return (_ref = (_ref1 = dynamics.tests) != null ? typeof _ref1.isSVG === "function" ? _ref1.isSVG(el) : void 0 : void 0) != null ? _ref : false; } }; roundf = function(v, decimal) { var d; d = Math.pow(10, decimal); return Math.round(v * d) / d; }; Set = (function() { function Set(array) { var v, _i, _len; this.obj = {}; for (_i = 0, _len = array.length; _i < _len; _i++) { v = array[_i]; this.obj[v] = 1; } } Set.prototype.contains = function(v) { return this.obj[v] === 1; }; return Set; })(); toDashed = function(str) { return str.replace(/([A-Z])/g, function($1) { return "-" + $1.toLowerCase(); }); }; pxProperties = new Set('marginTop,marginLeft,marginBottom,marginRight,paddingTop,paddingLeft,paddingBottom,paddingRight,top,left,bottom,right,translateX,translateY,translateZ,perspectiveX,perspectiveY,perspectiveZ,width,height,maxWidth,maxHeight,minWidth,minHeight,borderRadius'.split(',')); degProperties = new Set('rotate,rotateX,rotateY,rotateZ,skew,skewX,skewY,skewZ'.split(',')); transformProperties = new Set('translate,translateX,translateY,translateZ,scale,scaleX,scaleY,scaleZ,rotate,rotateX,rotateY,rotateZ,rotateC,rotateCX,rotateCY,skew,skewX,skewY,skewZ,perspective'.split(',')); svgProperties = new Set('accent-height,ascent,azimuth,baseFrequency,baseline-shift,bias,cx,cy,d,diffuseConstant,divisor,dx,dy,elevation,filterRes,fx,fy,gradientTransform,height,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,letter-spacing,limitingConeAngle,markerHeight,markerWidth,numOctaves,order,overline-position,overline-thickness,pathLength,points,pointsAtX,pointsAtY,pointsAtZ,r,radius,rx,ry,seed,specularConstant,specularExponent,stdDeviation,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,surfaceScale,target,targetX,targetY,transform,underline-position,underline-thickness,viewBox,width,x,x1,x2,y,y1,y2,z'.split(',')); unitForProperty = function(k, v) { if (typeof v !== 'number') { return ''; } if (pxProperties.contains(k)) { return 'px'; } else if (degProperties.contains(k)) { return 'deg'; } return ''; }; transformValueForProperty = function(k, v) { var match, unit; match = ("" + v).match(/^([0-9.-]*)([^0-9]*)$/); if (match != null) { v = match[1]; unit = match[2]; } else { v = parseFloat(v); } v = roundf(parseFloat(v), 10); if ((unit == null) || unit === "") { unit = unitForProperty(k, v); } return "" + k + "(" + v + unit + ")"; }; parseProperties = function(properties) { var axis, match, parsed, property, value, _i, _len, _ref; parsed = {}; for (property in properties) { value = properties[property]; if (transformProperties.contains(property)) { match = property.match(/(translate|rotateC|rotate|skew|scale|perspective)(X|Y|Z|)/); if (match && match[2].length > 0) { parsed[property] = value; } else { _ref = ['X', 'Y', 'Z']; for (_i = 0, _len = _ref.length; _i < _len; _i++) { axis = _ref[_i]; parsed[match[1] + axis] = value; } } } else { parsed[property] = value; } } return parsed; }; defaultValueForKey = function(key) { var v; v = key === 'opacity' ? 1 : 0; return "" + v + (unitForProperty(key, v)); }; getCurrentProperties = function(el, keys) { var isSVG, key, matrix, properties, style, v, _i, _j, _len, _len1, _ref; properties = {}; isSVG = isSVGElement(el); if (el.style != null) { style = window.getComputedStyle(el, null); for (_i = 0, _len = keys.length; _i < _len; _i++) { key = keys[_i]; if (transformProperties.contains(key)) { if (properties['transform'] == null) { if (isSVG) { matrix = new Matrix2D((_ref = el.transform.baseVal.consolidate()) != null ? _ref.matrix : void 0); } else { matrix = Matrix.fromTransform(style[propertyWithPrefix('transform')]); } properties['transform'] = matrix.decompose(); } } else { v = style[key]; if ((v == null) && svgProperties.contains(key)) { v = el.getAttribute(key); } if (v === "" || (v == null)) { v = defaultValueForKey(key); } properties[key] = createInterpolable(v); } } } else { for (_j = 0, _len1 = keys.length; _j < _len1; _j++) { key = keys[_j]; properties[key] = createInterpolable(el[key]); } } return properties; }; createInterpolable = function(value) { var interpolable, klass, klasses, _i, _len; klasses = [InterpolableColor, InterpolableArray, InterpolableObject, InterpolableWithUnit]; for (_i = 0, _len = klasses.length; _i < _len; _i++) { klass = klasses[_i]; interpolable = klass.create(value); if (interpolable != null) { return interpolable; } } return null; }; InterpolableObject = (function() { function InterpolableObject(obj) { this.format = __bind(this.format, this); this.interpolate = __bind(this.interpolate, this); this.obj = obj; } InterpolableObject.prototype.interpolate = function(endInterpolable, t) { var end, k, newObj, start, v; start = this.obj; end = endInterpolable.obj; newObj = {}; for (k in start) { v = start[k]; if (v.interpolate != null) { newObj[k] = v.interpolate(end[k], t); } else { newObj[k] = v; } } return new InterpolableObject(newObj); }; InterpolableObject.prototype.format = function() { return this.obj; }; InterpolableObject.create = function(value) { var k, obj, v; if (value instanceof Object) { obj = {}; for (k in value) { v = value[k]; obj[k] = createInterpolable(v); } return new InterpolableObject(obj); } return null; }; return InterpolableObject; })(); InterpolableWithUnit = (function() { function InterpolableWithUnit(value, prefix, suffix) { this.prefix = prefix; this.suffix = suffix; this.format = __bind(this.format, this); this.interpolate = __bind(this.interpolate, this); this.value = parseFloat(value); } InterpolableWithUnit.prototype.interpolate = function(endInterpolable, t) { var end, start; start = this.value; end = endInterpolable.value; return new InterpolableWithUnit((end - start) * t + start, endInterpolable.prefix || this.prefix, endInterpolable.suffix || this.suffix); }; InterpolableWithUnit.prototype.format = function() { if ((this.prefix == null) && (this.suffix == null)) { return roundf(this.value, 5); } return this.prefix + roundf(this.value, 5) + this.suffix; }; InterpolableWithUnit.create = function(value) { var match; if (typeof value !== "string") { return new InterpolableWithUnit(value); } match = ("" + value).match("([^0-9.+-]*)([0-9.+-]+)([^0-9.+-]*)"); if (match != null) { return new InterpolableWithUnit(match[2], match[1], match[3]); } return null; }; return InterpolableWithUnit; })(); InterpolableArray = (function() { function InterpolableArray(values, sep) { this.values = values; this.sep = sep; this.format = __bind(this.format, this); this.interpolate = __bind(this.interpolate, this); } InterpolableArray.prototype.interpolate = function(endInterpolable, t) { var end, i, newValues, start, _i, _ref; start = this.values; end = endInterpolable.values; newValues = []; for (i = _i = 0, _ref = Math.min(start.length, end.length); 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { if (start[i].interpolate != null) { newValues.push(start[i].interpolate(end[i], t)); } else { newValues.push(start[i]); } } return new InterpolableArray(newValues, this.sep); }; InterpolableArray.prototype.format = function() { var values; values = this.values.map(function(val) { if (val.format != null) { return val.format(); } else { return val; } }); if (this.sep != null) { return values.join(this.sep); } else { return values; } }; InterpolableArray.createFromArray = function(arr, sep) { var values; values = arr.map(function(val) { return createInterpolable(val) || val; }); values = values.filter(function(val) { return val != null; }); return new InterpolableArray(values, sep); }; InterpolableArray.create = function(value) { var arr, sep, seps, _i, _len; if (value instanceof Array) { return InterpolableArray.createFromArray(value, null); } if (typeof value !== "string") { return; } seps = [' ', ',', '|', ';', '/', ':']; for (_i = 0, _len = seps.length; _i < _len; _i++) { sep = seps[_i]; arr = value.split(sep); if (arr.length > 1) { return InterpolableArray.createFromArray(arr, sep); } } return null; }; return InterpolableArray; })(); Color = (function() { function Color(rgb, format) { this.rgb = rgb != null ? rgb : {}; this.format = format; this.toRgba = __bind(this.toRgba, this); this.toRgb = __bind(this.toRgb, this); this.toHex = __bind(this.toHex, this); } Color.fromHex = function(hex) { var hex3, result; hex3 = hex.match(/^#([a-f\d]{1})([a-f\d]{1})([a-f\d]{1})$/i); if (hex3 != null) { hex = "#" + hex3[1] + hex3[1] + hex3[2] + hex3[2] + hex3[3] + hex3[3]; } result = hex.match(/^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i); if (result != null) { return new Color({ r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16), a: 1 }, "hex"); } return null; }; Color.fromRgb = function(rgb) { var match, _ref; match = rgb.match(/^rgba?\(([0-9.]*), ?([0-9.]*), ?([0-9.]*)(?:, ?([0-9.]*))?\)$/); if (match != null) { return new Color({ r: parseFloat(match[1]), g: parseFloat(match[2]), b: parseFloat(match[3]), a: parseFloat((_ref = match[4]) != null ? _ref : 1) }, match[4] != null ? "rgba" : "rgb"); } return null; }; Color.componentToHex = function(c) { var hex; hex = c.toString(16); if (hex.length === 1) { return "0" + hex; } else { return hex; } }; Color.prototype.toHex = function() { return "#" + Color.componentToHex(this.rgb.r) + Color.componentToHex(this.rgb.g) + Color.componentToHex(this.rgb.b); }; Color.prototype.toRgb = function() { return "rgb(" + this.rgb.r + ", " + this.rgb.g + ", " + this.rgb.b + ")"; }; Color.prototype.toRgba = function() { return "rgba(" + this.rgb.r + ", " + this.rgb.g + ", " + this.rgb.b + ", " + this.rgb.a + ")"; }; return Color; })(); InterpolableColor = (function() { function InterpolableColor(color) { this.color = color; this.format = __bind(this.format, this); this.interpolate = __bind(this.interpolate, this); } InterpolableColor.prototype.interpolate = function(endInterpolable, t) { var end, k, rgb, start, v, _i, _len, _ref; start = this.color; end = endInterpolable.color; rgb = {}; _ref = ['r', 'g', 'b']; for (_i = 0, _len = _ref.length; _i < _len; _i++) { k = _ref[_i]; v = Math.round((end.rgb[k] - start.rgb[k]) * t + start.rgb[k]); rgb[k] = Math.min(255, Math.max(0, v)); } k = "a"; v = roundf((end.rgb[k] - start.rgb[k]) * t + start.rgb[k], 5); rgb[k] = Math.min(1, Math.max(0, v)); return new InterpolableColor(new Color(rgb, end.format)); }; InterpolableColor.prototype.format = function() { if (this.color.format === "hex") { return this.color.toHex(); } else if (this.color.format === "rgb") { return this.color.toRgb(); } else if (this.color.format === "rgba") { return this.color.toRgba(); } }; InterpolableColor.create = function(value) { var color; if (typeof value !== "string") { return; } color = Color.fromHex(value) || Color.fromRgb(value); if (color != null) { return new InterpolableColor(color); } return null; }; return InterpolableColor; })(); DecomposedMatrix2D = (function() { function DecomposedMatrix2D(props) { this.props = props; this.applyRotateCenter = __bind(this.applyRotateCenter, this); this.format = __bind(this.format, this); this.interpolate = __bind(this.interpolate, this); } DecomposedMatrix2D.prototype.interpolate = function(endMatrix, t) { var i, k, newProps, _i, _j, _k, _l, _len, _len1, _ref, _ref1, _ref2; newProps = {}; _ref = ['translate', 'scale', 'rotate']; for (_i = 0, _len = _ref.length; _i < _len; _i++) { k = _ref[_i]; newProps[k] = []; for (i = _j = 0, _ref1 = this.props[k].length; 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) { newProps[k][i] = (endMatrix.props[k][i] - this.props[k][i]) * t + this.props[k][i]; } } for (i = _k = 1; _k <= 2; i = ++_k) { newProps['rotate'][i] = endMatrix.props['rotate'][i]; } _ref2 = ['skew']; for (_l = 0, _len1 = _ref2.length; _l < _len1; _l++) { k = _ref2[_l]; newProps[k] = (endMatrix.props[k] - this.props[k]) * t + this.props[k]; } return new DecomposedMatrix2D(newProps); }; DecomposedMatrix2D.prototype.format = function() { return "translate(" + (this.props.translate.join(',')) + ") rotate(" + (this.props.rotate.join(',')) + ") skewX(" + this.props.skew + ") scale(" + (this.props.scale.join(',')) + ")"; }; DecomposedMatrix2D.prototype.applyRotateCenter = function(rotateC) { var i, m, m2d, negativeTranslate, _i, _results; m = baseSVG.createSVGMatrix(); m = m.translate(rotateC[0], rotateC[1]); m = m.rotate(this.props.rotate[0]); m = m.translate(-rotateC[0], -rotateC[1]); m2d = new Matrix2D(m); negativeTranslate = m2d.decompose().props.translate; _results = []; for (i = _i = 0; _i <= 1; i = ++_i) { _results.push(this.props.translate[i] -= negativeTranslate[i]); } return _results; }; return DecomposedMatrix2D; })(); baseSVG = typeof document !== "undefined" && document !== null ? document.createElementNS("http://www.w3.org/2000/svg", "svg") : void 0; Matrix2D = (function() { function Matrix2D(m) { this.m = m; this.applyProperties = __bind(this.applyProperties, this); this.decompose = __bind(this.decompose, this); if (!this.m) { this.m = baseSVG.createSVGMatrix(); } } Matrix2D.prototype.decompose = function() { var kx, ky, kz, r0, r1; r0 = new Vector([this.m.a, this.m.b]); r1 = new Vector([this.m.c, this.m.d]); kx = r0.length(); kz = r0.dot(r1); r0 = r0.normalize(); ky = r1.combine(r0, 1, -kz).length(); return new DecomposedMatrix2D({ translate: [this.m.e, this.m.f], rotate: [Math.atan2(this.m.b, this.m.a) * 180 / Math.PI, this.rotateCX, this.rotateCY], scale: [kx, ky], skew: kz / ky * 180 / Math.PI }); }; Matrix2D.prototype.applyProperties = function(properties) { var hash, k, props, v, _i, _len, _ref, _ref1; hash = {}; for (_i = 0, _len = properties.length; _i < _len; _i++) { props = properties[_i]; hash[props[0]] = props[1]; } for (k in hash) { v = hash[k]; if (k === "translateX") { this.m = this.m.translate(v, 0); } else if (k === "translateY") { this.m = this.m.translate(0, v); } else if (k === "scaleX") { this.m = this.m.scale(v, 1); } else if (k === "scaleY") { this.m = this.m.scale(1, v); } else if (k === "rotateZ") { this.m = this.m.rotate(v); } else if (k === "skewX") { this.m = this.m.skewX(v); } else if (k === "skewY") { this.m = this.m.skewY(v); } } this.rotateCX = (_ref = hash.rotateCX) != null ? _ref : 0; return this.rotateCY = (_ref1 = hash.rotateCY) != null ? _ref1 : 0; }; return Matrix2D; })(); Vector = (function() { function Vector(els) { this.els = els; this.combine = __bind(this.combine, this); this.normalize = __bind(this.normalize, this); this.length = __bind(this.length, this); this.cross = __bind(this.cross, this); this.dot = __bind(this.dot, this); this.e = __bind(this.e, this); } Vector.prototype.e = function(i) { if (i < 1 || i > this.els.length) { return null; } else { return this.els[i - 1]; } }; Vector.prototype.dot = function(vector) { var V, n, product; V = vector.els || vector; product = 0; n = this.els.length; if (n !== V.length) { return null; } n += 1; while (--n) { product += this.els[n - 1] * V[n - 1]; } return product; }; Vector.prototype.cross = function(vector) { var A, B; B = vector.els || vector; if (this.els.length !== 3 || B.length !== 3) { return null; } A = this.els; return new Vector([(A[1] * B[2]) - (A[2] * B[1]), (A[2] * B[0]) - (A[0] * B[2]), (A[0] * B[1]) - (A[1] * B[0])]); }; Vector.prototype.length = function() { var a, e, _i, _len, _ref; a = 0; _ref = this.els; for (_i = 0, _len = _ref.length; _i < _len; _i++) { e = _ref[_i]; a += Math.pow(e, 2); } return Math.sqrt(a); }; Vector.prototype.normalize = function() { var e, i, length, newElements, _ref; length = this.length(); newElements = []; _ref = this.els; for (i in _ref) { e = _ref[i]; newElements[i] = e / length; } return new Vector(newElements); }; Vector.prototype.combine = function(b, ascl, bscl) { var i, result, _i, _ref; result = []; for (i = _i = 0, _ref = this.els.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { result[i] = (ascl * this.els[i]) + (bscl * b.els[i]); } return new Vector(result); }; return Vector; })(); DecomposedMatrix = (function() { function DecomposedMatrix() { this.toMatrix = __bind(this.toMatrix, this); this.format = __bind(this.format, this); this.interpolate = __bind(this.interpolate, this); } DecomposedMatrix.prototype.interpolate = function(decomposedB, t, only) { var angle, decomposed, decomposedA, i, invscale, invth, k, qa, qb, scale, th, _i, _j, _k, _l, _len, _ref, _ref1; if (only == null) { only = null; } decomposedA = this; decomposed = new DecomposedMatrix; _ref = ['translate', 'scale', 'skew', 'perspective']; for (_i = 0, _len = _ref.length; _i < _len; _i++) { k = _ref[_i]; decomposed[k] = []; for (i = _j = 0, _ref1 = decomposedA[k].length - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; i = 0 <= _ref1 ? ++_j : --_j) { if ((only == null) || only.indexOf(k) > -1 || only.indexOf("" + k + ['x', 'y', 'z'][i]) > -1) { decomposed[k][i] = (decomposedB[k][i] - decomposedA[k][i]) * t + decomposedA[k][i]; } else { decomposed[k][i] = decomposedA[k][i]; } } } if ((only == null) || only.indexOf('rotate') !== -1) { qa = decomposedA.quaternion; qb = decomposedB.quaternion; angle = qa[0] * qb[0] + qa[1] * qb[1] + qa[2] * qb[2] + qa[3] * qb[3]; if (angle < 0.0) { for (i = _k = 0; _k <= 3; i = ++_k) { qa[i] = -qa[i]; } angle = -angle; } if (angle + 1.0 > .05) { if (1.0 - angle >= .05) { th = Math.acos(angle); invth = 1.0 / Math.sin(th); scale = Math.sin(th * (1.0 - t)) * invth; invscale = Math.sin(th * t) * invth; } else { scale = 1.0 - t; invscale = t; } } else { qb[0] = -qa[1]; qb[1] = qa[0]; qb[2] = -qa[3]; qb[3] = qa[2]; scale = Math.sin(piDouble * (.5 - t)); invscale = Math.sin(piDouble * t); } decomposed.quaternion = []; for (i = _l = 0; _l <= 3; i = ++_l) { decomposed.quaternion[i] = qa[i] * scale + qb[i] * invscale; } } else { decomposed.quaternion = decomposedA.quaternion; } return decomposed; }; DecomposedMatrix.prototype.format = function() { return this.toMatrix().toString(); }; DecomposedMatrix.prototype.toMatrix = function() { var decomposedMatrix, i, j, match, matrix, quaternion, skew, temp, w, x, y, z, _i, _j, _k, _l; decomposedMatrix = this; matrix = Matrix.I(4); for (i = _i = 0; _i <= 3; i = ++_i) { matrix.els[i][3] = decomposedMatrix.perspective[i]; } quaternion = decomposedMatrix.quaternion; x = quaternion[0]; y = quaternion[1]; z = quaternion[2]; w = quaternion[3]; skew = decomposedMatrix.skew; match = [[1, 0], [2, 0], [2, 1]]; for (i = _j = 2; _j >= 0; i = --_j) { if (skew[i]) { temp = Matrix.I(4); temp.els[match[i][0]][match[i][1]] = skew[i]; matrix = matrix.multiply(temp); } } matrix = matrix.multiply(new Matrix([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w), 0], [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w), 0], [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y), 0], [0, 0, 0, 1]])); for (i = _k = 0; _k <= 2; i = ++_k) { for (j = _l = 0; _l <= 2; j = ++_l) { matrix.els[i][j] *= decomposedMatrix.scale[i]; } matrix.els[3][i] = decomposedMatrix.translate[i]; } return matrix; }; return DecomposedMatrix; })(); Matrix = (function() { function Matrix(els) { this.els = els; this.toString = __bind(this.toString, this); this.decompose = __bind(this.decompose, this); this.inverse = __bind(this.inverse, this); this.augment = __bind(this.augment, this); this.toRightTriangular = __bind(this.toRightTriangular, this); this.transpose = __bind(this.transpose, this); this.multiply = __bind(this.multiply, this); this.dup = __bind(this.dup, this); this.e = __bind(this.e, this); } Matrix.prototype.e = function(i, j) { if (i < 1 || i > this.els.length || j < 1 || j > this.els[0].length) { return null; } return this.els[i - 1][j - 1]; }; Matrix.prototype.dup = function() { return new Matrix(this.els); }; Matrix.prototype.multiply = function(matrix) { var M, c, cols, elements, i, j, ki, kj, nc, ni, nj, returnVector, sum; returnVector = matrix.modulus ? true : false; M = matrix.els || matrix; if (typeof M[0][0] === 'undefined') { M = new Matrix(M).els; } ni = this.els.length; ki = ni; kj = M[0].length; cols = this.els[0].length; elements = []; ni += 1; while (--ni) { i = ki - ni; elements[i] = []; nj = kj; nj += 1; while (--nj) { j = kj - nj; sum = 0; nc = cols; nc += 1; while (--nc) { c = cols - nc; sum += this.els[i][c] * M[c][j]; } elements[i][j] = sum; } } M = new Matrix(elements); if (returnVector) { return M.col(1); } else { return M; } }; Matrix.prototype.transpose = function() { var cols, elements, i, j, ni, nj, rows; rows = this.els.length; cols = this.els[0].length; elements = []; ni = cols; ni += 1; while (--ni) { i = cols - ni; elements[i] = []; nj = rows; nj += 1; while (--nj) { j = rows - nj; elements[i][j] = this.els[j][i]; } } return new Matrix(elements); }; Matrix.prototype.toRightTriangular = function() { var M, els, i, j, k, kp, multiplier, n, np, p, _i, _j, _ref, _ref1; M = this.dup(); n = this.els.length; k = n; kp = this.els[0].length; while (--n) { i = k - n; if (M.els[i][i] === 0) { for (j = _i = _ref = i + 1; _ref <= k ? _i < k : _i > k; j = _ref <= k ? ++_i : --_i) { if (M.els[j][i] !== 0) { els = []; np = kp; np += 1; while (--np) { p = kp - np; els.push(M.els[i][p] + M.els[j][p]); } M.els[i] = els; break; } } } if (M.els[i][i] !== 0) { for (j = _j = _ref1 = i + 1; _ref1 <= k ? _j < k : _j > k; j = _ref1 <= k ? ++_j : --_j) { multiplier = M.els[j][i] / M.els[i][i]; els = []; np = kp; np += 1; while (--np) { p = kp - np; els.push(p <= i ? 0 : M.els[j][p] - M.els[i][p] * multiplier); } M.els[j] = els; } } } return M; }; Matrix.prototype.augment = function(matrix) { var M, T, cols, i, j, ki, kj, ni, nj; M = matrix.els || matrix; if (typeof M[0][0] === 'undefined') { M = new Matrix(M).els; } T = this.dup(); cols = T.els[0].length; ni = T.els.length; ki = ni; kj = M[0].length; if (ni !== M.length) { return null; } ni += 1; while (--ni) { i = ki - ni; nj = kj; nj += 1; while (--nj) { j = kj - nj; T.els[i][cols + j] = M[i][j]; } } return T; }; Matrix.prototype.inverse = function() { var M, divisor, els, i, inverse_elements, j, ki, kp, new_element, ni, np, p, _i; ni = this.els.length; ki = ni; M = this.augment(Matrix.I(ni)).toRightTriangular(); kp = M.els[0].length; inverse_elements = []; ni += 1; while (--ni) { i = ni - 1; els = []; np = kp; inverse_elements[i] = []; divisor = M.els[i][i]; np += 1; while (--np) { p = kp - np; new_element = M.els[i][p] / divisor; els.push(new_element); if (p >= ki) { inverse_elements[i].push(new_element); } } M.els[i] = els; for (j = _i = 0; 0 <= i ? _i < i : _i > i; j = 0 <= i ? ++_i : --_i) { els = []; np = kp; np += 1; while (--np) { p = kp - np; els.push(M.els[j][p] - M.els[i][p] * M.els[j][i]); } M.els[j] = els; } } return new Matrix(inverse_elements); }; Matrix.I = function(n) { var els, i, j, k, nj; els = []; k = n; n += 1; while (--n) { i = k - n; els[i] = []; nj = k; nj += 1; while (--nj) { j = k - nj; els[i][j] = i === j ? 1 : 0; } } return new Matrix(els); }; Matrix.prototype.decompose = function() { var els, i, inversePerspectiveMatrix, j, k, matrix, pdum3, perspective, perspectiveMatrix, quaternion, result, rightHandSide, rotate, row, rowElement, s, scale, skew, t, translate, transposedInversePerspectiveMatrix, type, typeKey, v, w, x, y, z, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r; matrix = this; translate = []; scale = []; skew = []; quaternion = []; perspective = []; els = []; for (i = _i = 0; _i <= 3; i = ++_i) { els[i] = []; for (j = _j = 0; _j <= 3; j = ++_j) { els[i][j] = matrix.els[i][j]; } } if (els[3][3] === 0) { return false; } for (i = _k = 0; _k <= 3; i = ++_k) { for (j = _l = 0; _l <= 3; j = ++_l) { els[i][j] /= els[3][3]; } } perspectiveMatrix = matrix.dup(); for (i = _m = 0; _m <= 2; i = ++_m) { perspectiveMatrix.els[i][3] = 0; } perspectiveMatrix.els[3][3] = 1; if (els[0][3] !== 0 || els[1][3] !== 0 || els[2][3] !== 0) { rightHandSide = new Vector(els.slice(0, 4)[3]); inversePerspectiveMatrix = perspectiveMatrix.inverse(); transposedInversePerspectiveMatrix = inversePerspectiveMatrix.transpose(); perspective = transposedInversePerspectiveMatrix.multiply(rightHandSide).els; for (i = _n = 0; _n <= 2; i = ++_n) { els[i][3] = 0; } els[3][3] = 1; } else { perspective = [0, 0, 0, 1]; } for (i = _o = 0; _o <= 2; i = ++_o) { translate[i] = els[3][i]; els[3][i] = 0; } row = []; for (i = _p = 0; _p <= 2; i = ++_p) { row[i] = new Vector(els[i].slice(0, 3)); } scale[0] = row[0].length(); row[0] = row[0].normalize(); skew[0] = row[0].dot(row[1]); row[1] = row[1].combine(row[0], 1.0, -skew[0]); scale[1] = row[1].length(); row[1] = row[1].normalize(); skew[0] /= scale[1]; skew[1] = row[0].dot(row[2]); row[2] = row[2].combine(row[0], 1.0, -skew[1]); skew[2] = row[1].dot(row[2]); row[2] = row[2].combine(row[1], 1.0, -skew[2]); scale[2] = row[2].length(); row[2] = row[2].normalize(); skew[1] /= scale[2]; skew[2] /= scale[2]; pdum3 = row[1].cross(row[2]); if (row[0].dot(pdum3) < 0) { for (i = _q = 0; _q <= 2; i = ++_q) { scale[i] *= -1; for (j = _r = 0; _r <= 2; j = ++_r) { row[i].els[j] *= -1; } } } rowElement = function(index, elementIndex) { return row[index].els[elementIndex]; }; rotate = []; rotate[1] = Math.asin(-rowElement(0, 2)); if (Math.cos(rotate[1]) !== 0) { rotate[0] = Math.atan2(rowElement(1, 2), rowElement(2, 2)); rotate[2] = Math.atan2(rowElement(0, 1), rowElement(0, 0)); } else { rotate[0] = Math.atan2(-rowElement(2, 0), rowElement(1, 1)); rotate[1] = 0; } t = rowElement(0, 0) + rowElement(1, 1) + rowElement(2, 2) + 1.0; if (t > 1e-4) { s = 0.5 / Math.sqrt(t); w = 0.25 / s; x = (rowElement(2, 1) - rowElement(1, 2)) * s; y = (rowElement(0, 2) - rowElement(2, 0)) * s; z = (rowElement(1, 0) - rowElement(0, 1)) * s; } else if ((rowElement(0, 0) > rowElement(1, 1)) && (rowElement(0, 0) > rowElement(2, 2))) { s = Math.sqrt(1.0 + rowElement(0, 0) - rowElement(1, 1) - rowElement(2, 2)) * 2.0; x = 0.25 * s; y = (rowElement(0, 1) + rowElement(1, 0)) / s; z = (rowElement(0, 2) + rowElement(2, 0)) / s; w = (rowElement(2, 1) - rowElement(1, 2)) / s; } else if (rowElement(1, 1) > rowElement(2, 2)) { s = Math.sqrt(1.0 + rowElement(1, 1) - rowElement(0, 0) - rowElement(2, 2)) * 2.0; x = (rowElement(0, 1) + rowElement(1, 0)) / s; y = 0.25 * s; z = (rowElement(1, 2) + rowElement(2, 1)) / s; w = (rowElement(0, 2) - rowElement(2, 0)) / s; } else { s = Math.sqrt(1.0 + rowElement(2, 2) - rowElement(0, 0) - rowElement(1, 1)) * 2.0; x = (rowElement(0, 2) + rowElement(2, 0)) / s; y = (rowElement(1, 2) + rowElement(2, 1)) / s; z = 0.25 * s; w = (rowElement(1, 0) - rowElement(0, 1)) / s; } quaternion = [x, y, z, w]; result = new DecomposedMatrix; result.translate = translate; result.scale = scale; result.skew = skew; result.quaternion = quaternion; result.perspective = perspective; result.rotate = rotate; for (typeKey in result) { type = result[typeKey]; for (k in type) { v = type[k]; if (isNaN(v)) { type[k] = 0; } } } return result; }; Matrix.prototype.toString = function() { var i, j, str, _i, _j; str = 'matrix3d('; for (i = _i = 0; _i <= 3; i = ++_i) { for (j = _j = 0; _j <= 3; j = ++_j) { str += roundf(this.els[i][j], 10); if (!(i === 3 && j === 3)) { str += ','; } } } str += ')'; return str; }; Matrix.matrixForTransform = cacheFn(function(transform) { var matrixEl, result, style, _ref, _ref1, _ref2; matrixEl = document.createElement('div'); matrixEl.style.position = 'absolute'; matrixEl.style.visibility = 'hidden'; matrixEl.style[propertyWithPrefix("transform")] = transform; document.body.appendChild(matrixEl); style = window.getComputedStyle(matrixEl, null); result = (_ref = (_ref1 = style.transform) != null ? _ref1 : style[propertyWithPrefix("transform")]) != null ? _ref : (_ref2 = dynamics.tests) != null ? _ref2.matrixForTransform(transform) : void 0; document.body.removeChild(matrixEl); return result; }); Matrix.fromTransform = function(transform) { var digits, elements, i, match, matrixElements, _i; match = transform != null ? transform.match(/matrix3?d?\(([-0-9,e \.]*)\)/) : void 0; if (match) { digits = match[1].split(','); digits = digits.map(parseFloat); if (digits.length === 6) { elements = [digits[0], digits[1], 0, 0, digits[2], digits[3], 0, 0, 0, 0, 1, 0, digits[4], digits[5], 0, 1]; } else { elements = digits; } } else { elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; } matrixElements = []; for (i = _i = 0; _i <= 3; i = ++_i) { matrixElements.push(elements.slice(i * 4, i * 4 + 4)); } return new Matrix(matrixElements); }; return Matrix; })(); prefixFor = cacheFn(function(property) { var k, prefix, prop, propArray, propertyName, _i, _j, _len, _len1, _ref; if (document.body.style[property] !== void 0) { return ''; } propArray = property.split('-'); propertyName = ""; for (_i = 0, _len = propArray.length; _i < _len; _i++) { prop = propArray[_i]; propertyName += prop.substring(0, 1).toUpperCase() + prop.substring(1); } _ref = ["Webkit", "Moz", "ms"]; for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { prefix = _ref[_j]; k = prefix + propertyName; if (document.body.style[k] !== void 0) { return prefix; } } return ''; }); propertyWithPrefix = cacheFn(function(property) { var prefix; prefix = prefixFor(property); if (prefix === 'Moz') { return "" + prefix + (property.substring(0, 1).toUpperCase() + property.substring(1)); } if (prefix !== '') { return "-" + (prefix.toLowerCase()) + "-" + (toDashed(property)); } return toDashed(property); }); rAF = typeof window !== "undefined" && window !== null ? window.requestAnimationFrame : void 0; animations = []; animationsTimeouts = []; slow = false; slowRatio = 1; if (typeof window !== "undefined" && window !== null) { window.addEventListener('keyup', function(e) { if (e.keyCode === 68 && e.shiftKey && e.ctrlKey) { return dynamics.toggleSlow(); } }); } if (rAF == null) { lastTime = 0; rAF = function(callback) { var currTime, id, timeToCall; currTime = Date.now(); timeToCall = Math.max(0, 16 - (currTime - lastTime)); id = window.setTimeout(function() { return callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } runLoopRunning = false; runLoopPaused = false; startRunLoop = function() { if (!runLoopRunning) { runLoopRunning = true; return rAF(runLoopTick); } }; runLoopTick = function(t) { var animation, toRemoveAnimations, _i, _len; if (runLoopPaused) { rAF(runLoopTick); return; } toRemoveAnimations = []; for (_i = 0, _len = animations.length; _i < _len; _i++) { animation = animations[_i]; if (!animationTick(t, animation)) { toRemoveAnimations.push(animation); } } animations = animations.filter(function(animation) { return toRemoveAnimations.indexOf(animation) === -1; }); if (animations.length === 0) { return runLoopRunning = false; } else { return rAF(runLoopTick); } }; animationTick = function(t, animation) { var key, properties, property, tt, y, _base, _base1, _ref; if (animation.tStart == null) { animation.tStart = t; } tt = (t - animation.tStart) / animation.options.duration; y = animation.curve(tt); properties = {}; if (tt >= 1) { if (animation.curve.initialForce) { properties = animation.properties.start; } else { properties = animation.properties.end; } } else { _ref = animation.properties.start; for (key in _ref) { property = _ref[key]; properties[key] = interpolate(property, animation.properties.end[key], y); } } applyFrame(animation.el, properties); if (typeof (_base = animation.options).change === "function") { _base.change(animation.el); } if (tt >= 1) { if (typeof (_base1 = animation.options).complete === "function") { _base1.complete(animation.el); } } return tt < 1; }; interpolate = function(start, end, y) { if ((start != null) && (start.interpolate != null)) { return start.interpolate(end, y); } return null; }; startAnimation = function(el, properties, options, timeoutId) { var endProperties, isSVG, k, matrix, startProperties, transforms, v, _base; if (timeoutId != null) { animationsTimeouts = animationsTimeouts.filter(function(timeout) { return timeout.id !== timeoutId; }); } dynamics.stop(el, { timeout: false }); if (!options.animated) { dynamics.css(el, properties); if (typeof options.complete === "function") { options.complete(this); } return; } properties = parseProperties(properties); startProperties = getCurrentProperties(el, Object.keys(properties)); endProperties = {}; transforms = []; for (k in properties) { v = properties[k]; if ((el.style != null) && transformProperties.contains(k)) { transforms.push([k, v]); } else { endProperties[k] = createInterpolable(v); if (endProperties[k] instanceof InterpolableWithUnit && (el.style != null)) { endProperties[k].prefix = ''; if ((_base = endProperties[k]).suffix == null) { _base.suffix = unitForProperty(k, 0); } } } } if (transforms.length > 0) { isSVG = isSVGElement(el); if (isSVG) { matrix = new Matrix2D(); matrix.applyProperties(transforms); } else { v = (transforms.map(function(transform) { return transformValueForProperty(transform[0], transform[1]); })).join(" "); matrix = Matrix.fromTransform(Matrix.matrixForTransform(v)); } endProperties['transform'] = matrix.decompose(); if (isSVG) { startProperties.transform.applyRotateCenter([endProperties.transform.props.rotate[1], endProperties.transform.props.rotate[2]]); } } animations.push({ el: el, properties: { start: startProperties, end: endProperties }, options: options, curve: options.type.call(options.type, options) }); return startRunLoop(); }; timeouts = []; timeoutLastId = 0; setRealTimeout = function(timeout) { if (!isDocumentVisible()) { return; } return timeout.realTimeoutId = setTimeout(function() { timeout.fn(); return cancelTimeout(timeout.id); }, timeout.delay); }; addTimeout = function(fn, delay) { var timeout; timeoutLastId += 1; timeout = { id: timeoutLastId, tStart: Date.now(), fn: fn, delay: delay, originalDelay: delay }; setRealTimeout(timeout); timeouts.push(timeout); return timeoutLastId; }; cancelTimeout = function(id) { return timeouts = timeouts.filter(function(timeout) { if (timeout.id === id) { clearTimeout(timeout.realTimeoutId); } return timeout.id !== id; }); }; leftDelayForTimeout = function(time, timeout) { var consumedDelay; if (time != null) { consumedDelay = time - timeout.tStart; return timeout.originalDelay - consumedDelay; } else { return timeout.originalDelay; } }; if (typeof window !== "undefined" && window !== null) { window.addEventListener('unload', function() {}); } timeBeforeVisibilityChange = null; observeVisibilityChange(function(visible) { var animation, difference, timeout, _i, _j, _k, _len, _len1, _len2, _results; runLoopPaused = !visible; if (!visible) { timeBeforeVisibilityChange = Date.now(); _results = []; for (_i = 0, _len = timeouts.length; _i < _len; _i++) { timeout = timeouts[_i]; _results.push(clearTimeout(timeout.realTimeoutId)); } return _results; } else { if (runLoopRunning) { difference = Date.now() - timeBeforeVisibilityChange; for (_j = 0, _len1 = animations.length; _j < _len1; _j++) { animation = animations[_j]; if (animation.tStart != null) { animation.tStart += difference; } } } for (_k = 0, _len2 = timeouts.length; _k < _len2; _k++) { timeout = timeouts[_k]; timeout.delay = leftDelayForTimeout(timeBeforeVisibilityChange, timeout); setRealTimeout(timeout); } return timeBeforeVisibilityChange = null; } }); dynamics = {}; dynamics.linear = function() { return function(t) { return t; }; }; dynamics.spring = function(options) { var A1, A2, decal, frequency, friction, s; if (options == null) { options = {}; } applyDefaults(options, arguments.callee.defaults); frequency = Math.max(1, options.frequency / 20); friction = Math.pow(20, options.friction / 100); s = options.anticipationSize / 1000; decal = Math.max(0, s); A1 = function(t) { var M, a, b, x0, x1; M = 0.8; x0 = s / (1 - s); x1 = 0; b = (x0 - (M * x1)) / (x0 - x1); a = (M - b) / x0; return (a * t * options.anticipationStrength / 100) + b; }; A2 = function(t) { return Math.pow(friction / 10, -t) * (1 - t); }; return function(t) { var A, At, a, angle, b, frictionT, y0, yS; frictionT = (t / (1 - s)) - (s / (1 - s)); if (t < s) { yS = (s / (1 - s)) - (s / (1 - s)); y0 = (0 / (1 - s)) - (s / (1 - s)); b = Math.acos(1 / A1(yS)); a = (Math.acos(1 / A1(y0)) - b) / (frequency * (-s)); A = A1; } else { A = A2; b = 0; a = 1; } At = A(frictionT); angle = frequency * (t - s) * a + b; return 1 - (At * Math.cos(angle)); }; }; dynamics.bounce = function(options) { var A, fn, frequency, friction; if (options == null) { options = {}; } applyDefaults(options, arguments.callee.defaults); frequency = Math.max(1, options.frequency / 20); friction = Math.pow(20, options.friction / 100); A = function(t) { return Math.pow(friction / 10, -t) * (1 - t); }; fn = function(t) { var At, a, angle, b; b = -3.14 / 2; a = 1; At = A(t); angle = frequency * t * a + b; return At * Math.cos(angle); }; fn.initialForce = true; return fn; }; dynamics.gravity = function(options) { var L, bounciness, curves, elasticity, fn, getPointInCurve, gravity; if (options == null) { options = {}; } applyDefaults(options, arguments.callee.defaults); bounciness = Math.min(options.bounciness / 1250, 0.8); elasticity = options.elasticity / 1000; gravity = 100; curves = []; L = (function() { var b, curve; b = Math.sqrt(2 / gravity); curve = { a: -b, b: b, H: 1 }; if (options.initialForce) { curve.a = 0; curve.b = curve.b * 2; } while (curve.H > 0.001) { L = curve.b - curve.a; curve = { a: curve.b, b: curve.b + L * bounciness, H: curve.H * bounciness * bounciness }; } return curve.b; })(); getPointInCurve = function(a, b, H, t) { var c, t2; L = b - a; t2 = (2 / L) * t - 1 - (a * 2 / L); c = t2 * t2 * H - H + 1; if (options.initialForce) { c = 1 - c; } return c; }; (function() { var L2, b, curve, _results; b = Math.sqrt(2 / (gravity * L * L)); curve = { a: -b, b: b, H: 1 }; if (options.initialForce) { curve.a = 0; curve.b = curve.b * 2; } curves.push(curve); L2 = L; _results = []; while (curve.b < 1 && curve.H > 0.001) { L2 = curve.b - curve.a; curve = { a: curve.b, b: curve.b + L2 * bounciness, H: curve.H * elasticity }; _results.push(curves.push(curve)); } return _results; })(); fn = function(t) { var curve, i, v; i = 0; curve = curves[i]; while (!(t >= curve.a && t <= curve.b)) { i += 1; curve = curves[i]; if (!curve) { break; } } if (!curve) { v = options.initialForce ? 0 : 1; } else { v = getPointInCurve(curve.a, curve.b, curve.H, t); } return v; }; fn.initialForce = options.initialForce; return fn; }; dynamics.forceWithGravity = function(options) { if (options == null) { options = {}; } applyDefaults(options, arguments.callee.defaults); options.initialForce = true; return dynamics.gravity(options); }; dynamics.bezier = (function() { var Bezier, Bezier_, yForX; Bezier_ = function(t, p0, p1, p2, p3) { return (Math.pow(1 - t, 3) * p0) + (3 * Math.pow(1 - t, 2) * t * p1) + (3 * (1 - t) * Math.pow(t, 2) * p2) + Math.pow(t, 3) * p3; }; Bezier = function(t, p0, p1, p2, p3) { return { x: Bezier_(t, p0.x, p1.x, p2.x, p3.x), y: Bezier_(t, p0.y, p1.y, p2.y, p3.y) }; }; yForX = function(xTarget, Bs, returnsToSelf) { var B, aB, i, lower, percent, upper, x, xTolerance, _i, _len; B = null; for (_i = 0, _len = Bs.length; _i < _len; _i++) { aB = Bs[_i]; if (xTarget >= aB(0).x && xTarget <= aB(1).x) { B = aB; } if (B !== null) { break; } } if (!B) { if (returnsToSelf) { return 0; } else { return 1; } } xTolerance = 0.0001; lower = 0; upper = 1; percent = (upper + lower) / 2; x = B(percent).x; i = 0; while (Math.abs(xTarget - x) > xTolerance && i < 100) { if (xTarget > x) { lower = percent; } else { upper = percent; } percent = (upper + lower) / 2; x = B(percent).x; i += 1; } return B(percent).y; }; return function(options) { var Bs, points, returnsToSelf; if (options == null) { options = {}; } points = options.points; returnsToSelf = false; Bs = (function() { var i, k, _fn; Bs = []; _fn = function(pointA, pointB) { var B2; B2 = function(t) { return Bezier(t, pointA, pointA.cp[pointA.cp.length - 1], pointB.cp[0], pointB); }; return Bs.push(B2); }; for (i in points) { k = parseInt(i); if (k >= points.length - 1) { break; } _fn(points[k], points[k + 1]); } return Bs; })(); return function(t) { if (t === 0) { return 0; } else if (t === 1) { return 1; } else { return yForX(t, Bs, returnsToSelf); } }; }; })(); dynamics.easeInOut = function(options) { var friction, _ref; if (options == null) { options = {}; } friction = (_ref = options.friction) != null ? _ref : arguments.callee.defaults.friction; return dynamics.bezier({ points: [ { x: 0, y: 0, cp: [ { x: 0.92 - (friction / 1000), y: 0 } ] }, { x: 1, y: 1, cp: [ { x: 0.08 + (friction / 1000), y: 1 } ] } ] }); }; dynamics.easeIn = function(options) { var friction, _ref; if (options == null) { options = {}; } friction = (_ref = options.friction) != null ? _ref : arguments.callee.defaults.friction; return dynamics.bezier({ points: [ { x: 0, y: 0, cp: [ { x: 0.92 - (friction / 1000), y: 0 } ] }, { x: 1, y: 1, cp: [ { x: 1, y: 1 } ] } ] }); }; dynamics.easeOut = function(options) { var friction, _ref; if (options == null) { options = {}; } friction = (_ref = options.friction) != null ? _ref : arguments.callee.defaults.friction; return dynamics.bezier({ points: [ { x: 0, y: 0, cp: [ { x: 0, y: 0 } ] }, { x: 1, y: 1, cp: [ { x: 0.08 + (friction / 1000), y: 1 } ] } ] }); }; dynamics.spring.defaults = { frequency: 300, friction: 200, anticipationSize: 0, anticipationStrength: 0 }; dynamics.bounce.defaults = { frequency: 300, friction: 200 }; dynamics.forceWithGravity.defaults = dynamics.gravity.defaults = { bounciness: 400, elasticity: 200 }; dynamics.easeInOut.defaults = dynamics.easeIn.defaults = dynamics.easeOut.defaults = { friction: 500 }; dynamics.css = makeArrayFn(function(el, properties) { return applyProperties(el, properties, true); }); dynamics.animate = makeArrayFn(function(el, properties, options) { var id; if (options == null) { options = {}; } options = clone(options); applyDefaults(options, { type: dynamics.easeInOut, duration: 1000, delay: 0, animated: true }); options.duration = Math.max(0, options.duration * slowRatio); options.delay = Math.max(0, options.delay); if (options.delay === 0) { return startAnimation(el, properties, options); } else { id = dynamics.setTimeout(function() { return startAnimation(el, properties, options, id); }, options.delay); return animationsTimeouts.push({ id: id, el: el }); } }); dynamics.stop = makeArrayFn(function(el, options) { if (options == null) { options = {}; } if (options.timeout == null) { options.timeout = true; } if (options.timeout) { animationsTimeouts = animationsTimeouts.filter(function(timeout) { if (timeout.el === el && ((options.filter == null) || options.filter(timeout))) { dynamics.clearTimeout(timeout.id); return false; } return true; }); } return animations = animations.filter(function(animation) { return animation.el !== el; }); }); dynamics.setTimeout = function(fn, delay) { return addTimeout(fn, delay * slowRatio); }; dynamics.clearTimeout = function(id) { return cancelTimeout(id); }; dynamics.toggleSlow = function() { slow = !slow; if (slow) { slowRatio = 3; } else { slowRatio = 1; } return typeof console !== "undefined" && console !== null ? typeof console.log === "function" ? console.log("dynamics.js: slow animations " + (slow ? "enabled" : "disabled")) : void 0 : void 0; }; if (typeof module === "object" && typeof module.exports === "object") { module.exports = dynamics; } else if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return dynamics; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.dynamics = dynamics; } }).call(this); /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { (function (global, factory) { true ? factory(exports, __webpack_require__(4)) : typeof define === 'function' && define.amd ? define(['exports', 'd3-color'], factory) : (factory((global.d3_interpolate = global.d3_interpolate || {}),global.d3_color)); }(this, function (exports,d3Color) { 'use strict'; function constant(x) { return function() { return x; }; } function linear(a, d) { return function(t) { return a + t * d; }; } function exponential(a, b, y) { return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) { return Math.pow(a + t * b, y); }; } function interpolateHue(a, b) { var d = b - a; return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a); } function gamma(y) { return (y = +y) === 1 ? nogamma : function(a, b) { return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a); }; } function nogamma(a, b) { var d = b - a; return d ? linear(a, d) : constant(isNaN(a) ? b : a); } var rgb$1 = (function gamma$$(y) { var interpolateColor = gamma(y); function interpolateRgb(start, end) { var r = interpolateColor((start = d3Color.rgb(start)).r, (end = d3Color.rgb(end)).r), g = interpolateColor(start.g, end.g), b = interpolateColor(start.b, end.b), opacity = interpolateColor(start.opacity, end.opacity); return function(t) { start.r = r(t); start.g = g(t); start.b = b(t); start.opacity = opacity(t); return start + ""; }; } interpolateRgb.gamma = gamma$$; return interpolateRgb; })(1); // TODO sparse arrays? function array(a, b) { var x = [], c = [], na = a ? a.length : 0, nb = b ? b.length : 0, n0 = Math.min(na, nb), i; for (i = 0; i < n0; ++i) x.push(value(a[i], b[i])); for (; i < na; ++i) c[i] = a[i]; for (; i < nb; ++i) c[i] = b[i]; return function(t) { for (i = 0; i < n0; ++i) c[i] = x[i](t); return c; }; } function number(a, b) { return a = +a, b -= a, function(t) { return a + b * t; }; } function object(a, b) { var i = {}, c = {}, k; if (a === null || typeof a !== "object") a = {}; if (b === null || typeof b !== "object") b = {}; for (k in a) { if (k in b) { i[k] = value(a[k], b[k]); } else { c[k] = a[k]; } } for (k in b) { if (!(k in a)) { c[k] = b[k]; } } return function(t) { for (k in i) c[k] = i[k](t); return c; }; } var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g; var reB = new RegExp(reA.source, "g"); function zero(b) { return function() { return b; }; } function one(b) { return function(t) { return b(t) + ""; }; } function string(a, b) { var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b am, // current match in a bm, // current match in b bs, // string preceding current number in b, if any i = -1, // index in s s = [], // string constants and placeholders q = []; // number interpolators // Coerce inputs to strings. a = a + "", b = b + ""; // Interpolate pairs of numbers in a & b. while ((am = reA.exec(a)) && (bm = reB.exec(b))) { if ((bs = bm.index) > bi) { // a string precedes the next number in b bs = b.slice(bi, bs); if (s[i]) s[i] += bs; // coalesce with previous string else s[++i] = bs; } if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match if (s[i]) s[i] += bm; // coalesce with previous string else s[++i] = bm; } else { // interpolate non-matching numbers s[++i] = null; q.push({i: i, x: number(am, bm)}); } bi = reB.lastIndex; } // Add remains of b. if (bi < b.length) { bs = b.slice(bi); if (s[i]) s[i] += bs; // coalesce with previous string else s[++i] = bs; } // Special optimization for only a single match. // Otherwise, interpolate each of the numbers and rejoin the string. return s.length < 2 ? (q[0] ? one(q[0].x) : zero(b)) : (b = q.length, function(t) { for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); return s.join(""); }); } var values = [ function(a, b) { var t = typeof b, c; return (t === "string" ? ((c = d3Color.color(b)) ? (b = c, rgb$1) : string) : b instanceof d3Color.color ? rgb$1 : Array.isArray(b) ? array : t === "object" && isNaN(b) ? object : number)(a, b); } ]; function value(a, b) { var i = values.length, f; while (--i >= 0 && !(f = values[i](a, b))); return f; } function round(a, b) { return a = +a, b -= a, function(t) { return Math.round(a + b * t); }; } var rad2deg = 180 / Math.PI; var identity = { translateX: 0, translateY: 0, rotate: 0, skewX: 0, scaleX: 1, scaleY: 1 }; function decompose(a, b, c, d, e, f) { if (a * d === b * c) return null; var scaleX = Math.sqrt(a * a + b * b); a /= scaleX, b /= scaleX; var skewX = a * c + b * d; c -= a * skewX, d -= b * skewX; var scaleY = Math.sqrt(c * c + d * d); c /= scaleY, d /= scaleY, skewX /= scaleY; if (a * d < b * c) a = -a, b = -b, skewX = -skewX, scaleX = -scaleX; return { translateX: e, translateY: f, rotate: Math.atan2(b, a) * rad2deg, skewX: Math.atan(skewX) * rad2deg, scaleX: scaleX, scaleY: scaleY }; } var cssNode; var cssRoot; var cssView; var svgNode; function parseCss(value) { if (value === "none") return identity; if (!cssNode) cssNode = document.createElement("DIV"), cssRoot = document.documentElement, cssView = document.defaultView; cssNode.style.transform = value; cssRoot.appendChild(cssNode); value = cssView.getComputedStyle(cssNode, null).getPropertyValue("transform"); cssRoot.removeChild(cssNode); var m = value.slice(7, -1).split(","); return decompose(+m[0], +m[1], +m[2], +m[3], +m[4], +m[5]); } function parseSvg(value) { if (!svgNode) svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g"); svgNode.setAttribute("transform", value == null ? "" : value); var m = svgNode.transform.baseVal.consolidate().matrix; return decompose(m.a, m.b, m.c, m.d, m.e, m.f); } function interpolateTransform(parse, pxComma, pxParen, degParen) { function pop(s) { return s.length ? s.pop() + " " : ""; } function translate(xa, ya, xb, yb, s, q) { if (xa !== xb || ya !== yb) { var i = s.push("translate(", null, pxComma, null, pxParen); q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)}); } else if (xb || yb) { s.push("translate(" + xb + pxComma + yb + pxParen); } } function rotate(a, b, s, q) { if (a !== b) { if (a - b > 180) b += 360; else if (b - a > 180) a += 360; // shortest path q.push({i: s.push(pop(s) + "rotate(", null, degParen) - 2, x: number(a, b)}); } else if (b) { s.push(pop(s) + "rotate(" + b + degParen); } } function skewX(a, b, s, q) { if (a !== b) { q.push({i: s.push(pop(s) + "skewX(", null, degParen) - 2, x: number(a, b)}); } else if (b) { s.push(pop(s) + "skewX(" + b + degParen); } } function scale(xa, ya, xb, yb, s, q) { if (xa !== xb || ya !== yb) { var i = s.push(pop(s) + "scale(", null, ",", null, ")"); q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)}); } else if (xb !== 1 || yb !== 1) { s.push(pop(s) + "scale(" + xb + "," + yb + ")"); } } return function(a, b) { var s = [], // string constants and placeholders q = []; // number interpolators a = parse(a), b = parse(b); translate(a.translateX, a.translateY, b.translateX, b.translateY, s, q); rotate(a.rotate, b.rotate, s, q); skewX(a.skewX, b.skewX, s, q); scale(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q); a = b = null; // gc return function(t) { var i = -1, n = q.length, o; while (++i < n) s[(o = q[i]).i] = o.x(t); return s.join(""); }; }; } var interpolateTransformCss = interpolateTransform(parseCss, "px, ", "px)", "deg)"); var interpolateTransformSvg = interpolateTransform(parseSvg, ", ", ")", ")"); var rho = Math.SQRT2; var rho2 = 2; var rho4 = 4; var epsilon2 = 1e-12; function cosh(x) { return ((x = Math.exp(x)) + 1 / x) / 2; } function sinh(x) { return ((x = Math.exp(x)) - 1 / x) / 2; } function tanh(x) { return ((x = Math.exp(2 * x)) - 1) / (x + 1); } // p0 = [ux0, uy0, w0] // p1 = [ux1, uy1, w1] function zoom(p0, p1) { var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; // Special case for u0 ≅ u1. if (d2 < epsilon2) { S = Math.log(w1 / w0) / rho; i = function(t) { return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(rho * t * S) ]; } } // General case. else { var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1), b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); S = (r1 - r0) / rho; i = function(t) { var s = t * S, coshr0 = cosh(r0), u = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s + r0) - sinh(r0)); return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / cosh(rho * s + r0) ]; } } i.duration = S * 1000; return i; } function interpolateHsl(start, end) { var h = interpolateHue((start = d3Color.hsl(start)).h, (end = d3Color.hsl(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.s = s(t); start.l = l(t); start.opacity = opacity(t); return start + ""; }; } function interpolateHslLong(start, end) { var h = nogamma((start = d3Color.hsl(start)).h, (end = d3Color.hsl(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.s = s(t); start.l = l(t); start.opacity = opacity(t); return start + ""; }; } function interpolateLab(start, end) { var l = nogamma((start = d3Color.lab(start)).l, (end = d3Color.lab(end)).l), a = nogamma(start.a, end.a), b = nogamma(start.b, end.b), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.l = l(t); start.a = a(t); start.b = b(t); start.opacity = opacity(t); return start + ""; }; } function interpolateHcl(start, end) { var h = interpolateHue((start = d3Color.hcl(start)).h, (end = d3Color.hcl(end)).h), c = nogamma(start.c, end.c), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.c = c(t); start.l = l(t); start.opacity = opacity(t); return start + ""; }; } function interpolateHclLong(start, end) { var h = nogamma((start = d3Color.hcl(start)).h, (end = d3Color.hcl(end)).h), c = nogamma(start.c, end.c), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.c = c(t); start.l = l(t); start.opacity = opacity(t); return start + ""; }; } var cubehelix$1 = (function gamma(y) { y = +y; function interpolateCubehelix(start, end) { var h = interpolateHue((start = d3Color.cubehelix(start)).h, (end = d3Color.cubehelix(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.s = s(t); start.l = l(Math.pow(t, y)); start.opacity = opacity(t); return start + ""; }; } interpolateCubehelix.gamma = gamma; return interpolateCubehelix; })(1); var cubehelixLong = (function gamma(y) { y = +y; function interpolateCubehelixLong(start, end) { var h = nogamma((start = d3Color.cubehelix(start)).h, (end = d3Color.cubehelix(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.s = s(t); start.l = l(Math.pow(t, y)); start.opacity = opacity(t); return start + ""; }; } interpolateCubehelixLong.gamma = gamma; return interpolateCubehelixLong; })(1); var version = "0.6.0"; exports.version = version; exports.interpolate = value; exports.interpolators = values; exports.interpolateArray = array; exports.interpolateNumber = number; exports.interpolateObject = object; exports.interpolateRound = round; exports.interpolateString = string; exports.interpolateTransformCss = interpolateTransformCss; exports.interpolateTransformSvg = interpolateTransformSvg; exports.interpolateZoom = zoom; exports.interpolateRgb = rgb$1; exports.interpolateHsl = interpolateHsl; exports.interpolateHslLong = interpolateHslLong; exports.interpolateLab = interpolateLab; exports.interpolateHcl = interpolateHcl; exports.interpolateHclLong = interpolateHclLong; exports.interpolateCubehelix = cubehelix$1; exports.interpolateCubehelixLong = cubehelixLong; })); /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { (function (global, factory) { true ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.d3_color = global.d3_color || {}))); }(this, function (exports) { 'use strict'; function define(constructor, factory, prototype) { constructor.prototype = factory.prototype = prototype; prototype.constructor = constructor; } function extend(parent, definition) { var prototype = Object.create(parent.prototype); for (var key in definition) prototype[key] = definition[key]; return prototype; } function Color() {} var darker = 0.7; var brighter = 1 / darker; var reHex3 = /^#([0-9a-f]{3})$/; var reHex6 = /^#([0-9a-f]{6})$/; var reRgbInteger = /^rgb\(\s*([-+]?\d+)\s*,\s*([-+]?\d+)\s*,\s*([-+]?\d+)\s*\)$/; var reRgbPercent = /^rgb\(\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*\)$/; var reRgbaInteger = /^rgba\(\s*([-+]?\d+)\s*,\s*([-+]?\d+)\s*,\s*([-+]?\d+)\s*,\s*([-+]?\d+(?:\.\d+)?)\s*\)$/; var reRgbaPercent = /^rgba\(\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)\s*\)$/; var reHslPercent = /^hsl\(\s*([-+]?\d+(?:\.\d+)?)\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*\)$/; var reHslaPercent = /^hsla\(\s*([-+]?\d+(?:\.\d+)?)\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)\s*\)$/; var named = { aliceblue: 0xf0f8ff, antiquewhite: 0xfaebd7, aqua: 0x00ffff, aquamarine: 0x7fffd4, azure: 0xf0ffff, beige: 0xf5f5dc, bisque: 0xffe4c4, black: 0x000000, blanchedalmond: 0xffebcd, blue: 0x0000ff, blueviolet: 0x8a2be2, brown: 0xa52a2a, burlywood: 0xdeb887, cadetblue: 0x5f9ea0, chartreuse: 0x7fff00, chocolate: 0xd2691e, coral: 0xff7f50, cornflowerblue: 0x6495ed, cornsilk: 0xfff8dc, crimson: 0xdc143c, cyan: 0x00ffff, darkblue: 0x00008b, darkcyan: 0x008b8b, darkgoldenrod: 0xb8860b, darkgray: 0xa9a9a9, darkgreen: 0x006400, darkgrey: 0xa9a9a9, darkkhaki: 0xbdb76b, darkmagenta: 0x8b008b, darkolivegreen: 0x556b2f, darkorange: 0xff8c00, darkorchid: 0x9932cc, darkred: 0x8b0000, darksalmon: 0xe9967a, darkseagreen: 0x8fbc8f, darkslateblue: 0x483d8b, darkslategray: 0x2f4f4f, darkslategrey: 0x2f4f4f, darkturquoise: 0x00ced1, darkviolet: 0x9400d3, deeppink: 0xff1493, deepskyblue: 0x00bfff, dimgray: 0x696969, dimgrey: 0x696969, dodgerblue: 0x1e90ff, firebrick: 0xb22222, floralwhite: 0xfffaf0, forestgreen: 0x228b22, fuchsia: 0xff00ff, gainsboro: 0xdcdcdc, ghostwhite: 0xf8f8ff, gold: 0xffd700, goldenrod: 0xdaa520, gray: 0x808080, green: 0x008000, greenyellow: 0xadff2f, grey: 0x808080, honeydew: 0xf0fff0, hotpink: 0xff69b4, indianred: 0xcd5c5c, indigo: 0x4b0082, ivory: 0xfffff0, khaki: 0xf0e68c, lavender: 0xe6e6fa, lavenderblush: 0xfff0f5, lawngreen: 0x7cfc00, lemonchiffon: 0xfffacd, lightblue: 0xadd8e6, lightcoral: 0xf08080, lightcyan: 0xe0ffff, lightgoldenrodyellow: 0xfafad2, lightgray: 0xd3d3d3, lightgreen: 0x90ee90, lightgrey: 0xd3d3d3, lightpink: 0xffb6c1, lightsalmon: 0xffa07a, lightseagreen: 0x20b2aa, lightskyblue: 0x87cefa, lightslategray: 0x778899, lightslategrey: 0x778899, lightsteelblue: 0xb0c4de, lightyellow: 0xffffe0, lime: 0x00ff00, limegreen: 0x32cd32, linen: 0xfaf0e6, magenta: 0xff00ff, maroon: 0x800000, mediumaquamarine: 0x66cdaa, mediumblue: 0x0000cd, mediumorchid: 0xba55d3, mediumpurple: 0x9370db, mediumseagreen: 0x3cb371, mediumslateblue: 0x7b68ee, mediumspringgreen: 0x00fa9a, mediumturquoise: 0x48d1cc, mediumvioletred: 0xc71585, midnightblue: 0x191970, mintcream: 0xf5fffa, mistyrose: 0xffe4e1, moccasin: 0xffe4b5, navajowhite: 0xffdead, navy: 0x000080, oldlace: 0xfdf5e6, olive: 0x808000, olivedrab: 0x6b8e23, orange: 0xffa500, orangered: 0xff4500, orchid: 0xda70d6, palegoldenrod: 0xeee8aa, palegreen: 0x98fb98, paleturquoise: 0xafeeee, palevioletred: 0xdb7093, papayawhip: 0xffefd5, peachpuff: 0xffdab9, peru: 0xcd853f, pink: 0xffc0cb, plum: 0xdda0dd, powderblue: 0xb0e0e6, purple: 0x800080, rebeccapurple: 0x663399, red: 0xff0000, rosybrown: 0xbc8f8f, royalblue: 0x4169e1, saddlebrown: 0x8b4513, salmon: 0xfa8072, sandybrown: 0xf4a460, seagreen: 0x2e8b57, seashell: 0xfff5ee, sienna: 0xa0522d, silver: 0xc0c0c0, skyblue: 0x87ceeb, slateblue: 0x6a5acd, slategray: 0x708090, slategrey: 0x708090, snow: 0xfffafa, springgreen: 0x00ff7f, steelblue: 0x4682b4, tan: 0xd2b48c, teal: 0x008080, thistle: 0xd8bfd8, tomato: 0xff6347, turquoise: 0x40e0d0, violet: 0xee82ee, wheat: 0xf5deb3, white: 0xffffff, whitesmoke: 0xf5f5f5, yellow: 0xffff00, yellowgreen: 0x9acd32 }; define(Color, color, { displayable: function() { return this.rgb().displayable(); }, toString: function() { return this.rgb() + ""; } }); function color(format) { var m; format = (format + "").trim().toLowerCase(); return (m = reHex3.exec(format)) ? (m = parseInt(m[1], 16), new Rgb((m >> 8 & 0xf) | (m >> 4 & 0x0f0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1)) // #f00 : (m = reHex6.exec(format)) ? rgbn(parseInt(m[1], 16)) // #ff0000 : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0) : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%) : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1) : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1) : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%) : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1) : named.hasOwnProperty(format) ? rgbn(named[format]) : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null; } function rgbn(n) { return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1); } function rgba(r, g, b, a) { if (a <= 0) r = g = b = NaN; return new Rgb(r, g, b, a); } function rgbConvert(o) { if (!(o instanceof Color)) o = color(o); if (!o) return new Rgb; o = o.rgb(); return new Rgb(o.r, o.g, o.b, o.opacity); } function rgb(r, g, b, opacity) { return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity); } function Rgb(r, g, b, opacity) { this.r = +r; this.g = +g; this.b = +b; this.opacity = +opacity; } define(Rgb, rgb, extend(Color, { brighter: function(k) { k = k == null ? brighter : Math.pow(brighter, k); return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); }, darker: function(k) { k = k == null ? darker : Math.pow(darker, k); return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); }, rgb: function() { return this; }, displayable: function() { return (0 <= this.r && this.r <= 255) && (0 <= this.g && this.g <= 255) && (0 <= this.b && this.b <= 255) && (0 <= this.opacity && this.opacity <= 1); }, toString: function() { var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a)); return (a === 1 ? "rgb(" : "rgba(") + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", " + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", " + Math.max(0, Math.min(255, Math.round(this.b) || 0)) + (a === 1 ? ")" : ", " + a + ")"); } })); function hsla(h, s, l, a) { if (a <= 0) h = s = l = NaN; else if (l <= 0 || l >= 1) h = s = NaN; else if (s <= 0) h = NaN; return new Hsl(h, s, l, a); } function hslConvert(o) { if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity); if (!(o instanceof Color)) o = color(o); if (!o) return new Hsl; if (o instanceof Hsl) return o; o = o.rgb(); var r = o.r / 255, g = o.g / 255, b = o.b / 255, min = Math.min(r, g, b), max = Math.max(r, g, b), h = NaN, s = max - min, l = (max + min) / 2; if (s) { if (r === max) h = (g - b) / s + (g < b) * 6; else if (g === max) h = (b - r) / s + 2; else h = (r - g) / s + 4; s /= l < 0.5 ? max + min : 2 - max - min; h *= 60; } else { s = l > 0 && l < 1 ? 0 : h; } return new Hsl(h, s, l, o.opacity); } function hsl(h, s, l, opacity) { return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity); } function Hsl(h, s, l, opacity) { this.h = +h; this.s = +s; this.l = +l; this.opacity = +opacity; } define(Hsl, hsl, extend(Color, { brighter: function(k) { k = k == null ? brighter : Math.pow(brighter, k); return new Hsl(this.h, this.s, this.l * k, this.opacity); }, darker: function(k) { k = k == null ? darker : Math.pow(darker, k); return new Hsl(this.h, this.s, this.l * k, this.opacity); }, rgb: function() { var h = this.h % 360 + (this.h < 0) * 360, s = isNaN(h) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s, m1 = 2 * l - m2; return new Rgb( hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2), hsl2rgb(h, m1, m2), hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2), this.opacity ); }, displayable: function() { return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && (0 <= this.l && this.l <= 1) && (0 <= this.opacity && this.opacity <= 1); } })); /* From FvD 13.37, CSS Color Module Level 3 */ function hsl2rgb(h, m1, m2) { return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255; } var deg2rad = Math.PI / 180; var rad2deg = 180 / Math.PI; var Kn = 18; var Xn = 0.950470; var Yn = 1; var Zn = 1.088830; var t0 = 4 / 29; var t1 = 6 / 29; var t2 = 3 * t1 * t1; var t3 = t1 * t1 * t1; function labConvert(o) { if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity); if (o instanceof Hcl) { var h = o.h * deg2rad; return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity); } if (!(o instanceof Rgb)) o = rgbConvert(o); var b = rgb2xyz(o.r), a = rgb2xyz(o.g), l = rgb2xyz(o.b), x = xyz2lab((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn), y = xyz2lab((0.2126729 * b + 0.7151522 * a + 0.0721750 * l) / Yn), z = xyz2lab((0.0193339 * b + 0.1191920 * a + 0.9503041 * l) / Zn); return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity); } function lab(l, a, b, opacity) { return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity); } function Lab(l, a, b, opacity) { this.l = +l; this.a = +a; this.b = +b; this.opacity = +opacity; } define(Lab, lab, extend(Color, { brighter: function(k) { return new Lab(this.l + Kn * (k == null ? 1 : k), this.a, this.b, this.opacity); }, darker: function(k) { return new Lab(this.l - Kn * (k == null ? 1 : k), this.a, this.b, this.opacity); }, rgb: function() { var y = (this.l + 16) / 116, x = isNaN(this.a) ? y : y + this.a / 500, z = isNaN(this.b) ? y : y - this.b / 200; y = Yn * lab2xyz(y); x = Xn * lab2xyz(x); z = Zn * lab2xyz(z); return new Rgb( xyz2rgb( 3.2404542 * x - 1.5371385 * y - 0.4985314 * z), // D65 -> sRGB xyz2rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z), xyz2rgb( 0.0556434 * x - 0.2040259 * y + 1.0572252 * z), this.opacity ); } })); function xyz2lab(t) { return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0; } function lab2xyz(t) { return t > t1 ? t * t * t : t2 * (t - t0); } function xyz2rgb(x) { return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055); } function rgb2xyz(x) { return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); } function hclConvert(o) { if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity); if (!(o instanceof Lab)) o = labConvert(o); var h = Math.atan2(o.b, o.a) * rad2deg; return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity); } function hcl(h, c, l, opacity) { return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity); } function Hcl(h, c, l, opacity) { this.h = +h; this.c = +c; this.l = +l; this.opacity = +opacity; } define(Hcl, hcl, extend(Color, { brighter: function(k) { return new Hcl(this.h, this.c, this.l + Kn * (k == null ? 1 : k), this.opacity); }, darker: function(k) { return new Hcl(this.h, this.c, this.l - Kn * (k == null ? 1 : k), this.opacity); }, rgb: function() { return labConvert(this).rgb(); } })); var A = -0.14861; var B = +1.78277; var C = -0.29227; var D = -0.90649; var E = +1.97294; var ED = E * D; var EB = E * B; var BC_DA = B * C - D * A; function cubehelixConvert(o) { if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity); if (!(o instanceof Rgb)) o = rgbConvert(o); var r = o.r / 255, g = o.g / 255, b = o.b / 255, l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB), bl = b - l, k = (E * (g - l) - C * bl) / D, s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1 h = s ? Math.atan2(k, bl) * rad2deg - 120 : NaN; return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity); } function cubehelix(h, s, l, opacity) { return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity); } function Cubehelix(h, s, l, opacity) { this.h = +h; this.s = +s; this.l = +l; this.opacity = +opacity; } define(Cubehelix, cubehelix, extend(Color, { brighter: function(k) { k = k == null ? brighter : Math.pow(brighter, k); return new Cubehelix(this.h, this.s, this.l * k, this.opacity); }, darker: function(k) { k = k == null ? darker : Math.pow(darker, k); return new Cubehelix(this.h, this.s, this.l * k, this.opacity); }, rgb: function() { var h = isNaN(this.h) ? 0 : (this.h + 120) * deg2rad, l = +this.l, a = isNaN(this.s) ? 0 : this.s * l * (1 - l), cosh = Math.cos(h), sinh = Math.sin(h); return new Rgb( 255 * (l + a * (A * cosh + B * sinh)), 255 * (l + a * (C * cosh + D * sinh)), 255 * (l + a * (E * cosh)), this.opacity ); } })); var version = "0.4.2"; exports.version = version; exports.color = color; exports.rgb = rgb; exports.hsl = hsl; exports.lab = lab; exports.hcl = hcl; exports.cubehelix = cubehelix; })); /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if (process.env.NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 7 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(9); /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule React */ 'use strict'; var ReactDOM = __webpack_require__(10); var ReactDOMServer = __webpack_require__(154); var ReactIsomorphic = __webpack_require__(158); var assign = __webpack_require__(45); var deprecated = __webpack_require__(163); // `version` will be added here by ReactIsomorphic. var React = {}; assign(React, ReactIsomorphic); assign(React, { // ReactDOM findDOMNode: deprecated('findDOMNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.findDOMNode), render: deprecated('render', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.render), unmountComponentAtNode: deprecated('unmountComponentAtNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.unmountComponentAtNode), // ReactDOMServer renderToString: deprecated('renderToString', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToString), renderToStaticMarkup: deprecated('renderToStaticMarkup', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToStaticMarkup) }); React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOM; React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOMServer; module.exports = React; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOM */ /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ 'use strict'; var ReactCurrentOwner = __webpack_require__(11); var ReactDOMTextComponent = __webpack_require__(12); var ReactDefaultInjection = __webpack_require__(77); var ReactInstanceHandles = __webpack_require__(51); var ReactMount = __webpack_require__(34); var ReactPerf = __webpack_require__(24); var ReactReconciler = __webpack_require__(56); var ReactUpdates = __webpack_require__(60); var ReactVersion = __webpack_require__(152); var findDOMNode = __webpack_require__(97); var renderSubtreeIntoContainer = __webpack_require__(153); var warning = __webpack_require__(31); ReactDefaultInjection.inject(); var render = ReactPerf.measure('React', 'render', ReactMount.render); var React = { findDOMNode: findDOMNode, render: render, unmountComponentAtNode: ReactMount.unmountComponentAtNode, version: ReactVersion, /* eslint-disable camelcase */ unstable_batchedUpdates: ReactUpdates.batchedUpdates, unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. /* eslint-enable camelcase */ if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ CurrentOwner: ReactCurrentOwner, InstanceHandles: ReactInstanceHandles, Mount: ReactMount, Reconciler: ReactReconciler, TextComponent: ReactDOMTextComponent }); } if (process.env.NODE_ENV !== 'production') { var ExecutionEnvironment = __webpack_require__(15); if (ExecutionEnvironment.canUseDOM && window.top === window.self) { // First check if devtools is not installed if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { // If we're in Chrome or Firefox, provide a download link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { console.debug('Download the React DevTools for a better development experience: ' + 'https://fb.me/react-devtools'); } } // If we're in IE8, check to see if we are in compatibility mode and provide // information on preventing compatibility mode var ieCompatibilityMode = document.documentMode && document.documentMode < 8; process.env.NODE_ENV !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : undefined; var expectedFeatures = [ // shims Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim, // shams Object.create, Object.freeze]; for (var i = 0; i < expectedFeatures.length; i++) { if (!expectedFeatures[i]) { console.error('One or more ES5 shim/shams expected by React are not available: ' + 'https://fb.me/react-warning-polyfills'); break; } } } } module.exports = React; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 11 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCurrentOwner */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextComponent * @typechecks static-only */ 'use strict'; var DOMChildrenOperations = __webpack_require__(13); var DOMPropertyOperations = __webpack_require__(28); var ReactComponentBrowserEnvironment = __webpack_require__(32); var ReactMount = __webpack_require__(34); var assign = __webpack_require__(45); var escapeTextContentForBrowser = __webpack_require__(27); var setTextContent = __webpack_require__(26); var validateDOMNesting = __webpack_require__(76); /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings in elements so that they can undergo * the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactDOMTextComponent * @extends ReactComponent * @internal */ var ReactDOMTextComponent = function (props) { // This constructor and its argument is currently used by mocks. }; assign(ReactDOMTextComponent.prototype, { /** * @param {ReactText} text * @internal */ construct: function (text) { // TODO: This is really a ReactText (ReactNode), not a ReactElement this._currentElement = text; this._stringText = '' + text; // Properties this._rootNodeID = null; this._mountIndex = 0; }, /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function (rootID, transaction, context) { if (process.env.NODE_ENV !== 'production') { if (context[validateDOMNesting.ancestorInfoContextKey]) { validateDOMNesting('span', null, context[validateDOMNesting.ancestorInfoContextKey]); } } this._rootNodeID = rootID; if (transaction.useCreateElement) { var ownerDocument = context[ReactMount.ownerDocumentContextKey]; var el = ownerDocument.createElement('span'); DOMPropertyOperations.setAttributeForID(el, rootID); // Populate node cache ReactMount.getID(el); setTextContent(el, this._stringText); return el; } else { var escapedText = escapeTextContentForBrowser(this._stringText); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this in a `span` for the reasons stated above, but // since this is a situation where React won't take over (static pages), // we can simply return the text as it is. return escapedText; } return '<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' + escapedText + '</span>'; } }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function (nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = '' + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; var node = ReactMount.getNode(this._rootNodeID); DOMChildrenOperations.updateTextContent(node, nextStringText); } } }, unmountComponent: function () { ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); } }); module.exports = ReactDOMTextComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMChildrenOperations * @typechecks static-only */ 'use strict'; var Danger = __webpack_require__(14); var ReactMultiChildUpdateTypes = __webpack_require__(22); var ReactPerf = __webpack_require__(24); var setInnerHTML = __webpack_require__(25); var setTextContent = __webpack_require__(26); var invariant = __webpack_require__(19); /** * Inserts `childNode` as a child of `parentNode` at the `index`. * * @param {DOMElement} parentNode Parent node in which to insert. * @param {DOMElement} childNode Child node to insert. * @param {number} index Index at which to insert the child. * @internal */ function insertChildAt(parentNode, childNode, index) { // By exploiting arrays returning `undefined` for an undefined index, we can // rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. However, using `undefined` is not allowed by all // browsers so we must replace it with `null`. // fix render order error in safari // IE8 will throw error when index out of list size. var beforeChild = index >= parentNode.childNodes.length ? null : parentNode.childNodes.item(index); parentNode.insertBefore(childNode, beforeChild); } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup, updateTextContent: setTextContent, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @param {array<string>} markupList List of markup strings. * @internal */ processUpdates: function (updates, markupList) { var update; // Mapping from parent IDs to initial child orderings. var initialChildren = null; // List of children that will be moved or removed. var updatedChildren = null; for (var i = 0; i < updates.length; i++) { update = updates[i]; if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING || update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) { var updatedIndex = update.fromIndex; var updatedChild = update.parentNode.childNodes[updatedIndex]; var parentID = update.parentID; !updatedChild ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processUpdates(): Unable to find child %s of element. This ' + 'probably means the DOM was unexpectedly mutated (e.g., by the ' + 'browser), usually due to forgetting a <tbody> when using tables, ' + 'nesting tags like <form>, <p>, or <a>, or using non-SVG elements ' + 'in an <svg> parent. Try inspecting the child nodes of the element ' + 'with React ID `%s`.', updatedIndex, parentID) : invariant(false) : undefined; initialChildren = initialChildren || {}; initialChildren[parentID] = initialChildren[parentID] || []; initialChildren[parentID][updatedIndex] = updatedChild; updatedChildren = updatedChildren || []; updatedChildren.push(updatedChild); } } var renderedMarkup; // markupList is either a list of markup or just a list of elements if (markupList.length && typeof markupList[0] === 'string') { renderedMarkup = Danger.dangerouslyRenderMarkup(markupList); } else { renderedMarkup = markupList; } // Remove updated children first so that `toIndex` is consistent. if (updatedChildren) { for (var j = 0; j < updatedChildren.length; j++) { updatedChildren[j].parentNode.removeChild(updatedChildren[j]); } } for (var k = 0; k < updates.length; k++) { update = updates[k]; switch (update.type) { case ReactMultiChildUpdateTypes.INSERT_MARKUP: insertChildAt(update.parentNode, renderedMarkup[update.markupIndex], update.toIndex); break; case ReactMultiChildUpdateTypes.MOVE_EXISTING: insertChildAt(update.parentNode, initialChildren[update.parentID][update.fromIndex], update.toIndex); break; case ReactMultiChildUpdateTypes.SET_MARKUP: setInnerHTML(update.parentNode, update.content); break; case ReactMultiChildUpdateTypes.TEXT_CONTENT: setTextContent(update.parentNode, update.content); break; case ReactMultiChildUpdateTypes.REMOVE_NODE: // Already removed by the for-loop above. break; } } } }; ReactPerf.measureMethods(DOMChildrenOperations, 'DOMChildrenOperations', { updateTextContent: 'updateTextContent' }); module.exports = DOMChildrenOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Danger * @typechecks static-only */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var createNodesFromMarkup = __webpack_require__(16); var emptyFunction = __webpack_require__(21); var getMarkupWrap = __webpack_require__(20); var invariant = __webpack_require__(19); var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/; var RESULT_INDEX_ATTR = 'data-danger-index'; /** * Extracts the `nodeName` from a string of markup. * * NOTE: Extracting the `nodeName` does not require a regular expression match * because we make assumptions about React-generated markup (i.e. there are no * spaces surrounding the opening tag and there is at least one attribute). * * @param {string} markup String of markup. * @return {string} Node name of the supplied markup. * @see http://jsperf.com/extract-nodename */ function getNodeName(markup) { return markup.substring(1, markup.indexOf(' ')); } var Danger = { /** * Renders markup into an array of nodes. The markup is expected to render * into a list of root nodes. Also, the length of `resultList` and * `markupList` should be the same. * * @param {array<string>} markupList List of markup strings to render. * @return {array<DOMElement>} List of rendered nodes. * @internal */ dangerouslyRenderMarkup: function (markupList) { !ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString for server rendering.') : invariant(false) : undefined; var nodeName; var markupByNodeName = {}; // Group markup by `nodeName` if a wrap is necessary, else by '*'. for (var i = 0; i < markupList.length; i++) { !markupList[i] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Missing markup.') : invariant(false) : undefined; nodeName = getNodeName(markupList[i]); nodeName = getMarkupWrap(nodeName) ? nodeName : '*'; markupByNodeName[nodeName] = markupByNodeName[nodeName] || []; markupByNodeName[nodeName][i] = markupList[i]; } var resultList = []; var resultListAssignmentCount = 0; for (nodeName in markupByNodeName) { if (!markupByNodeName.hasOwnProperty(nodeName)) { continue; } var markupListByNodeName = markupByNodeName[nodeName]; // This for-in loop skips the holes of the sparse array. The order of // iteration should follow the order of assignment, which happens to match // numerical index order, but we don't rely on that. var resultIndex; for (resultIndex in markupListByNodeName) { if (markupListByNodeName.hasOwnProperty(resultIndex)) { var markup = markupListByNodeName[resultIndex]; // Push the requested markup with an additional RESULT_INDEX_ATTR // attribute. If the markup does not start with a < character, it // will be discarded below (with an appropriate console.error). markupListByNodeName[resultIndex] = markup.replace(OPEN_TAG_NAME_EXP, // This index will be parsed back out below. '$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" '); } } // Render each group of markup with similar wrapping `nodeName`. var renderNodes = createNodesFromMarkup(markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags. ); for (var j = 0; j < renderNodes.length; ++j) { var renderNode = renderNodes[j]; if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) { resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR); renderNode.removeAttribute(RESULT_INDEX_ATTR); !!resultList.hasOwnProperty(resultIndex) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Assigning to an already-occupied result index.') : invariant(false) : undefined; resultList[resultIndex] = renderNode; // This should match resultList.length and markupList.length when // we're done. resultListAssignmentCount += 1; } else if (process.env.NODE_ENV !== 'production') { console.error('Danger: Discarding unexpected node:', renderNode); } } } // Although resultList was populated out of order, it should now be a dense // array. !(resultListAssignmentCount === resultList.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Did not assign to every index of resultList.') : invariant(false) : undefined; !(resultList.length === markupList.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length) : invariant(false) : undefined; return resultList; }, /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) { !ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. Make sure `window` and `document` are available ' + 'globally before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined; !markup ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(false) : undefined; !(oldChild.tagName.toLowerCase() !== 'html') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' + '<html> node. This is because browser quirks make this unreliable ' + 'and/or slow. If you want to render to the root you must use ' + 'server rendering. See ReactDOMServer.renderToString().') : invariant(false) : undefined; var newChild; if (typeof markup === 'string') { newChild = createNodesFromMarkup(markup, emptyFunction)[0]; } else { newChild = markup; } oldChild.parentNode.replaceChild(newChild, oldChild); } }; module.exports = Danger; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 15 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ExecutionEnvironment */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createNodesFromMarkup * @typechecks */ /*eslint-disable fb-www/unsafe-html*/ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var createArrayFromMixed = __webpack_require__(17); var getMarkupWrap = __webpack_require__(20); var invariant = __webpack_require__(19); /** * Dummy container used to render all markup. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Pattern used by `getNodeName`. */ var nodeNamePattern = /^\s*<(\w+)/; /** * Extracts the `nodeName` of the first element in a string of markup. * * @param {string} markup String of markup. * @return {?string} Node name of the supplied markup. */ function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); } /** * Creates an array containing the nodes rendered from the supplied markup. The * optionally supplied `handleScript` function will be invoked once for each * <script> element that is rendered. If no `handleScript` function is supplied, * an exception is thrown if any <script> elements are rendered. * * @param {string} markup A string of valid HTML markup. * @param {?function} handleScript Invoked once for each rendered <script>. * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. */ function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; !!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : undefined; var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { !handleScript ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : undefined; createArrayFromMixed(scripts).forEach(handleScript); } var nodes = createArrayFromMixed(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createArrayFromMixed * @typechecks */ 'use strict'; var toArray = __webpack_require__(18); /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { return( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFromMixed = require('createArrayFromMixed'); * * function takesOneOrMoreThings(things) { * things = createArrayFromMixed(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFromMixed; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule toArray * @typechecks */ 'use strict'; var invariant = __webpack_require__(19); /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFromMixed. * * @param {object|function|filelist} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browse builtin objects can report typeof 'function' (e.g. NodeList in // old versions of Safari). !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : undefined; !(typeof length === 'number') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : undefined; !(length === 0 || length - 1 in obj) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : undefined; // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } module.exports = toArray; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule invariant */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ function invariant(condition, format, a, b, c, d, e, f) { if (process.env.NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getMarkupWrap */ /*eslint-disable fb-www/unsafe-html */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var invariant = __webpack_require__(19); /** * Dummy container used to detect which wraps are necessary. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Some browsers cannot use `innerHTML` to render certain elements standalone, * so we wrap them, render the wrapped nodes, then extract the desired node. * * In IE8, certain elements cannot render alone, so wrap all elements ('*'). */ var shouldWrap = {}; var selectWrap = [1, '<select multiple="true">', '</select>']; var tableWrap = [1, '<table>', '</table>']; var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>']; var markupWrap = { '*': [1, '?<div>', '</div>'], 'area': [1, '<map>', '</map>'], 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], 'legend': [1, '<fieldset>', '</fieldset>'], 'param': [1, '<object>', '</object>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'optgroup': selectWrap, 'option': selectWrap, 'caption': tableWrap, 'colgroup': tableWrap, 'tbody': tableWrap, 'tfoot': tableWrap, 'thead': tableWrap, 'td': trWrap, 'th': trWrap }; // Initialize the SVG elements since we know they'll always need to be wrapped // consistently. If they are created inside a <div> they will be initialized in // the wrong namespace (and will not display). var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan']; svgElements.forEach(function (nodeName) { markupWrap[nodeName] = svgWrap; shouldWrap[nodeName] = true; }); /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { !!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : undefined; if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode.innerHTML = '<link />'; } else { dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; } module.exports = getMarkupWrap; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 21 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyFunction */ "use strict"; function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChildUpdateTypes */ 'use strict'; var keyMirror = __webpack_require__(23); /** * When a component's children are updated, a series of update configuration * objects are created in order to batch and serialize the required changes. * * Enumerates all the possible types of update configurations. * * @internal */ var ReactMultiChildUpdateTypes = keyMirror({ INSERT_MARKUP: null, MOVE_EXISTING: null, REMOVE_NODE: null, SET_MARKUP: null, TEXT_CONTENT: null }); module.exports = ReactMultiChildUpdateTypes; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyMirror * @typechecks static-only */ 'use strict'; var invariant = __webpack_require__(19); /** * Constructs an enumeration with keys equal to their value. * * For example: * * var COLORS = keyMirror({blue: null, red: null}); * var myColor = COLORS.blue; * var isColorValid = !!COLORS[myColor]; * * The last line could not be performed if the values of the generated enum were * not equal to their keys. * * Input: {key1: val1, key2: val2} * Output: {key1: key1, key2: key2} * * @param {object} obj * @return {object} */ var keyMirror = function (obj) { var ret = {}; var key; !(obj instanceof Object && !Array.isArray(obj)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : undefined; for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPerf * @typechecks static-only */ 'use strict'; /** * ReactPerf is a general AOP system designed to measure performance. This * module only has the hooks: see ReactDefaultPerf for the analysis tool. */ var ReactPerf = { /** * Boolean to enable/disable measurement. Set to false by default to prevent * accidental logging and perf loss. */ enableMeasure: false, /** * Holds onto the measure function in use. By default, don't measure * anything, but we'll override this if we inject a measure function. */ storedMeasure: _noMeasure, /** * @param {object} object * @param {string} objectName * @param {object<string>} methodNames */ measureMethods: function (object, objectName, methodNames) { if (process.env.NODE_ENV !== 'production') { for (var key in methodNames) { if (!methodNames.hasOwnProperty(key)) { continue; } object[key] = ReactPerf.measure(objectName, methodNames[key], object[key]); } } }, /** * Use this to wrap methods you want to measure. Zero overhead in production. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ measure: function (objName, fnName, func) { if (process.env.NODE_ENV !== 'production') { var measuredFunc = null; var wrapper = function () { if (ReactPerf.enableMeasure) { if (!measuredFunc) { measuredFunc = ReactPerf.storedMeasure(objName, fnName, func); } return measuredFunc.apply(this, arguments); } return func.apply(this, arguments); }; wrapper.displayName = objName + '_' + fnName; return wrapper; } return func; }, injection: { /** * @param {function} measure */ injectMeasure: function (measure) { ReactPerf.storedMeasure = measure; } } }; /** * Simply passes through the measured function, without measuring it. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ function _noMeasure(objName, fnName, func) { return func; } module.exports = ReactPerf; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setInnerHTML */ /* globals MSApp */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var WHITESPACE_TEST = /^[ \r\n\t\f]/; var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; /** * Set the innerHTML property of a node, ensuring that whitespace is preserved * even in IE8. * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = function (node, html) { node.innerHTML = html; }; // Win8 apps: Allow all html to be inserted if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { setInnerHTML = function (node, html) { MSApp.execUnsafeLocalFunction(function () { node.innerHTML = html; }); }; } if (ExecutionEnvironment.canUseDOM) { // IE8: When updating a just created node with innerHTML only leading // whitespace is removed. When updating an existing node with innerHTML // whitespace in root TextNodes is also collapsed. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html // Feature detection; only IE8 is known to behave improperly like this. var testElement = document.createElement('div'); testElement.innerHTML = ' '; if (testElement.innerHTML === '') { setInnerHTML = function (node, html) { // Magic theory: IE8 supposedly differentiates between added and updated // nodes when processing innerHTML, innerHTML on updated nodes suffers // from worse whitespace behavior. Re-adding a node like this triggers // the initial and more favorable whitespace behavior. // TODO: What to do on a detached node? if (node.parentNode) { node.parentNode.replaceChild(node, node); } // We also implement a workaround for non-visible tags disappearing into // thin air on IE8, this only happens if there is no visible text // in-front of the non-visible tags. Piggyback on the whitespace fix // and simply check if any non-visible tags appear in the source. if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. // UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode // in hopes that this is preserved even if "\uFEFF" is transformed to // the actual Unicode character (by Babel, for example). // https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216 node.innerHTML = String.fromCharCode(0xFEFF) + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; if (textNode.data.length === 1) { node.removeChild(textNode); } else { textNode.deleteData(0, 1); } } else { node.innerHTML = html; } }; } } module.exports = setInnerHTML; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setTextContent */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var escapeTextContentForBrowser = __webpack_require__(27); var setInnerHTML = __webpack_require__(25); /** * Set the textContent property of a node, ensuring that whitespace is preserved * even in IE8. innerText is a poor substitute for textContent and, among many * issues, inserts <br> instead of the literal newline chars. innerHTML behaves * as it should. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function (node, text) { node.textContent = text; }; if (ExecutionEnvironment.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function (node, text) { setInnerHTML(node, escapeTextContentForBrowser(text)); }; } } module.exports = setTextContent; /***/ }, /* 27 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule escapeTextContentForBrowser */ 'use strict'; var ESCAPE_LOOKUP = { '&': '&amp;', '>': '&gt;', '<': '&lt;', '"': '&quot;', '\'': '&#x27;' }; var ESCAPE_REGEX = /[&><"']/g; function escaper(match) { return ESCAPE_LOOKUP[match]; } /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextContentForBrowser(text) { return ('' + text).replace(ESCAPE_REGEX, escaper); } module.exports = escapeTextContentForBrowser; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMPropertyOperations * @typechecks static-only */ 'use strict'; var DOMProperty = __webpack_require__(29); var ReactPerf = __webpack_require__(24); var quoteAttributeValueForBrowser = __webpack_require__(30); var warning = __webpack_require__(31); // Simplified subset var VALID_ATTRIBUTE_NAME_REGEX = /^[a-zA-Z_][\w\.\-]*$/; var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { return true; } if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : undefined; return false; } function shouldIgnoreValue(propertyInfo, value) { return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false; } if (process.env.NODE_ENV !== 'production') { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true }; var warnedProperties = {}; var warnUnknownProperty = function (name) { if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return; } warnedProperties[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; // For now, only warn when we have a suggested correction. This prevents // logging too much when using transferPropsTo. process.env.NODE_ENV !== 'production' ? warning(standardName == null, 'Unknown DOM property %s. Did you mean %s?', name, standardName) : undefined; }; } /** * Operations for dealing with DOM properties. */ var DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function (id) { return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id); }, setAttributeForID: function (node, id) { node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id); }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function (name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { if (shouldIgnoreValue(propertyInfo, value)) { return ''; } var attributeName = propertyInfo.attributeName; if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { return attributeName + '=""'; } return attributeName + '=' + quoteAttributeValueForBrowser(value); } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); } else if (process.env.NODE_ENV !== 'production') { warnUnknownProperty(name); } return null; }, /** * Creates markup for a custom property. * * @param {string} name * @param {*} value * @return {string} Markup string, or empty string if the property was invalid. */ createMarkupForCustomAttribute: function (name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function (node, name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(propertyInfo, value)) { this.deleteValueForProperty(node, name); } else if (propertyInfo.mustUseAttribute) { var attributeName = propertyInfo.attributeName; var namespace = propertyInfo.attributeNamespace; // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. if (namespace) { node.setAttributeNS(namespace, attributeName, '' + value); } else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { node.setAttribute(attributeName, ''); } else { node.setAttribute(attributeName, '' + value); } } else { var propName = propertyInfo.propertyName; // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the // property type before comparing; only `value` does and is string. if (!propertyInfo.hasSideEffects || '' + node[propName] !== '' + value) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propName] = value; } } } else if (DOMProperty.isCustomAttribute(name)) { DOMPropertyOperations.setValueForAttribute(node, name, value); } else if (process.env.NODE_ENV !== 'production') { warnUnknownProperty(name); } }, setValueForAttribute: function (node, name, value) { if (!isAttributeNameSafe(name)) { return; } if (value == null) { node.removeAttribute(name); } else { node.setAttribute(name, '' + value); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function (node, name) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, undefined); } else if (propertyInfo.mustUseAttribute) { node.removeAttribute(propertyInfo.attributeName); } else { var propName = propertyInfo.propertyName; var defaultValue = DOMProperty.getDefaultValueForProperty(node.nodeName, propName); if (!propertyInfo.hasSideEffects || '' + node[propName] !== defaultValue) { node[propName] = defaultValue; } } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } else if (process.env.NODE_ENV !== 'production') { warnUnknownProperty(name); } } }; ReactPerf.measureMethods(DOMPropertyOperations, 'DOMPropertyOperations', { setValueForProperty: 'setValueForProperty', setValueForAttribute: 'setValueForAttribute', deleteValueForProperty: 'deleteValueForProperty' }); module.exports = DOMPropertyOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMProperty * @typechecks static-only */ 'use strict'; var invariant = __webpack_require__(19); function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_ATTRIBUTE: 0x1, MUST_USE_PROPERTY: 0x2, HAS_SIDE_EFFECTS: 0x4, HAS_BOOLEAN_VALUE: 0x8, HAS_NUMERIC_VALUE: 0x10, HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10, HAS_OVERLOADED_BOOLEAN_VALUE: 0x40, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMAttributeNamespaces: object mapping React attribute name to the DOM * attribute namespace URL. (Attribute names not specified use no namespace.) * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function (domPropertyConfig) { var Injection = DOMPropertyInjection; var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute); } for (var propName in Properties) { !!DOMProperty.properties.hasOwnProperty(propName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName) : invariant(false) : undefined; var lowerCased = propName.toLowerCase(); var propConfig = Properties[propName]; var propertyInfo = { attributeName: lowerCased, attributeNamespace: null, propertyName: propName, mutationMethod: null, mustUseAttribute: checkMask(propConfig, Injection.MUST_USE_ATTRIBUTE), mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS), hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE) }; !(!propertyInfo.mustUseAttribute || !propertyInfo.mustUseProperty) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Cannot require using both attribute and property: %s', propName) : invariant(false) : undefined; !(propertyInfo.mustUseProperty || !propertyInfo.hasSideEffects) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Properties that have side effects must use property: %s', propName) : invariant(false) : undefined; !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName) : invariant(false) : undefined; if (process.env.NODE_ENV !== 'production') { DOMProperty.getPossibleStandardName[lowerCased] = propName; } if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName; if (process.env.NODE_ENV !== 'production') { DOMProperty.getPossibleStandardName[attributeName] = propName; } } if (DOMAttributeNamespaces.hasOwnProperty(propName)) { propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; } if (DOMPropertyNames.hasOwnProperty(propName)) { propertyInfo.propertyName = DOMPropertyNames[propName]; } if (DOMMutationMethods.hasOwnProperty(propName)) { propertyInfo.mutationMethod = DOMMutationMethods[propName]; } DOMProperty.properties[propName] = propertyInfo; } } }; var defaultValueCache = {}; /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', /** * Map from property "standard name" to an object with info about how to set * the property in the DOM. Each object contains: * * attributeName: * Used when rendering markup or with `*Attribute()`. * attributeNamespace * propertyName: * Used on DOM node instances. (This includes properties that mutate due to * external factors.) * mutationMethod: * If non-null, used instead of the property or `setAttribute()` after * initial render. * mustUseAttribute: * Whether the property must be accessed and mutated using `*Attribute()`. * (This includes anything that fails `<propName> in <element>`.) * mustUseProperty: * Whether the property must be accessed and mutated as an object property. * hasSideEffects: * Whether or not setting a value causes side effects such as triggering * resources to be loaded or text selection changes. If true, we read from * the DOM before updating to ensure that the value is only set if it has * changed. * hasBooleanValue: * Whether the property should be removed when set to a falsey value. * hasNumericValue: * Whether the property must be numeric or parse as a numeric and should be * removed when set to a falsey value. * hasPositiveNumericValue: * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * hasOverloadedBooleanValue: * Whether the property can be used as a flag as well as with a value. * Removed when strictly equal to false; present without a value when * strictly equal to true; present with a value otherwise. */ properties: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. Available only in __DEV__. * @type {Object} */ getPossibleStandardName: process.env.NODE_ENV !== 'production' ? {} : null, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function (attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, /** * Returns the default property value for a DOM property (i.e., not an * attribute). Most default values are '' or false, but not all. Worse yet, * some (in particular, `type`) vary depending on the type of element. * * TODO: Is it better to grab all the possible properties when creating an * element to avoid having to create the same element twice? */ getDefaultValueForProperty: function (nodeName, prop) { var nodeDefaults = defaultValueCache[nodeName]; var testElement; if (!nodeDefaults) { defaultValueCache[nodeName] = nodeDefaults = {}; } if (!(prop in nodeDefaults)) { testElement = document.createElement(nodeName); nodeDefaults[prop] = testElement[prop]; } return nodeDefaults[prop]; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule quoteAttributeValueForBrowser */ 'use strict'; var escapeTextContentForBrowser = __webpack_require__(27); /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Value to escape. * @return {string} An escaped string. */ function quoteAttributeValueForBrowser(value) { return '"' + escapeTextContentForBrowser(value) + '"'; } module.exports = quoteAttributeValueForBrowser; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule warning */ 'use strict'; var emptyFunction = __webpack_require__(21); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if (process.env.NODE_ENV !== 'production') { warning = function (condition, format) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} } }; } module.exports = warning; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentBrowserEnvironment */ 'use strict'; var ReactDOMIDOperations = __webpack_require__(33); var ReactMount = __webpack_require__(34); /** * Abstracts away all functionality of the reconciler that requires knowledge of * the browser context. TODO: These callers should be refactored to avoid the * need for this injection. */ var ReactComponentBrowserEnvironment = { processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates, replaceNodeWithMarkupByID: ReactDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID, /** * If a particular environment requires that some resources be cleaned up, * specify this in the injected Mixin. In the DOM, we would likely want to * purge any cached node ID lookups. * * @private */ unmountIDFromEnvironment: function (rootNodeID) { ReactMount.purgeID(rootNodeID); } }; module.exports = ReactComponentBrowserEnvironment; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMIDOperations * @typechecks static-only */ 'use strict'; var DOMChildrenOperations = __webpack_require__(13); var DOMPropertyOperations = __webpack_require__(28); var ReactMount = __webpack_require__(34); var ReactPerf = __webpack_require__(24); var invariant = __webpack_require__(19); /** * Errors for properties that should not be updated with `updatePropertyByID()`. * * @type {object} * @private */ var INVALID_PROPERTY_ERRORS = { dangerouslySetInnerHTML: '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.', style: '`style` must be set using `updateStylesByID()`.' }; /** * Operations used to process updates to DOM nodes. */ var ReactDOMIDOperations = { /** * Updates a DOM node with new property values. This should only be used to * update DOM properties in `DOMProperty`. * * @param {string} id ID of the node to update. * @param {string} name A valid property name, see `DOMProperty`. * @param {*} value New value of the property. * @internal */ updatePropertyByID: function (id, name, value) { var node = ReactMount.getNode(id); !!INVALID_PROPERTY_ERRORS.hasOwnProperty(name) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name]) : invariant(false) : undefined; // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertantly setting to a string. This // brings us in line with the same behavior we have on initial render. if (value != null) { DOMPropertyOperations.setValueForProperty(node, name, value); } else { DOMPropertyOperations.deleteValueForProperty(node, name); } }, /** * Replaces a DOM node that exists in the document with markup. * * @param {string} id ID of child to be replaced. * @param {string} markup Dangerous markup to inject in place of child. * @internal * @see {Danger.dangerouslyReplaceNodeWithMarkup} */ dangerouslyReplaceNodeWithMarkupByID: function (id, markup) { var node = ReactMount.getNode(id); DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup); }, /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @param {array<string>} markup List of markup strings. * @internal */ dangerouslyProcessChildrenUpdates: function (updates, markup) { for (var i = 0; i < updates.length; i++) { updates[i].parentNode = ReactMount.getNode(updates[i].parentID); } DOMChildrenOperations.processUpdates(updates, markup); } }; ReactPerf.measureMethods(ReactDOMIDOperations, 'ReactDOMIDOperations', { dangerouslyReplaceNodeWithMarkupByID: 'dangerouslyReplaceNodeWithMarkupByID', dangerouslyProcessChildrenUpdates: 'dangerouslyProcessChildrenUpdates' }); module.exports = ReactDOMIDOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMount */ 'use strict'; var DOMProperty = __webpack_require__(29); var ReactBrowserEventEmitter = __webpack_require__(35); var ReactCurrentOwner = __webpack_require__(11); var ReactDOMFeatureFlags = __webpack_require__(47); var ReactElement = __webpack_require__(48); var ReactEmptyComponentRegistry = __webpack_require__(50); var ReactInstanceHandles = __webpack_require__(51); var ReactInstanceMap = __webpack_require__(53); var ReactMarkupChecksum = __webpack_require__(54); var ReactPerf = __webpack_require__(24); var ReactReconciler = __webpack_require__(56); var ReactUpdateQueue = __webpack_require__(59); var ReactUpdates = __webpack_require__(60); var assign = __webpack_require__(45); var emptyObject = __webpack_require__(64); var containsNode = __webpack_require__(65); var instantiateReactComponent = __webpack_require__(68); var invariant = __webpack_require__(19); var setInnerHTML = __webpack_require__(25); var shouldUpdateReactComponent = __webpack_require__(73); var validateDOMNesting = __webpack_require__(76); var warning = __webpack_require__(31); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var nodeCache = {}; var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; var ownerDocumentContextKey = '__ReactMount_ownerDocument$' + Math.random().toString(36).slice(2); /** Mapping from reactRootID to React component instance. */ var instancesByReactRootID = {}; /** Mapping from reactRootID to `container` nodes. */ var containersByReactRootID = {}; if (process.env.NODE_ENV !== 'production') { /** __DEV__-only mapping from reactRootID to root elements. */ var rootElementsByReactRootID = {}; } // Used to store breadth-first search state in findComponentRoot. var findComponentRootReusableArray = []; /** * Finds the index of the first character * that's not common between the two given strings. * * @return {number} the index of the character where the strings diverge */ function firstDifferenceIndex(string1, string2) { var minLen = Math.min(string1.length, string2.length); for (var i = 0; i < minLen; i++) { if (string1.charAt(i) !== string2.charAt(i)) { return i; } } return string1.length === string2.length ? -1 : minLen; } /** * @param {DOMElement|DOMDocument} container DOM element that may contain * a React component * @return {?*} DOM element that may have the reactRoot ID, or null. */ function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOC_NODE_TYPE) { return container.documentElement; } else { return container.firstChild; } } /** * @param {DOMElement} container DOM element that may contain a React component. * @return {?string} A "reactRoot" ID, if a React component is rendered. */ function getReactRootID(container) { var rootElement = getReactRootElementInContainer(container); return rootElement && ReactMount.getID(rootElement); } /** * Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form * element can return its control whose name or ID equals ATTR_NAME. All * DOM nodes support `getAttributeNode` but this can also get called on * other objects so just return '' if we're given something other than a * DOM node (such as window). * * @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node. * @return {string} ID of the supplied `domNode`. */ function getID(node) { var id = internalGetID(node); if (id) { if (nodeCache.hasOwnProperty(id)) { var cached = nodeCache[id]; if (cached !== node) { !!isValid(cached, id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', ATTR_NAME, id) : invariant(false) : undefined; nodeCache[id] = node; } } else { nodeCache[id] = node; } } return id; } function internalGetID(node) { // If node is something like a window, document, or text node, none of // which support attributes or a .getAttribute method, gracefully return // the empty string, as if the attribute were missing. return node && node.getAttribute && node.getAttribute(ATTR_NAME) || ''; } /** * Sets the React-specific ID of the given node. * * @param {DOMElement} node The DOM node whose ID will be set. * @param {string} id The value of the ID attribute. */ function setID(node, id) { var oldID = internalGetID(node); if (oldID !== id) { delete nodeCache[oldID]; } node.setAttribute(ATTR_NAME, id); nodeCache[id] = node; } /** * Finds the node with the supplied React-generated DOM ID. * * @param {string} id A React-generated DOM ID. * @return {DOMElement} DOM node with the suppled `id`. * @internal */ function getNode(id) { if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { nodeCache[id] = ReactMount.findReactNodeByID(id); } return nodeCache[id]; } /** * Finds the node with the supplied public React instance. * * @param {*} instance A public React instance. * @return {?DOMElement} DOM node with the suppled `id`. * @internal */ function getNodeFromInstance(instance) { var id = ReactInstanceMap.get(instance)._rootNodeID; if (ReactEmptyComponentRegistry.isNullComponentID(id)) { return null; } if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { nodeCache[id] = ReactMount.findReactNodeByID(id); } return nodeCache[id]; } /** * A node is "valid" if it is contained by a currently mounted container. * * This means that the node does not have to be contained by a document in * order to be considered valid. * * @param {?DOMElement} node The candidate DOM node. * @param {string} id The expected ID of the node. * @return {boolean} Whether the node is contained by a mounted container. */ function isValid(node, id) { if (node) { !(internalGetID(node) === id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactMount: Unexpected modification of `%s`', ATTR_NAME) : invariant(false) : undefined; var container = ReactMount.findReactContainerForID(id); if (container && containsNode(container, node)) { return true; } } return false; } /** * Causes the cache to forget about one React-specific ID. * * @param {string} id The ID to forget. */ function purgeID(id) { delete nodeCache[id]; } var deepestNodeSoFar = null; function findDeepestCachedAncestorImpl(ancestorID) { var ancestor = nodeCache[ancestorID]; if (ancestor && isValid(ancestor, ancestorID)) { deepestNodeSoFar = ancestor; } else { // This node isn't populated in the cache, so presumably none of its // descendants are. Break out of the loop. return false; } } /** * Return the deepest cached node whose ID is a prefix of `targetID`. */ function findDeepestCachedAncestor(targetID) { deepestNodeSoFar = null; ReactInstanceHandles.traverseAncestors(targetID, findDeepestCachedAncestorImpl); var foundNode = deepestNodeSoFar; deepestNodeSoFar = null; return foundNode; } /** * Mounts this component and inserts it into the DOM. * * @param {ReactComponent} componentInstance The instance to mount. * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function mountComponentIntoNode(componentInstance, rootID, container, transaction, shouldReuseMarkup, context) { if (ReactDOMFeatureFlags.useCreateElement) { context = assign({}, context); if (container.nodeType === DOC_NODE_TYPE) { context[ownerDocumentContextKey] = container; } else { context[ownerDocumentContextKey] = container.ownerDocument; } } if (process.env.NODE_ENV !== 'production') { if (context === emptyObject) { context = {}; } var tag = container.nodeName.toLowerCase(); context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(null, tag, null); } var markup = ReactReconciler.mountComponent(componentInstance, rootID, transaction, context); componentInstance._renderedComponent._topLevelWrapper = componentInstance; ReactMount._mountImageIntoNode(markup, container, shouldReuseMarkup, transaction); } /** * Batched mount. * * @param {ReactComponent} componentInstance The instance to mount. * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function batchedMountComponentIntoNode(componentInstance, rootID, container, shouldReuseMarkup, context) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* forceHTML */shouldReuseMarkup); transaction.perform(mountComponentIntoNode, null, componentInstance, rootID, container, transaction, shouldReuseMarkup, context); ReactUpdates.ReactReconcileTransaction.release(transaction); } /** * Unmounts a component and removes it from the DOM. * * @param {ReactComponent} instance React component instance. * @param {DOMElement} container DOM element to unmount from. * @final * @internal * @see {ReactMount.unmountComponentAtNode} */ function unmountComponentFromNode(instance, container) { ReactReconciler.unmountComponent(instance); if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } } /** * True if the supplied DOM node has a direct React-rendered child that is * not a React root element. Useful for warning in `render`, * `unmountComponentAtNode`, etc. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM element contains a direct child that was * rendered by React but is not a root element. * @internal */ function hasNonRootReactChild(node) { var reactRootID = getReactRootID(node); return reactRootID ? reactRootID !== ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID) : false; } /** * Returns the first (deepest) ancestor of a node which is rendered by this copy * of React. */ function findFirstReactDOMImpl(node) { // This node might be from another React instance, so we make sure not to // examine the node cache here for (; node && node.parentNode !== node; node = node.parentNode) { if (node.nodeType !== 1) { // Not a DOMElement, therefore not a React component continue; } var nodeID = internalGetID(node); if (!nodeID) { continue; } var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); // If containersByReactRootID contains the container we find by crawling up // the tree, we know that this instance of React rendered the node. // nb. isValid's strategy (with containsNode) does not work because render // trees may be nested and we don't want a false positive in that case. var current = node; var lastID; do { lastID = internalGetID(current); current = current.parentNode; if (current == null) { // The passed-in node has been detached from the container it was // originally rendered into. return null; } } while (lastID !== reactRootID); if (current === containersByReactRootID[reactRootID]) { return node; } } return null; } /** * Temporary (?) hack so that we can store all top-level pending updates on * composites instead of having to worry about different types of components * here. */ var TopLevelWrapper = function () {}; TopLevelWrapper.prototype.isReactComponent = {}; if (process.env.NODE_ENV !== 'production') { TopLevelWrapper.displayName = 'TopLevelWrapper'; } TopLevelWrapper.prototype.render = function () { // this.props is actually a ReactElement return this.props; }; /** * Mounting is the process of initializing a React component by creating its * representative DOM elements and inserting them into a supplied `container`. * Any prior content inside `container` is destroyed in the process. * * ReactMount.render( * component, * document.getElementById('container') * ); * * <div id="container"> <-- Supplied `container`. * <div data-reactid=".3"> <-- Rendered reactRoot of React * // ... component. * </div> * </div> * * Inside of `container`, the first element rendered is the "reactRoot". */ var ReactMount = { TopLevelWrapper: TopLevelWrapper, /** Exposed for debugging purposes **/ _instancesByReactRootID: instancesByReactRootID, /** * This is a hook provided to support rendering React components while * ensuring that the apparent scroll position of its `container` does not * change. * * @param {DOMElement} container The `container` being rendered into. * @param {function} renderCallback This must be called once to do the render. */ scrollMonitor: function (container, renderCallback) { renderCallback(); }, /** * Take a component that's already mounted into the DOM and replace its props * @param {ReactComponent} prevComponent component instance already in the DOM * @param {ReactElement} nextElement component instance to render * @param {DOMElement} container container to render into * @param {?function} callback function triggered on completion */ _updateRootComponent: function (prevComponent, nextElement, container, callback) { ReactMount.scrollMonitor(container, function () { ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback); } }); if (process.env.NODE_ENV !== 'production') { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[getReactRootID(container)] = getReactRootElementInContainer(container); } return prevComponent; }, /** * Register a component into the instance map and starts scroll value * monitoring * @param {ReactComponent} nextComponent component instance to render * @param {DOMElement} container container to render into * @return {string} reactRoot ID prefix */ _registerComponent: function (nextComponent, container) { !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : invariant(false) : undefined; ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var reactRootID = ReactMount.registerContainer(container); instancesByReactRootID[reactRootID] = nextComponent; return reactRootID; }, /** * Render a new component into the DOM. * @param {ReactElement} nextElement element to render * @param {DOMElement} container container to render into * @param {boolean} shouldReuseMarkup if we should skip the markup insertion * @return {ReactComponent} nextComponent */ _renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined; var componentInstance = instantiateReactComponent(nextElement, null); var reactRootID = ReactMount._registerComponent(componentInstance, container); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, reactRootID, container, shouldReuseMarkup, context); if (process.env.NODE_ENV !== 'production') { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container); } return componentInstance; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactComponent} parentComponent The conceptual parent of this render tree. * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { !(parentComponent != null && parentComponent._reactInternalInstance != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : invariant(false) : undefined; return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback); }, _renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { !ReactElement.isValidElement(nextElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing an element string, make sure to instantiate ' + 'it by passing it to React.createElement.' : typeof nextElement === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : // Check if it quacks like an element nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : invariant(false) : undefined; process.env.NODE_ENV !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : undefined; var nextWrappedElement = new ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement); var prevComponent = instancesByReactRootID[getReactRootID(container)]; if (prevComponent) { var prevWrappedElement = prevComponent._currentElement; var prevElement = prevWrappedElement.props; if (shouldUpdateReactComponent(prevElement, nextElement)) { var publicInst = prevComponent._renderedComponent.getPublicInstance(); var updatedCallback = callback && function () { callback.call(publicInst); }; ReactMount._updateRootComponent(prevComponent, nextWrappedElement, container, updatedCallback); return publicInst; } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement); var containerHasNonRootReactChild = hasNonRootReactChild(container); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : undefined; if (!containerHasReactMarkup || reactRootElement.nextSibling) { var rootElementSibling = reactRootElement; while (rootElementSibling) { if (internalGetID(rootElementSibling)) { process.env.NODE_ENV !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : undefined; break; } rootElementSibling = rootElementSibling.nextSibling; } } } var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild; var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, parentComponent != null ? parentComponent._reactInternalInstance._processChildContext(parentComponent._reactInternalInstance._context) : emptyObject)._renderedComponent.getPublicInstance(); if (callback) { callback.call(component); } return component; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ render: function (nextElement, container, callback) { return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback); }, /** * Registers a container node into which React components will be rendered. * This also creates the "reactRoot" ID that will be assigned to the element * rendered within. * * @param {DOMElement} container DOM element to register as a container. * @return {string} The "reactRoot" ID of elements rendered within. */ registerContainer: function (container) { var reactRootID = getReactRootID(container); if (reactRootID) { // If one exists, make sure it is a valid "reactRoot" ID. reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID); } if (!reactRootID) { // No valid "reactRoot" ID found, create one. reactRootID = ReactInstanceHandles.createReactRootID(); } containersByReactRootID[reactRootID] = container; return reactRootID; }, /** * Unmounts and destroys the React component rendered in the `container`. * * @param {DOMElement} container DOM element containing a React component. * @return {boolean} True if a component was found in and unmounted from * `container` */ unmountComponentAtNode: function (container) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined; !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : invariant(false) : undefined; var reactRootID = getReactRootID(container); var component = instancesByReactRootID[reactRootID]; if (!component) { // Check if the node being unmounted was rendered by React, but isn't a // root node. var containerHasNonRootReactChild = hasNonRootReactChild(container); // Check if the container itself is a React root node. var containerID = internalGetID(container); var isContainerReactRoot = containerID && containerID === ReactInstanceHandles.getReactRootIDFromNodeID(containerID); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : undefined; } return false; } ReactUpdates.batchedUpdates(unmountComponentFromNode, component, container); delete instancesByReactRootID[reactRootID]; delete containersByReactRootID[reactRootID]; if (process.env.NODE_ENV !== 'production') { delete rootElementsByReactRootID[reactRootID]; } return true; }, /** * Finds the container DOM element that contains React component to which the * supplied DOM `id` belongs. * * @param {string} id The ID of an element rendered by a React component. * @return {?DOMElement} DOM element that contains the `id`. */ findReactContainerForID: function (id) { var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id); var container = containersByReactRootID[reactRootID]; if (process.env.NODE_ENV !== 'production') { var rootElement = rootElementsByReactRootID[reactRootID]; if (rootElement && rootElement.parentNode !== container) { process.env.NODE_ENV !== 'production' ? warning( // Call internalGetID here because getID calls isValid which calls // findReactContainerForID (this function). internalGetID(rootElement) === reactRootID, 'ReactMount: Root element ID differed from reactRootID.') : undefined; var containerChild = container.firstChild; if (containerChild && reactRootID === internalGetID(containerChild)) { // If the container has a new child with the same ID as the old // root element, then rootElementsByReactRootID[reactRootID] is // just stale and needs to be updated. The case that deserves a // warning is when the container is empty. rootElementsByReactRootID[reactRootID] = containerChild; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactMount: Root element has been removed from its original ' + 'container. New container: %s', rootElement.parentNode) : undefined; } } } return container; }, /** * Finds an element rendered by React with the supplied ID. * * @param {string} id ID of a DOM node in the React component. * @return {DOMElement} Root DOM node of the React component. */ findReactNodeByID: function (id) { var reactRoot = ReactMount.findReactContainerForID(id); return ReactMount.findComponentRoot(reactRoot, id); }, /** * Traverses up the ancestors of the supplied node to find a node that is a * DOM representation of a React component rendered by this copy of React. * * @param {*} node * @return {?DOMEventTarget} * @internal */ getFirstReactDOM: function (node) { return findFirstReactDOMImpl(node); }, /** * Finds a node with the supplied `targetID` inside of the supplied * `ancestorNode`. Exploits the ID naming scheme to perform the search * quickly. * * @param {DOMEventTarget} ancestorNode Search from this root. * @pararm {string} targetID ID of the DOM representation of the component. * @return {DOMEventTarget} DOM node with the supplied `targetID`. * @internal */ findComponentRoot: function (ancestorNode, targetID) { var firstChildren = findComponentRootReusableArray; var childIndex = 0; var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode; if (process.env.NODE_ENV !== 'production') { // This will throw on the next line; give an early warning process.env.NODE_ENV !== 'production' ? warning(deepestAncestor != null, 'React can\'t find the root component node for data-reactid value ' + '`%s`. If you\'re seeing this message, it probably means that ' + 'you\'ve loaded two copies of React on the page. At this time, only ' + 'a single copy of React can be loaded at a time.', targetID) : undefined; } firstChildren[0] = deepestAncestor.firstChild; firstChildren.length = 1; while (childIndex < firstChildren.length) { var child = firstChildren[childIndex++]; var targetChild; while (child) { var childID = ReactMount.getID(child); if (childID) { // Even if we find the node we're looking for, we finish looping // through its siblings to ensure they're cached so that we don't have // to revisit this node again. Otherwise, we make n^2 calls to getID // when visiting the many children of a single node in order. if (targetID === childID) { targetChild = child; } else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) { // If we find a child whose ID is an ancestor of the given ID, // then we can be sure that we only want to search the subtree // rooted at this child, so we can throw out the rest of the // search state. firstChildren.length = childIndex = 0; firstChildren.push(child.firstChild); } } else { // If this child had no ID, then there's a chance that it was // injected automatically by the browser, as when a `<table>` // element sprouts an extra `<tbody>` child as a side effect of // `.innerHTML` parsing. Optimistically continue down this // branch, but not before examining the other siblings. firstChildren.push(child.firstChild); } child = child.nextSibling; } if (targetChild) { // Emptying firstChildren/findComponentRootReusableArray is // not necessary for correctness, but it helps the GC reclaim // any nodes that were left at the end of the search. firstChildren.length = 0; return targetChild; } } firstChildren.length = 0; true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findComponentRoot(..., %s): Unable to find element. This probably ' + 'means the DOM was unexpectedly mutated (e.g., by the browser), ' + 'usually due to forgetting a <tbody> when using tables, nesting tags ' + 'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' + 'parent. ' + 'Try inspecting the child nodes of the element with React ID `%s`.', targetID, ReactMount.getID(ancestorNode)) : invariant(false) : undefined; }, _mountImageIntoNode: function (markup, container, shouldReuseMarkup, transaction) { !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : invariant(false) : undefined; if (shouldReuseMarkup) { var rootElement = getReactRootElementInContainer(container); if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) { return; } else { var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); var rootMarkup = rootElement.outerHTML; rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum); var normalizedMarkup = markup; if (process.env.NODE_ENV !== 'production') { // because rootMarkup is retrieved from the DOM, various normalizations // will have occurred which will not be present in `markup`. Here, // insert markup into a <div> or <iframe> depending on the container // type to perform the same normalizations before comparing. var normalizer; if (container.nodeType === ELEMENT_NODE_TYPE) { normalizer = document.createElement('div'); normalizer.innerHTML = markup; normalizedMarkup = normalizer.innerHTML; } else { normalizer = document.createElement('iframe'); document.body.appendChild(normalizer); normalizer.contentDocument.write(markup); normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML; document.body.removeChild(normalizer); } } var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup); var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20); !(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side:\n%s', difference) : invariant(false) : undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : undefined; } } } !(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined; if (transaction.useCreateElement) { while (container.lastChild) { container.removeChild(container.lastChild); } container.appendChild(markup); } else { setInnerHTML(container, markup); } }, ownerDocumentContextKey: ownerDocumentContextKey, /** * React ID utilities. */ getReactRootID: getReactRootID, getID: getID, setID: setID, getNode: getNode, getNodeFromInstance: getNodeFromInstance, isValid: isValid, purgeID: purgeID }; ReactPerf.measureMethods(ReactMount, 'ReactMount', { _renderNewRootComponent: '_renderNewRootComponent', _mountImageIntoNode: '_mountImageIntoNode' }); module.exports = ReactMount; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserEventEmitter * @typechecks static-only */ 'use strict'; var EventConstants = __webpack_require__(36); var EventPluginHub = __webpack_require__(37); var EventPluginRegistry = __webpack_require__(38); var ReactEventEmitterMixin = __webpack_require__(43); var ReactPerf = __webpack_require__(24); var ViewportMetrics = __webpack_require__(44); var assign = __webpack_require__(45); var isEventSupported = __webpack_require__(46); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topAbort: 'abort', topBlur: 'blur', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topScroll: 'scroll', topSeeked: 'seeked', topSeeking: 'seeking', topSelectionChange: 'selectionchange', topStalled: 'stalled', topSuspend: 'suspend', topTextInput: 'textInput', topTimeUpdate: 'timeupdate', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topVolumeChange: 'volumechange', topWaiting: 'waiting', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function (ReactEventListener) { ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function (enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function () { return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function (registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName]; var topLevelTypes = EventConstants.topLevelTypes; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { if (dependency === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt); } } else if (dependency === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE); } } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt); } // to make sure blur and focus event listeners are only attached once isListening[topLevelTypes.topBlur] = true; isListening[topLevelTypes.topFocus] = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt); } isListening[dependency] = true; } } }, trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle); }, trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle); }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function () { if (!isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } }, eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs, registrationNameModules: EventPluginHub.registrationNameModules, putListener: EventPluginHub.putListener, getListener: EventPluginHub.getListener, deleteListener: EventPluginHub.deleteListener, deleteAllListeners: EventPluginHub.deleteAllListeners }); ReactPerf.measureMethods(ReactBrowserEventEmitter, 'ReactBrowserEventEmitter', { putListener: 'putListener', deleteListener: 'deleteListener' }); module.exports = ReactBrowserEventEmitter; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventConstants */ 'use strict'; var keyMirror = __webpack_require__(23); var PropagationPhases = keyMirror({ bubbled: null, captured: null }); /** * Types of raw signals from the browser caught at the top level. */ var topLevelTypes = keyMirror({ topAbort: null, topBlur: null, topCanPlay: null, topCanPlayThrough: null, topChange: null, topClick: null, topCompositionEnd: null, topCompositionStart: null, topCompositionUpdate: null, topContextMenu: null, topCopy: null, topCut: null, topDoubleClick: null, topDrag: null, topDragEnd: null, topDragEnter: null, topDragExit: null, topDragLeave: null, topDragOver: null, topDragStart: null, topDrop: null, topDurationChange: null, topEmptied: null, topEncrypted: null, topEnded: null, topError: null, topFocus: null, topInput: null, topKeyDown: null, topKeyPress: null, topKeyUp: null, topLoad: null, topLoadedData: null, topLoadedMetadata: null, topLoadStart: null, topMouseDown: null, topMouseMove: null, topMouseOut: null, topMouseOver: null, topMouseUp: null, topPaste: null, topPause: null, topPlay: null, topPlaying: null, topProgress: null, topRateChange: null, topReset: null, topScroll: null, topSeeked: null, topSeeking: null, topSelectionChange: null, topStalled: null, topSubmit: null, topSuspend: null, topTextInput: null, topTimeUpdate: null, topTouchCancel: null, topTouchEnd: null, topTouchMove: null, topTouchStart: null, topVolumeChange: null, topWaiting: null, topWheel: null }); var EventConstants = { topLevelTypes: topLevelTypes, PropagationPhases: PropagationPhases }; module.exports = EventConstants; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginHub */ 'use strict'; var EventPluginRegistry = __webpack_require__(38); var EventPluginUtils = __webpack_require__(39); var ReactErrorUtils = __webpack_require__(40); var accumulateInto = __webpack_require__(41); var forEachAccumulated = __webpack_require__(42); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); /** * Internal store for event listeners */ var listenerBank = {}; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @param {boolean} simulated If the event is simulated (changes exn behavior) * @private */ var executeDispatchesAndRelease = function (event, simulated) { if (event) { EventPluginUtils.executeDispatchesInOrder(event, simulated); if (!event.isPersistent()) { event.constructor.release(event); } } }; var executeDispatchesAndReleaseSimulated = function (e) { return executeDispatchesAndRelease(e, true); }; var executeDispatchesAndReleaseTopLevel = function (e) { return executeDispatchesAndRelease(e, false); }; /** * - `InstanceHandle`: [required] Module that performs logical traversals of DOM * hierarchy given ids of the logical DOM elements involved. */ var InstanceHandle = null; function validateInstanceHandle() { var valid = InstanceHandle && InstanceHandle.traverseTwoPhase && InstanceHandle.traverseEnterLeave; process.env.NODE_ENV !== 'production' ? warning(valid, 'InstanceHandle not injected before use!') : undefined; } /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {object} InjectedMount * @public */ injectMount: EventPluginUtils.injection.injectMount, /** * @param {object} InjectedInstanceHandle * @public */ injectInstanceHandle: function (InjectedInstanceHandle) { InstanceHandle = InjectedInstanceHandle; if (process.env.NODE_ENV !== 'production') { validateInstanceHandle(); } }, getInstanceHandle: function () { if (process.env.NODE_ENV !== 'production') { validateInstanceHandle(); } return InstanceHandle; }, /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs, registrationNameModules: EventPluginRegistry.registrationNameModules, /** * Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {?function} listener The callback to store. */ putListener: function (id, registrationName, listener) { !(typeof listener === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : invariant(false) : undefined; var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[id] = listener; var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.didPutListener) { PluginModule.didPutListener(id, registrationName, listener); } }, /** * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function (id, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; return bankForRegistrationName && bankForRegistrationName[id]; }, /** * Deletes a listener from the registration bank. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function (id, registrationName) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(id, registrationName); } var bankForRegistrationName = listenerBank[registrationName]; // TODO: This should never be null -- when is it? if (bankForRegistrationName) { delete bankForRegistrationName[id]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {string} id ID of the DOM element. */ deleteAllListeners: function (id) { for (var registrationName in listenerBank) { if (!listenerBank[registrationName][id]) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(id, registrationName); } delete listenerBank[registrationName][id]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget); if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function (events) { if (events) { eventQueue = accumulateInto(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function (simulated) { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; if (simulated) { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); } else { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); } !!eventQueue ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.') : invariant(false) : undefined; // This would be a good time to rethrow if any of the event handlers threw. ReactErrorUtils.rethrowCaughtError(); }, /** * These are needed for tests only. Do not use! */ __purge: function () { listenerBank = {}; }, __getListenerBank: function () { return listenerBank; } }; module.exports = EventPluginHub; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginRegistry * @typechecks static-only */ 'use strict'; var invariant = __webpack_require__(19); /** * Injectable ordering of event plugins. */ var EventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!EventPluginOrder) { // Wait until an `EventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var PluginModule = namesToPlugins[pluginName]; var pluginIndex = EventPluginOrder.indexOf(pluginName); !(pluginIndex > -1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName) : invariant(false) : undefined; if (EventPluginRegistry.plugins[pluginIndex]) { continue; } !PluginModule.extractEvents ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName) : invariant(false) : undefined; EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) { !publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : invariant(false) : undefined; } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName) : invariant(false) : undefined; EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName(phasedRegistrationName, PluginModule, eventName); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, PluginModule, eventName) { !!EventPluginRegistry.registrationNameModules[registrationName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName) : invariant(false) : undefined; EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies; } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function (InjectedEventPluginOrder) { !!EventPluginOrder ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.') : invariant(false) : undefined; // Clone the ordering so it cannot be dynamically mutated. EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function (injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var PluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) { !!namesToPlugins[pluginName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName) : invariant(false) : undefined; namesToPlugins[pluginName] = PluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function (event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null; } for (var phase in dispatchConfig.phasedRegistrationNames) { if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]]; if (PluginModule) { return PluginModule; } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function () { EventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } } }; module.exports = EventPluginRegistry; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginUtils */ 'use strict'; var EventConstants = __webpack_require__(36); var ReactErrorUtils = __webpack_require__(40); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); /** * Injected dependencies: */ /** * - `Mount`: [required] Module that can convert between React dom IDs and * actual node references. */ var injection = { Mount: null, injectMount: function (InjectedMount) { injection.Mount = InjectedMount; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(InjectedMount && InjectedMount.getNode && InjectedMount.getID, 'EventPluginUtils.injection.injectMount(...): Injected Mount ' + 'module is missing getNode or getID.') : undefined; } } }; var topLevelTypes = EventConstants.topLevelTypes; function isEndish(topLevelType) { return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel; } function isMoveish(topLevelType) { return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove; } function isStartish(topLevelType) { return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart; } var validateEventDispatches; if (process.env.NODE_ENV !== 'production') { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; var listenersIsArr = Array.isArray(dispatchListeners); var idsIsArr = Array.isArray(dispatchIDs); var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0; var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; process.env.NODE_ENV !== 'production' ? warning(idsIsArr === listenersIsArr && IDsLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : undefined; }; } /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {boolean} simulated If the event is simulated (changes exn behavior) * @param {function} listener Application-level callback * @param {string} domID DOM id to pass to the callback. */ function executeDispatch(event, simulated, listener, domID) { var type = event.type || 'unknown-event'; event.currentTarget = injection.Mount.getNode(domID); if (simulated) { ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event, domID); } else { ReactErrorUtils.invokeGuardedCallback(type, listener, event, domID); } event.currentTarget = null; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, simulated) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. executeDispatch(event, simulated, dispatchListeners[i], dispatchIDs[i]); } } else if (dispatchListeners) { executeDispatch(event, simulated, dispatchListeners, dispatchIDs); } event._dispatchListeners = null; event._dispatchIDs = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchIDs[i])) { return dispatchIDs[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchIDs)) { return dispatchIDs; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchIDs = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return {*} The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchID = event._dispatchIDs; !!Array.isArray(dispatchListener) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : invariant(false) : undefined; var res = dispatchListener ? dispatchListener(event, dispatchID) : null; event._dispatchListeners = null; event._dispatchIDs = null; return res; } /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, getNode: function (id) { return injection.Mount.getNode(id); }, getID: function (node) { return injection.Mount.getID(node); }, injection: injection }; module.exports = EventPluginUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactErrorUtils * @typechecks */ 'use strict'; var caughtError = null; /** * Call a function while guarding against errors that happens within it. * * @param {?String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} a First argument * @param {*} b Second argument */ function invokeGuardedCallback(name, func, a, b) { try { return func(a, b); } catch (x) { if (caughtError === null) { caughtError = x; } return undefined; } } var ReactErrorUtils = { invokeGuardedCallback: invokeGuardedCallback, /** * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event * handler are sure to be rethrown by rethrowCaughtError. */ invokeGuardedCallbackWithCatch: invokeGuardedCallback, /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ rethrowCaughtError: function () { if (caughtError) { var error = caughtError; caughtError = null; throw error; } } }; if (process.env.NODE_ENV !== 'production') { /** * To help development we can get better devtools integration by simulating a * real browser event. */ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { var fakeNode = document.createElement('react'); ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) { var boundFunc = func.bind(null, a, b); var evtType = 'react-' + name; fakeNode.addEventListener(evtType, boundFunc, false); var evt = document.createEvent('Event'); evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); fakeNode.removeEventListener(evtType, boundFunc, false); }; } } module.exports = ReactErrorUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule accumulateInto */ 'use strict'; var invariant = __webpack_require__(19); /** * * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { !(next != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : invariant(false) : undefined; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). var currentIsArray = Array.isArray(current); var nextIsArray = Array.isArray(next); if (currentIsArray && nextIsArray) { current.push.apply(current, next); return current; } if (currentIsArray) { current.push(next); return current; } if (nextIsArray) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } module.exports = accumulateInto; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 42 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule forEachAccumulated */ 'use strict'; /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ var forEachAccumulated = function (arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } }; module.exports = forEachAccumulated; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventEmitterMixin */ 'use strict'; var EventPluginHub = __webpack_require__(37); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(false); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native environment event. */ handleTopLevel: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var events = EventPluginHub.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; /***/ }, /* 44 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ViewportMetrics */ 'use strict'; var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function (scrollPosition) { ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; /***/ }, /* 45 */ /***/ function(module, exports) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign 'use strict'; function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; } module.exports = assign; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isEventSupported */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = (eventName in document); if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; /***/ }, /* 47 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMFeatureFlags */ 'use strict'; var ReactDOMFeatureFlags = { useCreateElement: false }; module.exports = ReactDOMFeatureFlags; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElement */ 'use strict'; var ReactCurrentOwner = __webpack_require__(11); var assign = __webpack_require__(45); var canDefineProperty = __webpack_require__(49); // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {*} key * @param {string|object} ref * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @param {*} owner * @param {*} props * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allow us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; if (process.env.NODE_ENV !== 'production') { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. if (canDefineProperty) { Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); } else { element._store.validated = false; element._self = self; element._source = source; } Object.freeze(element.props); Object.freeze(element); } return element; }; ReactElement.createElement = function (type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; key = config.key === undefined ? null : '' + config.key; self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); }; ReactElement.createFactory = function (type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. `<Foo />.type === Foo`. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceKey = function (oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; }; ReactElement.cloneAndReplaceProps = function (oldElement, newProps) { var newElement = ReactElement(oldElement.type, oldElement.key, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, newProps); if (process.env.NODE_ENV !== 'production') { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; ReactElement.cloneElement = function (element, config, children) { var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (config.ref !== undefined) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (config.key !== undefined) { key = '' + config.key; } // Remaining properties override existing props for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function (object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; module.exports = ReactElement; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule canDefineProperty */ 'use strict'; var canDefineProperty = false; if (process.env.NODE_ENV !== 'production') { try { Object.defineProperty({}, 'x', { get: function () {} }); canDefineProperty = true; } catch (x) { // IE will fail on defineProperty } } module.exports = canDefineProperty; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 50 */ /***/ function(module, exports) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEmptyComponentRegistry */ 'use strict'; // This registry keeps track of the React IDs of the components that rendered to // `null` (in reality a placeholder such as `noscript`) var nullComponentIDsRegistry = {}; /** * @param {string} id Component's `_rootNodeID`. * @return {boolean} True if the component is rendered to null. */ function isNullComponentID(id) { return !!nullComponentIDsRegistry[id]; } /** * Mark the component as having rendered to null. * @param {string} id Component's `_rootNodeID`. */ function registerNullComponentID(id) { nullComponentIDsRegistry[id] = true; } /** * Unmark the component as having rendered to null: it renders to something now. * @param {string} id Component's `_rootNodeID`. */ function deregisterNullComponentID(id) { delete nullComponentIDsRegistry[id]; } var ReactEmptyComponentRegistry = { isNullComponentID: isNullComponentID, registerNullComponentID: registerNullComponentID, deregisterNullComponentID: deregisterNullComponentID }; module.exports = ReactEmptyComponentRegistry; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstanceHandles * @typechecks static-only */ 'use strict'; var ReactRootIndex = __webpack_require__(52); var invariant = __webpack_require__(19); var SEPARATOR = '.'; var SEPARATOR_LENGTH = SEPARATOR.length; /** * Maximum depth of traversals before we consider the possibility of a bad ID. */ var MAX_TREE_DEPTH = 10000; /** * Creates a DOM ID prefix to use when mounting React components. * * @param {number} index A unique integer * @return {string} React root ID. * @internal */ function getReactRootIDString(index) { return SEPARATOR + index.toString(36); } /** * Checks if a character in the supplied ID is a separator or the end. * * @param {string} id A React DOM ID. * @param {number} index Index of the character to check. * @return {boolean} True if the character is a separator or end of the ID. * @private */ function isBoundary(id, index) { return id.charAt(index) === SEPARATOR || index === id.length; } /** * Checks if the supplied string is a valid React DOM ID. * * @param {string} id A React DOM ID, maybe. * @return {boolean} True if the string is a valid React DOM ID. * @private */ function isValidID(id) { return id === '' || id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR; } /** * Checks if the first ID is an ancestor of or equal to the second ID. * * @param {string} ancestorID * @param {string} descendantID * @return {boolean} True if `ancestorID` is an ancestor of `descendantID`. * @internal */ function isAncestorIDOf(ancestorID, descendantID) { return descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length); } /** * Gets the parent ID of the supplied React DOM ID, `id`. * * @param {string} id ID of a component. * @return {string} ID of the parent, or an empty string. * @private */ function getParentID(id) { return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : ''; } /** * Gets the next DOM ID on the tree path from the supplied `ancestorID` to the * supplied `destinationID`. If they are equal, the ID is returned. * * @param {string} ancestorID ID of an ancestor node of `destinationID`. * @param {string} destinationID ID of the destination node. * @return {string} Next ID on the path from `ancestorID` to `destinationID`. * @private */ function getNextDescendantID(ancestorID, destinationID) { !(isValidID(ancestorID) && isValidID(destinationID)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID) : invariant(false) : undefined; !isAncestorIDOf(ancestorID, destinationID) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID) : invariant(false) : undefined; if (ancestorID === destinationID) { return ancestorID; } // Skip over the ancestor and the immediate separator. Traverse until we hit // another separator or we reach the end of `destinationID`. var start = ancestorID.length + SEPARATOR_LENGTH; var i; for (i = start; i < destinationID.length; i++) { if (isBoundary(destinationID, i)) { break; } } return destinationID.substr(0, i); } /** * Gets the nearest common ancestor ID of two IDs. * * Using this ID scheme, the nearest common ancestor ID is the longest common * prefix of the two IDs that immediately preceded a "marker" in both strings. * * @param {string} oneID * @param {string} twoID * @return {string} Nearest common ancestor ID, or the empty string if none. * @private */ function getFirstCommonAncestorID(oneID, twoID) { var minLength = Math.min(oneID.length, twoID.length); if (minLength === 0) { return ''; } var lastCommonMarkerIndex = 0; // Use `<=` to traverse until the "EOL" of the shorter string. for (var i = 0; i <= minLength; i++) { if (isBoundary(oneID, i) && isBoundary(twoID, i)) { lastCommonMarkerIndex = i; } else if (oneID.charAt(i) !== twoID.charAt(i)) { break; } } var longestCommonID = oneID.substr(0, lastCommonMarkerIndex); !isValidID(longestCommonID) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID) : invariant(false) : undefined; return longestCommonID; } /** * Traverses the parent path between two IDs (either up or down). The IDs must * not be the same, and there must exist a parent path between them. If the * callback returns `false`, traversal is stopped. * * @param {?string} start ID at which to start traversal. * @param {?string} stop ID at which to end traversal. * @param {function} cb Callback to invoke each ID with. * @param {*} arg Argument to invoke the callback with. * @param {?boolean} skipFirst Whether or not to skip the first node. * @param {?boolean} skipLast Whether or not to skip the last node. * @private */ function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) { start = start || ''; stop = stop || ''; !(start !== stop) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start) : invariant(false) : undefined; var traverseUp = isAncestorIDOf(stop, start); !(traverseUp || isAncestorIDOf(start, stop)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop) : invariant(false) : undefined; // Traverse from `start` to `stop` one depth at a time. var depth = 0; var traverse = traverseUp ? getParentID : getNextDescendantID; for (var id = start;; /* until break */id = traverse(id, stop)) { var ret; if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) { ret = cb(id, traverseUp, arg); } if (ret === false || id === stop) { // Only break //after// visiting `stop`. break; } !(depth++ < MAX_TREE_DEPTH) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop, id) : invariant(false) : undefined; } } /** * Manages the IDs assigned to DOM representations of React components. This * uses a specific scheme in order to traverse the DOM efficiently (e.g. in * order to simulate events). * * @internal */ var ReactInstanceHandles = { /** * Constructs a React root ID * @return {string} A React root ID. */ createReactRootID: function () { return getReactRootIDString(ReactRootIndex.createReactRootIndex()); }, /** * Constructs a React ID by joining a root ID with a name. * * @param {string} rootID Root ID of a parent component. * @param {string} name A component's name (as flattened children). * @return {string} A React ID. * @internal */ createReactID: function (rootID, name) { return rootID + name; }, /** * Gets the DOM ID of the React component that is the root of the tree that * contains the React component with the supplied DOM ID. * * @param {string} id DOM ID of a React component. * @return {?string} DOM ID of the React component that is the root. * @internal */ getReactRootIDFromNodeID: function (id) { if (id && id.charAt(0) === SEPARATOR && id.length > 1) { var index = id.indexOf(SEPARATOR, 1); return index > -1 ? id.substr(0, index) : id; } return null; }, /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * NOTE: Does not invoke the callback on the nearest common ancestor because * nothing "entered" or "left" that element. * * @param {string} leaveID ID being left. * @param {string} enterID ID being entered. * @param {function} cb Callback to invoke on each entered/left ID. * @param {*} upArg Argument to invoke the callback with on left IDs. * @param {*} downArg Argument to invoke the callback with on entered IDs. * @internal */ traverseEnterLeave: function (leaveID, enterID, cb, upArg, downArg) { var ancestorID = getFirstCommonAncestorID(leaveID, enterID); if (ancestorID !== leaveID) { traverseParentPath(leaveID, ancestorID, cb, upArg, false, true); } if (ancestorID !== enterID) { traverseParentPath(ancestorID, enterID, cb, downArg, true, false); } }, /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseTwoPhase: function (targetID, cb, arg) { if (targetID) { traverseParentPath('', targetID, cb, arg, true, false); traverseParentPath(targetID, '', cb, arg, false, true); } }, /** * Same as `traverseTwoPhase` but skips the `targetID`. */ traverseTwoPhaseSkipTarget: function (targetID, cb, arg) { if (targetID) { traverseParentPath('', targetID, cb, arg, true, true); traverseParentPath(targetID, '', cb, arg, true, true); } }, /** * Traverse a node ID, calling the supplied `cb` for each ancestor ID. For * example, passing `.0.$row-0.1` would result in `cb` getting called * with `.0`, `.0.$row-0`, and `.0.$row-0.1`. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseAncestors: function (targetID, cb, arg) { traverseParentPath('', targetID, cb, arg, true, false); }, getFirstCommonAncestorID: getFirstCommonAncestorID, /** * Exposed for unit testing. * @private */ _getNextDescendantID: getNextDescendantID, isAncestorIDOf: isAncestorIDOf, SEPARATOR: SEPARATOR }; module.exports = ReactInstanceHandles; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 52 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRootIndex * @typechecks */ 'use strict'; var ReactRootIndexInjection = { /** * @param {function} _createReactRootIndex */ injectCreateReactRootIndex: function (_createReactRootIndex) { ReactRootIndex.createReactRootIndex = _createReactRootIndex; } }; var ReactRootIndex = { createReactRootIndex: null, injection: ReactRootIndexInjection }; module.exports = ReactRootIndex; /***/ }, /* 53 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstanceMap */ 'use strict'; /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. */ // TODO: Replace this with ES6: var ReactInstanceMap = new Map(); var ReactInstanceMap = { /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ remove: function (key) { key._reactInternalInstance = undefined; }, get: function (key) { return key._reactInternalInstance; }, has: function (key) { return key._reactInternalInstance !== undefined; }, set: function (key, value) { key._reactInternalInstance = value; } }; module.exports = ReactInstanceMap; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMarkupChecksum */ 'use strict'; var adler32 = __webpack_require__(55); var TAG_END = /\/?>/; var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function (markup) { var checksum = adler32(markup); // Add checksum (handle both parent tags and self-closing tags) return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'); }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function (markup, element) { var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; /***/ }, /* 55 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule adler32 */ 'use strict'; var MOD = 65521; // adler32 is not cryptographically strong, and is only used to sanity check that // markup generated on the server matches the markup generated on the client. // This implementation (a modified version of the SheetJS version) has been optimized // for our use case, at the expense of conforming to the adler32 specification // for non-ascii inputs. function adler32(data) { var a = 1; var b = 0; var i = 0; var l = data.length; var m = l & ~0x3; while (i < m) { for (; i < Math.min(i + 4096, m); i += 4) { b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3)); } a %= MOD; b %= MOD; } for (; i < l; i++) { b += a += data.charCodeAt(i); } a %= MOD; b %= MOD; return a | b << 16; } module.exports = adler32; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconciler */ 'use strict'; var ReactRef = __webpack_require__(57); /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs() { ReactRef.attachRefs(this, this._currentElement); } var ReactReconciler = { /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactComponent} internalInstance * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (internalInstance, rootID, transaction, context) { var markup = internalInstance.mountComponent(rootID, transaction, context); if (internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } return markup; }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (internalInstance) { ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(); }, /** * Update a component using a new element. * * @param {ReactComponent} internalInstance * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal */ receiveComponent: function (internalInstance, nextElement, transaction, context) { var prevElement = internalInstance._currentElement; if (nextElement === prevElement && context === internalInstance._context) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for an element created outside a composite to be // deeply mutated and reused. // TODO: Bailing out early is just a perf optimization right? // TODO: Removing the return statement should affect correctness? return; } var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement); if (refsChanged) { ReactRef.detachRefs(internalInstance, prevElement); } internalInstance.receiveComponent(nextElement, transaction, context); if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (internalInstance, transaction) { internalInstance.performUpdateIfNecessary(transaction); } }; module.exports = ReactReconciler; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRef */ 'use strict'; var ReactOwner = __webpack_require__(58); var ReactRef = {}; function attachRef(ref, component, owner) { if (typeof ref === 'function') { ref(component.getPublicInstance()); } else { // Legacy ref ReactOwner.addComponentAsRefTo(component, ref, owner); } } function detachRef(ref, component, owner) { if (typeof ref === 'function') { ref(null); } else { // Legacy ref ReactOwner.removeComponentAsRefFrom(component, ref, owner); } } ReactRef.attachRefs = function (instance, element) { if (element === null || element === false) { return; } var ref = element.ref; if (ref != null) { attachRef(ref, instance, element._owner); } }; ReactRef.shouldUpdateRefs = function (prevElement, nextElement) { // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; return( // This has a few false positives w/r/t empty components. prevEmpty || nextEmpty || nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref ); }; ReactRef.detachRefs = function (instance, element) { if (element === null || element === false) { return; } var ref = element.ref; if (ref != null) { detachRef(ref, instance, element._owner); } }; module.exports = ReactRef; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactOwner */ 'use strict'; var invariant = __webpack_require__(19); /** * ReactOwners are capable of storing references to owned components. * * All components are capable of //being// referenced by owner components, but * only ReactOwner components are capable of //referencing// owned components. * The named reference is known as a "ref". * * Refs are available when mounted and updated during reconciliation. * * var MyComponent = React.createClass({ * render: function() { * return ( * <div onClick={this.handleClick}> * <CustomComponent ref="custom" /> * </div> * ); * }, * handleClick: function() { * this.refs.custom.handleClick(); * }, * componentDidMount: function() { * this.refs.custom.initialize(); * } * }); * * Refs should rarely be used. When refs are used, they should only be done to * control data that is not handled by React's data flow. * * @class ReactOwner */ var ReactOwner = { /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ isValidOwner: function (object) { return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function'); }, /** * Adds a component by ref to an owner component. * * @param {ReactComponent} component Component to reference. * @param {string} ref Name by which to refer to the component. * @param {ReactOwner} owner Component on which to record the ref. * @final * @internal */ addComponentAsRefTo: function (component, ref, owner) { !ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might ' + 'be adding a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined; owner.attachRef(ref, component); }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function (component, ref, owner) { !ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might ' + 'be removing a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined; // Check that `component` is still the current ref because we do not want to // detach the ref if another component stole it. if (owner.getPublicInstance().refs[ref] === component.getPublicInstance()) { owner.detachRef(ref); } } }; module.exports = ReactOwner; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdateQueue */ 'use strict'; var ReactCurrentOwner = __webpack_require__(11); var ReactElement = __webpack_require__(48); var ReactInstanceMap = __webpack_require__(53); var ReactUpdates = __webpack_require__(60); var assign = __webpack_require__(45); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); function enqueueUpdate(internalInstance) { ReactUpdates.enqueueUpdate(internalInstance); } function getInternalInstanceReadyForUpdate(publicInstance, callerName) { var internalInstance = ReactInstanceMap.get(publicInstance); if (!internalInstance) { if (process.env.NODE_ENV !== 'production') { // Only warn when we have a callerName. Otherwise we should be silent. // We're probably calling from enqueueCallback. We don't want to warn // there because we already warned for the corresponding lifecycle method. process.env.NODE_ENV !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor.displayName) : undefined; } return null; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition ' + '(such as within `render`). Render methods should be a pure function ' + 'of props and state.', callerName) : undefined; } return internalInstance; } /** * ReactUpdateQueue allows for state updates to be scheduled into a later * reconciliation step. */ var ReactUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined; owner._warnedAboutRefsInRender = true; } } var internalInstance = ReactInstanceMap.get(publicInstance); if (internalInstance) { // During componentWillMount and render this will still be null but after // that will always render to something. At least for now. So we can use // this hack. return !!internalInstance._renderedComponent; } else { return false; } }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function (publicInstance, callback) { !(typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined; var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); // Previously we would throw an error if we didn't have an internal // instance. Since we want to make it a no-op instead, we mirror the same // behavior we have in other enqueue* methods. // We also need to ignore callbacks in componentWillMount. See // enqueueUpdates. if (!internalInstance) { return null; } if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } // TODO: The callback here is ignored when setState is called from // componentWillMount. Either fix it or disallow doing so completely in // favor of getInitialState. Alternatively, we can disallow // componentWillMount during server-side rendering. enqueueUpdate(internalInstance); }, enqueueCallbackInternal: function (internalInstance, callback) { !(typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined; if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } enqueueUpdate(internalInstance); }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate'); if (!internalInstance) { return; } internalInstance._pendingForceUpdate = true; enqueueUpdate(internalInstance); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; enqueueUpdate(internalInstance); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState'); if (!internalInstance) { return; } var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); queue.push(partialState); enqueueUpdate(internalInstance); }, /** * Sets a subset of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialProps Subset of the next props. * @internal */ enqueueSetProps: function (publicInstance, partialProps) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setProps'); if (!internalInstance) { return; } ReactUpdateQueue.enqueueSetPropsInternal(internalInstance, partialProps); }, enqueueSetPropsInternal: function (internalInstance, partialProps) { var topLevelWrapper = internalInstance._topLevelWrapper; !topLevelWrapper ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setProps(...): You called `setProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined; // Merge with the pending element if it exists, otherwise with existing // element props. var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement; var element = wrapElement.props; var props = assign({}, element.props, partialProps); topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props)); enqueueUpdate(topLevelWrapper); }, /** * Replaces all of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} props New props. * @internal */ enqueueReplaceProps: function (publicInstance, props) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceProps'); if (!internalInstance) { return; } ReactUpdateQueue.enqueueReplacePropsInternal(internalInstance, props); }, enqueueReplacePropsInternal: function (internalInstance, props) { var topLevelWrapper = internalInstance._topLevelWrapper; !topLevelWrapper ? process.env.NODE_ENV !== 'production' ? invariant(false, 'replaceProps(...): You called `replaceProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined; // Merge with the pending element if it exists, otherwise with existing // element props. var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement; var element = wrapElement.props; topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props)); enqueueUpdate(topLevelWrapper); }, enqueueElementInternal: function (internalInstance, newElement) { internalInstance._pendingElement = newElement; enqueueUpdate(internalInstance); } }; module.exports = ReactUpdateQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdates */ 'use strict'; var CallbackQueue = __webpack_require__(61); var PooledClass = __webpack_require__(62); var ReactPerf = __webpack_require__(24); var ReactReconciler = __webpack_require__(56); var Transaction = __webpack_require__(63); var assign = __webpack_require__(45); var invariant = __webpack_require__(19); var dirtyComponents = []; var asapCallbackQueue = CallbackQueue.getPooled(); var asapEnqueued = false; var batchingStrategy = null; function ensureInjected() { !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy') : invariant(false) : undefined; } var NESTED_UPDATES = { initialize: function () { this.dirtyComponentsLength = dirtyComponents.length; }, close: function () { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var UPDATE_QUEUEING = { initialize: function () { this.callbackQueue.reset(); }, close: function () { this.callbackQueue.notifyAll(); } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.callbackQueue = CallbackQueue.getPooled(); this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* forceHTML */false); } assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, destructor: function () { this.dirtyComponentsLength = null; CallbackQueue.release(this.callbackQueue); this.callbackQueue = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function (method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b, c, d, e) { ensureInjected(); batchingStrategy.batchedUpdates(callback, a, b, c, d, e); } /** * Array comparator for ReactComponents by mount ordering. * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; !(len === dirtyComponents.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length) : invariant(false) : undefined; // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator); for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i]; // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction); if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance()); } } } } var flushBatchedUpdates = function () { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. while (dirtyComponents.length || asapEnqueued) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = false; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(); queue.notifyAll(); CallbackQueue.release(queue); } } }; flushBatchedUpdates = ReactPerf.measure('ReactUpdates', 'flushBatchedUpdates', flushBatchedUpdates); /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setProps, setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component); return; } dirtyComponents.push(component); } /** * Enqueue a callback to be run at the end of the current batching cycle. Throws * if no updates are currently being performed. */ function asap(callback, context) { !batchingStrategy.isBatchingUpdates ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.') : invariant(false) : undefined; asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; } var ReactUpdatesInjection = { injectReconcileTransaction: function (ReconcileTransaction) { !ReconcileTransaction ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : invariant(false) : undefined; ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function (_batchingStrategy) { !_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : invariant(false) : undefined; !(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : invariant(false) : undefined; !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : invariant(false) : undefined; batchingStrategy = _batchingStrategy; } }; var ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection, asap: asap }; module.exports = ReactUpdates; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CallbackQueue */ 'use strict'; var PooledClass = __webpack_require__(62); var assign = __webpack_require__(45); var invariant = __webpack_require__(19); /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `CallbackQueue.getPooled()`. * * @class ReactMountReady * @implements PooledClass * @internal */ function CallbackQueue() { this._callbacks = null; this._contexts = null; } assign(CallbackQueue.prototype, { /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ enqueue: function (callback, context) { this._callbacks = this._callbacks || []; this._contexts = this._contexts || []; this._callbacks.push(callback); this._contexts.push(context); }, /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ notifyAll: function () { var callbacks = this._callbacks; var contexts = this._contexts; if (callbacks) { !(callbacks.length === contexts.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : invariant(false) : undefined; this._callbacks = null; this._contexts = null; for (var i = 0; i < callbacks.length; i++) { callbacks[i].call(contexts[i]); } callbacks.length = 0; contexts.length = 0; } }, /** * Resets the internal queue. * * @internal */ reset: function () { this._callbacks = null; this._contexts = null; }, /** * `PooledClass` looks for this. */ destructor: function () { this.reset(); } }); PooledClass.addPoolingTo(CallbackQueue); module.exports = CallbackQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule PooledClass */ 'use strict'; var invariant = __webpack_require__(19); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var fiveArgumentPooler = function (a1, a2, a3, a4, a5) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4, a5); return instance; } else { return new Klass(a1, a2, a3, a4, a5); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : invariant(false) : undefined; instance.destructor(); if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances (optional). * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler, fiveArgumentPooler: fiveArgumentPooler }; module.exports = PooledClass; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Transaction */ 'use strict'; var invariant = __webpack_require__(19); /** * `Transaction` creates a black box that is able to wrap any method such that * certain invariants are maintained before and after the method is invoked * (Even if an exception is thrown while invoking the wrapped method). Whoever * instantiates a transaction can provide enforcers of the invariants at * creation time. The `Transaction` class itself will supply one additional * automatic invariant for you - the invariant that any transaction instance * should not be run while it is already being run. You would typically create a * single instance of a `Transaction` for reuse multiple times, that potentially * is used to wrap several different methods. Wrappers are extremely simple - * they only require implementing two methods. * * <pre> * wrappers (injected at creation time) * + + * | | * +-----------------|--------|--------------+ * | v | | * | +---------------+ | | * | +--| wrapper1 |---|----+ | * | | +---------------+ v | | * | | +-------------+ | | * | | +----| wrapper2 |--------+ | * | | | +-------------+ | | | * | | | | | | * | v v v v | wrapper * | +---+ +---+ +---------+ +---+ +---+ | invariants * perform(anyMethod) | | | | | | | | | | | | maintained * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> * | | | | | | | | | | | | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +---+ +---+ +---------+ +---+ +---+ | * | initialize close | * +-----------------------------------------+ * </pre> * * Use cases: * - Preserving the input selection ranges before/after reconciliation. * Restoring selection even in the event of an unexpected error. * - Deactivating events while rearranging the DOM, preventing blurs/focuses, * while guaranteeing that afterwards, the event system is reactivated. * - Flushing a queue of collected DOM mutations to the main UI thread after a * reconciliation takes place in a worker thread. * - Invoking any collected `componentDidUpdate` callbacks after rendering new * content. * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue * to preserve the `scrollTop` (an automatic scroll aware DOM). * - (Future use case): Layout calculations before and after DOM updates. * * Transactional plugin API: * - A module that has an `initialize` method that returns any precomputation. * - and a `close` method that accepts the precomputation. `close` is invoked * when the wrapped process is completed, or has failed. * * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var Mixin = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function () { this.transactionWrappers = this.getTransactionWrappers(); if (this.wrapperInitData) { this.wrapperInitData.length = 0; } else { this.wrapperInitData = []; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function () { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. The optional arguments helps prevent the need * to bind in many cases. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} a Argument to pass to the method. * @param {Object?=} b Argument to pass to the method. * @param {Object?=} c Argument to pass to the method. * @param {Object?=} d Argument to pass to the method. * @param {Object?=} e Argument to pass to the method. * @param {Object?=} f Argument to pass to the method. * * @return {*} Return value from `method`. */ perform: function (method, scope, a, b, c, d, e, f) { !!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.') : invariant(false) : undefined; var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) {} } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function (startIndex) { var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = Transaction.OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) {} } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function (startIndex) { !this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : invariant(false) : undefined; var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) { wrapper.close.call(this, initData); } errorThrown = false; } finally { if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) {} } } } this.wrapperInitData.length = 0; } }; var Transaction = { Mixin: Mixin, /** * Token to look for to determine if an error occurred. */ OBSERVED_ERROR: {} }; module.exports = Transaction; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyObject */ 'use strict'; var emptyObject = {}; if (process.env.NODE_ENV !== 'production') { Object.freeze(emptyObject); } module.exports = emptyObject; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule containsNode * @typechecks */ 'use strict'; var isTextNode = __webpack_require__(66); /*eslint-disable no-bitwise */ /** * Checks if a given DOM node contains or is another DOM node. * * @param {?DOMNode} outerNode Outer DOM node. * @param {?DOMNode} innerNode Inner DOM node. * @return {boolean} True if `outerNode` contains or is `innerNode`. */ function containsNode(_x, _x2) { var _again = true; _function: while (_again) { var outerNode = _x, innerNode = _x2; _again = false; if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { _x = outerNode; _x2 = innerNode.parentNode; _again = true; continue _function; } else if (outerNode.contains) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } } module.exports = containsNode; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextNode * @typechecks */ 'use strict'; var isNode = __webpack_require__(67); /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && object.nodeType == 3; } module.exports = isTextNode; /***/ }, /* 67 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isNode * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ 'use strict'; function isNode(object) { return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); } module.exports = isNode; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule instantiateReactComponent * @typechecks static-only */ 'use strict'; var ReactCompositeComponent = __webpack_require__(69); var ReactEmptyComponent = __webpack_require__(74); var ReactNativeComponent = __webpack_require__(75); var assign = __webpack_require__(45); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); // To avoid a cyclic dependency, we create the final class in this module var ReactCompositeComponentWrapper = function () {}; assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, { _instantiateReactComponent: instantiateReactComponent }); function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Check if the type reference is a known internal type. I.e. not a user * provided composite type. * * @param {function} type * @return {boolean} Returns true if this is a valid internal type. */ function isInternalComponentType(type) { return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; } /** * Given a ReactNode, create an instance that will actually be mounted. * * @param {ReactNode} node * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(node) { var instance; if (node === null || node === false) { instance = new ReactEmptyComponent(instantiateReactComponent); } else if (typeof node === 'object') { var element = node; !(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) ' + 'or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(false) : undefined; // Special case string values if (typeof element.type === 'string') { instance = ReactNativeComponent.createInternalComponent(element); } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // representations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); } else { instance = new ReactCompositeComponentWrapper(); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactNativeComponent.createInstanceForText(node); } else { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : invariant(false) : undefined; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : undefined; } // Sets up the instance. This can probably just move into the constructor now. instance.construct(node); // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0; instance._mountImage = null; if (process.env.NODE_ENV !== 'production') { instance._isOwnerNecessary = false; instance._warnedAboutRefsInRender = false; } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if (process.env.NODE_ENV !== 'production') { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; } module.exports = instantiateReactComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCompositeComponent */ 'use strict'; var ReactComponentEnvironment = __webpack_require__(70); var ReactCurrentOwner = __webpack_require__(11); var ReactElement = __webpack_require__(48); var ReactInstanceMap = __webpack_require__(53); var ReactPerf = __webpack_require__(24); var ReactPropTypeLocations = __webpack_require__(71); var ReactPropTypeLocationNames = __webpack_require__(72); var ReactReconciler = __webpack_require__(56); var ReactUpdateQueue = __webpack_require__(59); var assign = __webpack_require__(45); var emptyObject = __webpack_require__(64); var invariant = __webpack_require__(19); var shouldUpdateReactComponent = __webpack_require__(73); var warning = __webpack_require__(31); function getDeclarationErrorAddendum(component) { var owner = component._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } function StatelessComponent(Component) {} StatelessComponent.prototype.render = function () { var Component = ReactInstanceMap.get(this)._currentElement.type; return Component(this.props, this.context, this.updater); }; /** * ------------------ The Life-Cycle of a Composite Component ------------------ * * - constructor: Initialization of state. The instance is now retained. * - componentWillMount * - render * - [children's constructors] * - [children's componentWillMount and render] * - [children's componentDidMount] * - componentDidMount * * Update Phases: * - componentWillReceiveProps (only called if parent updated) * - shouldComponentUpdate * - componentWillUpdate * - render * - [children's constructors or receive props phases] * - componentDidUpdate * * - componentWillUnmount * - [children's componentWillUnmount] * - [children destroyed] * - (destroyed): The instance is now blank, released by React and ready for GC. * * ----------------------------------------------------------------------------- */ /** * An incrementing ID assigned to each component when it is mounted. This is * used to enforce the order in which `ReactUpdates` updates dirty components. * * @private */ var nextMountID = 1; /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponentMixin = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function (element) { this._currentElement = element; this._rootNodeID = null; this._instance = null; // See ReactUpdateQueue this._pendingElement = null; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._renderedComponent = null; this._context = null; this._mountOrder = 0; this._topLevelWrapper = null; // See ReactUpdates and ReactUpdateQueue. this._pendingCallbacks = null; }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (rootID, transaction, context) { this._context = context; this._mountOrder = nextMountID++; this._rootNodeID = rootID; var publicProps = this._processProps(this._currentElement.props); var publicContext = this._processContext(context); var Component = this._currentElement.type; // Initialize the public class var inst; var renderedElement; // This is a way to detect if Component is a stateless arrow function // component, which is not newable. It might not be 100% reliable but is // something we can do until we start detecting that Component extends // React.Component. We already assume that typeof Component === 'function'. var canInstantiate = ('prototype' in Component); if (canInstantiate) { if (process.env.NODE_ENV !== 'production') { ReactCurrentOwner.current = this; try { inst = new Component(publicProps, publicContext, ReactUpdateQueue); } finally { ReactCurrentOwner.current = null; } } else { inst = new Component(publicProps, publicContext, ReactUpdateQueue); } } if (!canInstantiate || inst === null || inst === false || ReactElement.isValidElement(inst)) { renderedElement = inst; inst = new StatelessComponent(Component); } if (process.env.NODE_ENV !== 'production') { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging if (inst.render == null) { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`, returned ' + 'null/false from a stateless component, or tried to render an ' + 'element whose type is a function that isn\'t a React component.', Component.displayName || Component.name || 'Component') : undefined; } else { // We support ES6 inheriting from React.Component, the module pattern, // and stateless components, but not ES6 classes that don't extend process.env.NODE_ENV !== 'production' ? warning(Component.prototype && Component.prototype.isReactComponent || !canInstantiate || !(inst instanceof Component), '%s(...): React component classes must extend React.Component.', Component.displayName || Component.name || 'Component') : undefined; } } // These should be set up in the constructor, but as a convenience for // simpler class abstractions, we set them up after the fact. inst.props = publicProps; inst.context = publicContext; inst.refs = emptyObject; inst.updater = ReactUpdateQueue; this._instance = inst; // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this); if (process.env.NODE_ENV !== 'production') { // Since plain JS classes are defined without any special initialization // logic, we can not catch common errors early. Therefore, we have to // catch them here, at initialization time, instead. process.env.NODE_ENV !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : undefined; process.env.NODE_ENV !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : undefined; process.env.NODE_ENV !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : undefined; process.env.NODE_ENV !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : undefined; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : undefined; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : undefined; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : undefined; } var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; if (inst.componentWillMount) { inst.componentWillMount(); // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingStateQueue` without triggering a re-render. if (this._pendingStateQueue) { inst.state = this._processPendingState(inst.props, inst.context); } } // If not a stateless component, we now render if (renderedElement === undefined) { renderedElement = this._renderValidatedComponent(); } this._renderedComponent = this._instantiateReactComponent(renderedElement); var markup = ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, this._processChildContext(context)); if (inst.componentDidMount) { transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); } return markup; }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function () { var inst = this._instance; if (inst.componentWillUnmount) { inst.componentWillUnmount(); } ReactReconciler.unmountComponent(this._renderedComponent); this._renderedComponent = null; this._instance = null; // Reset pending fields // Even if this component is scheduled for another update in ReactUpdates, // it would still be ignored because these fields are reset. this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._pendingCallbacks = null; this._pendingElement = null; // These fields do not really need to be reset since this object is no // longer accessible. this._context = null; this._rootNodeID = null; this._topLevelWrapper = null; // Delete the reference from the instance to this internal representation // which allow the internals to be properly cleaned up even if the user // leaks a reference to the public instance. ReactInstanceMap.remove(inst); // Some existing components rely on inst.props even after they've been // destroyed (in event handlers). // TODO: inst.props = null; // TODO: inst.state = null; // TODO: inst.context = null; }, /** * Filters the context object to only contain keys specified in * `contextTypes` * * @param {object} context * @return {?object} * @private */ _maskContext: function (context) { var maskedContext = null; var Component = this._currentElement.type; var contextTypes = Component.contextTypes; if (!contextTypes) { return emptyObject; } maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function (context) { var maskedContext = this._maskContext(context); if (process.env.NODE_ENV !== 'production') { var Component = this._currentElement.type; if (Component.contextTypes) { this._checkPropTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function (currentContext) { var Component = this._currentElement.type; var inst = this._instance; var childContext = inst.getChildContext && inst.getChildContext(); if (childContext) { !(typeof Component.childContextTypes === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; if (process.env.NODE_ENV !== 'production') { this._checkPropTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext); } for (var name in childContext) { !(name in Component.childContextTypes) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : invariant(false) : undefined; } return assign({}, currentContext, childContext); } return currentContext; }, /** * Processes props by setting default values for unspecified props and * asserting that the props are valid. Does not mutate its argument; returns * a new props object with defaults merged in. * * @param {object} newProps * @return {object} * @private */ _processProps: function (newProps) { if (process.env.NODE_ENV !== 'production') { var Component = this._currentElement.type; if (Component.propTypes) { this._checkPropTypes(Component.propTypes, newProps, ReactPropTypeLocations.prop); } } return newProps; }, /** * Assert that the props are valid * * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkPropTypes: function (propTypes, props, location) { // TODO: Stop validating prop types here and only use the element // validation. var componentName = this.getName(); for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof propTypes[propName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined; error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } if (error instanceof Error) { // We may want to extend this logic for similar errors in // top-level render calls, so I'm abstracting it away into // a function to minimize refactoring in the future var addendum = getDeclarationErrorAddendum(this); if (location === ReactPropTypeLocations.prop) { // Preface gives us something to blacklist in warning module process.env.NODE_ENV !== 'production' ? warning(false, 'Failed Composite propType: %s%s', error.message, addendum) : undefined; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'Failed Context Types: %s%s', error.message, addendum) : undefined; } } } } }, receiveComponent: function (nextElement, transaction, nextContext) { var prevElement = this._currentElement; var prevContext = this._context; this._pendingElement = null; this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); }, /** * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent(this, this._pendingElement || this._currentElement, transaction, this._context); } if (this._pendingStateQueue !== null || this._pendingForceUpdate) { this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); } }, /** * Perform an update to a mounted component. The componentWillReceiveProps and * shouldComponentUpdate methods are called, then (assuming the update isn't * skipped) the remaining update lifecycle methods are called and the DOM * representation is updated. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevParentElement * @param {ReactElement} nextParentElement * @internal * @overridable */ updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { var inst = this._instance; var nextContext = this._context === nextUnmaskedContext ? inst.context : this._processContext(nextUnmaskedContext); var nextProps; // Distinguish between a props update versus a simple state update if (prevParentElement === nextParentElement) { // Skip checking prop types again -- we don't read inst.props to avoid // warning for DOM component props in this upgrade nextProps = nextParentElement.props; } else { nextProps = this._processProps(nextParentElement.props); // An update here will schedule an update but immediately set // _pendingStateQueue which will ensure that any state updates gets // immediately reconciled instead of waiting for the next batch. if (inst.componentWillReceiveProps) { inst.componentWillReceiveProps(nextProps, nextContext); } } var nextState = this._processPendingState(nextProps, nextContext); var shouldUpdate = this._pendingForceUpdate || !inst.shouldComponentUpdate || inst.shouldComponentUpdate(nextProps, nextState, nextContext); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(typeof shouldUpdate !== 'undefined', '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : undefined; } if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext); } else { // If it's determined that a component should not update, we still want // to set props and state but we shortcut the rest of the update. this._currentElement = nextParentElement; this._context = nextUnmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; } }, _processPendingState: function (props, context) { var inst = this._instance; var queue = this._pendingStateQueue; var replace = this._pendingReplaceState; this._pendingReplaceState = false; this._pendingStateQueue = null; if (!queue) { return inst.state; } if (replace && queue.length === 1) { return queue[0]; } var nextState = assign({}, replace ? queue[0] : inst.state); for (var i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial); } return nextState; }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @param {?object} unmaskedContext * @private */ _performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { var inst = this._instance; var hasComponentDidUpdate = Boolean(inst.componentDidUpdate); var prevProps; var prevState; var prevContext; if (hasComponentDidUpdate) { prevProps = inst.props; prevState = inst.state; prevContext = inst.context; } if (inst.componentWillUpdate) { inst.componentWillUpdate(nextProps, nextState, nextContext); } this._currentElement = nextElement; this._context = unmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; this._updateRenderedComponent(transaction, unmaskedContext); if (hasComponentDidUpdate) { transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst); } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function (transaction, context) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; var nextRenderedElement = this._renderValidatedComponent(); if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); } else { // These two IDs are actually the same! But nothing should rely on that. var thisID = this._rootNodeID; var prevComponentID = prevComponentInstance._rootNodeID; ReactReconciler.unmountComponent(prevComponentInstance); this._renderedComponent = this._instantiateReactComponent(nextRenderedElement); var nextMarkup = ReactReconciler.mountComponent(this._renderedComponent, thisID, transaction, this._processChildContext(context)); this._replaceNodeWithMarkupByID(prevComponentID, nextMarkup); } }, /** * @protected */ _replaceNodeWithMarkupByID: function (prevComponentID, nextMarkup) { ReactComponentEnvironment.replaceNodeWithMarkupByID(prevComponentID, nextMarkup); }, /** * @protected */ _renderValidatedComponentWithoutOwnerOrContext: function () { var inst = this._instance; var renderedComponent = inst.render(); if (process.env.NODE_ENV !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (typeof renderedComponent === 'undefined' && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedComponent = null; } } return renderedComponent; }, /** * @private */ _renderValidatedComponent: function () { var renderedComponent; ReactCurrentOwner.current = this; try { renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactCurrentOwner.current = null; } !( // TODO: An `isValidNode` function would probably be more appropriate renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; return renderedComponent; }, /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function (ref, component) { var inst = this.getPublicInstance(); !(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : invariant(false) : undefined; var publicComponentInstance = component.getPublicInstance(); if (process.env.NODE_ENV !== 'production') { var componentName = component && component.getName ? component.getName() : 'a component'; process.env.NODE_ENV !== 'production' ? warning(publicComponentInstance != null, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : undefined; } var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; refs[ref] = publicComponentInstance; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function (ref) { var refs = this.getPublicInstance().refs; delete refs[ref]; }, /** * Get a text description of the component that can be used to identify it * in error messages. * @return {string} The name or null. * @internal */ getName: function () { var type = this._currentElement.type; var constructor = this._instance && this._instance.constructor; return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; }, /** * Get the publicly accessible representation of this component - i.e. what * is exposed by refs and returned by render. Can be null for stateless * components. * * @return {ReactComponent} the public component instance. * @internal */ getPublicInstance: function () { var inst = this._instance; if (inst instanceof StatelessComponent) { return null; } return inst; }, // Stub _instantiateReactComponent: null }; ReactPerf.measureMethods(ReactCompositeComponentMixin, 'ReactCompositeComponent', { mountComponent: 'mountComponent', updateComponent: 'updateComponent', _renderValidatedComponent: '_renderValidatedComponent' }); var ReactCompositeComponent = { Mixin: ReactCompositeComponentMixin }; module.exports = ReactCompositeComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentEnvironment */ 'use strict'; var invariant = __webpack_require__(19); var injected = false; var ReactComponentEnvironment = { /** * Optionally injectable environment dependent cleanup hook. (server vs. * browser etc). Example: A browser system caches DOM nodes based on component * ID and must remove that cache entry when this instance is unmounted. */ unmountIDFromEnvironment: null, /** * Optionally injectable hook for swapping out mount images in the middle of * the tree. */ replaceNodeWithMarkupByID: null, /** * Optionally injectable hook for processing a queue of child updates. Will * later move into MultiChildComponents. */ processChildrenUpdates: null, injection: { injectEnvironment: function (environment) { !!injected ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : invariant(false) : undefined; ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment; ReactComponentEnvironment.replaceNodeWithMarkupByID = environment.replaceNodeWithMarkupByID; ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; injected = true; } } }; module.exports = ReactComponentEnvironment; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocations */ 'use strict'; var keyMirror = __webpack_require__(23); var ReactPropTypeLocations = keyMirror({ prop: null, context: null, childContext: null }); module.exports = ReactPropTypeLocations; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocationNames */ 'use strict'; var ReactPropTypeLocationNames = {}; if (process.env.NODE_ENV !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 73 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shouldUpdateReactComponent * @typechecks static-only */ 'use strict'; /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; if (prevEmpty || nextEmpty) { return prevEmpty === nextEmpty; } var prevType = typeof prevElement; var nextType = typeof nextElement; if (prevType === 'string' || prevType === 'number') { return nextType === 'string' || nextType === 'number'; } else { return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key; } return false; } module.exports = shouldUpdateReactComponent; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEmptyComponent */ 'use strict'; var ReactElement = __webpack_require__(48); var ReactEmptyComponentRegistry = __webpack_require__(50); var ReactReconciler = __webpack_require__(56); var assign = __webpack_require__(45); var placeholderElement; var ReactEmptyComponentInjection = { injectEmptyComponent: function (component) { placeholderElement = ReactElement.createElement(component); } }; var ReactEmptyComponent = function (instantiate) { this._currentElement = null; this._rootNodeID = null; this._renderedComponent = instantiate(placeholderElement); }; assign(ReactEmptyComponent.prototype, { construct: function (element) {}, mountComponent: function (rootID, transaction, context) { ReactEmptyComponentRegistry.registerNullComponentID(rootID); this._rootNodeID = rootID; return ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, context); }, receiveComponent: function () {}, unmountComponent: function (rootID, transaction, context) { ReactReconciler.unmountComponent(this._renderedComponent); ReactEmptyComponentRegistry.deregisterNullComponentID(this._rootNodeID); this._rootNodeID = null; this._renderedComponent = null; } }); ReactEmptyComponent.injection = ReactEmptyComponentInjection; module.exports = ReactEmptyComponent; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNativeComponent */ 'use strict'; var assign = __webpack_require__(45); var invariant = __webpack_require__(19); var autoGenerateWrapperClass = null; var genericComponentClass = null; // This registry keeps track of wrapper classes around native tags. var tagToComponentClass = {}; var textComponentClass = null; var ReactNativeComponentInjection = { // This accepts a class that receives the tag string. This is a catch all // that can render any kind of tag. injectGenericComponentClass: function (componentClass) { genericComponentClass = componentClass; }, // This accepts a text component class that takes the text string to be // rendered as props. injectTextComponentClass: function (componentClass) { textComponentClass = componentClass; }, // This accepts a keyed object with classes as values. Each key represents a // tag. That particular tag will use this class instead of the generic one. injectComponentClasses: function (componentClasses) { assign(tagToComponentClass, componentClasses); } }; /** * Get a composite component wrapper class for a specific tag. * * @param {ReactElement} element The tag for which to get the class. * @return {function} The React class constructor function. */ function getComponentClassForElement(element) { if (typeof element.type === 'function') { return element.type; } var tag = element.type; var componentClass = tagToComponentClass[tag]; if (componentClass == null) { tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag); } return componentClass; } /** * Get a native internal component class for a specific tag. * * @param {ReactElement} element The element to create. * @return {function} The internal class constructor function. */ function createInternalComponent(element) { !genericComponentClass ? process.env.NODE_ENV !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : invariant(false) : undefined; return new genericComponentClass(element.type, element.props); } /** * @param {ReactText} text * @return {ReactComponent} */ function createInstanceForText(text) { return new textComponentClass(text); } /** * @param {ReactComponent} component * @return {boolean} */ function isTextComponent(component) { return component instanceof textComponentClass; } var ReactNativeComponent = { getComponentClassForElement: getComponentClassForElement, createInternalComponent: createInternalComponent, createInstanceForText: createInstanceForText, isTextComponent: isTextComponent, injection: ReactNativeComponentInjection }; module.exports = ReactNativeComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule validateDOMNesting */ 'use strict'; var assign = __webpack_require__(45); var emptyFunction = __webpack_require__(21); var warning = __webpack_require__(31); var validateDOMNesting = emptyFunction; if (process.env.NODE_ENV !== 'production') { // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; var emptyAncestorInfo = { parentTag: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null }; var updatedAncestorInfo = function (oldInfo, tag, instance) { var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo); var info = { tag: tag, instance: instance }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.parentTag = info; if (tag === 'form') { ancestorInfo.formTag = info; } if (tag === 'a') { ancestorInfo.aTagInScope = info; } if (tag === 'button') { ancestorInfo.buttonTagInScope = info; } if (tag === 'nobr') { ancestorInfo.nobrTagInScope = info; } if (tag === 'p') { ancestorInfo.pTagInButtonScope = info; } if (tag === 'li') { ancestorInfo.listItemTagAutoclosing = info; } if (tag === 'dd' || tag === 'dt') { ancestorInfo.dlItemTagAutoclosing = info; } return ancestorInfo; }; /** * Returns whether */ var isTagValidWithParent = function (tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return tag === 'option' || tag === 'optgroup' || tag === '#text'; case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case 'head': return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; case 'rp': case 'rt': return impliedEndTags.indexOf(parentTag) === -1; case 'caption': case 'col': case 'colgroup': case 'frame': case 'head': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ var findInvalidAncestorForTag = function (tag, ancestorInfo) { switch (tag) { case 'address': case 'article': case 'aside': case 'blockquote': case 'center': case 'details': case 'dialog': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'main': case 'menu': case 'nav': case 'ol': case 'p': case 'section': case 'summary': case 'ul': case 'pre': case 'listing': case 'table': case 'hr': case 'xmp': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ancestorInfo.pTagInButtonScope; case 'form': return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case 'li': return ancestorInfo.listItemTagAutoclosing; case 'dd': case 'dt': return ancestorInfo.dlItemTagAutoclosing; case 'button': return ancestorInfo.buttonTagInScope; case 'a': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; }; /** * Given a ReactCompositeComponent instance, return a list of its recursive * owners, starting at the root and ending with the instance itself. */ var findOwnerStack = function (instance) { if (!instance) { return []; } var stack = []; /*eslint-disable space-after-keywords */ do { /*eslint-enable space-after-keywords */ stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }; var didWarn = {}; validateDOMNesting = function (childTag, childInstance, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.parentTag; var parentTag = parentInfo && parentInfo.tag; var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); var problematic = invalidParent || invalidAncestor; if (problematic) { var ancestorTag = problematic.tag; var ancestorInstance = problematic.instance; var childOwner = childInstance && childInstance._currentElement._owner; var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner; var childOwners = findOwnerStack(childOwner); var ancestorOwners = findOwnerStack(ancestorOwner); var minStackLen = Math.min(childOwners.length, ancestorOwners.length); var i; var deepestCommon = -1; for (i = 0; i < minStackLen; i++) { if (childOwners[i] === ancestorOwners[i]) { deepestCommon = i; } else { break; } } var UNKNOWN = '(unknown)'; var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ownerInfo = [].concat( // If the parent and child instances have a common owner ancestor, start // with that -- otherwise we just start with the parent's owners. deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag, // If we're warning about an invalid (non-parent) ancestry, add '...' invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > '); var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo; if (didWarn[warnKey]) { return; } didWarn[warnKey] = true; if (invalidParent) { var info = ''; if (ancestorTag === 'table' && childTag === 'tr') { info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.'; } process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a child of <%s>. ' + 'See %s.%s', childTag, ancestorTag, ownerInfo, info) : undefined; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a descendant of ' + '<%s>. See %s.', childTag, ancestorTag, ownerInfo) : undefined; } } }; validateDOMNesting.ancestorInfoContextKey = '__validateDOMNesting_ancestorInfo$' + Math.random().toString(36).slice(2); validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo; // For testing validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.parentTag; var parentTag = parentInfo && parentInfo.tag; return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo); }; } module.exports = validateDOMNesting; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultInjection */ 'use strict'; var BeforeInputEventPlugin = __webpack_require__(78); var ChangeEventPlugin = __webpack_require__(86); var ClientReactRootIndex = __webpack_require__(89); var DefaultEventPluginOrder = __webpack_require__(90); var EnterLeaveEventPlugin = __webpack_require__(91); var ExecutionEnvironment = __webpack_require__(15); var HTMLDOMPropertyConfig = __webpack_require__(95); var ReactBrowserComponentMixin = __webpack_require__(96); var ReactComponentBrowserEnvironment = __webpack_require__(32); var ReactDefaultBatchingStrategy = __webpack_require__(98); var ReactDOMComponent = __webpack_require__(99); var ReactDOMTextComponent = __webpack_require__(12); var ReactEventListener = __webpack_require__(124); var ReactInjection = __webpack_require__(127); var ReactInstanceHandles = __webpack_require__(51); var ReactMount = __webpack_require__(34); var ReactReconcileTransaction = __webpack_require__(131); var SelectEventPlugin = __webpack_require__(136); var ServerReactRootIndex = __webpack_require__(137); var SimpleEventPlugin = __webpack_require__(138); var SVGDOMPropertyConfig = __webpack_require__(147); var alreadyInjected = false; function inject() { if (alreadyInjected) { // TODO: This is currently true because these injections are shared between // the client and the server package. They should be built independently // and not share any injection state. Then this problem will be solved. return; } alreadyInjected = true; ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles); ReactInjection.EventPluginHub.injectMount(ReactMount); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }); ReactInjection.NativeComponent.injectGenericComponentClass(ReactDOMComponent); ReactInjection.NativeComponent.injectTextComponentClass(ReactDOMTextComponent); ReactInjection.Class.injectMixin(ReactBrowserComponentMixin); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponent('noscript'); ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction); ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy); ReactInjection.RootIndex.injectCreateReactRootIndex(ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); if (process.env.NODE_ENV !== 'production') { var url = ExecutionEnvironment.canUseDOM && window.location.href || ''; if (/[?&]react_perf\b/.test(url)) { var ReactDefaultPerf = __webpack_require__(148); ReactDefaultPerf.start(); } } } module.exports = { inject: inject }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015 Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule BeforeInputEventPlugin * @typechecks static-only */ 'use strict'; var EventConstants = __webpack_require__(36); var EventPropagators = __webpack_require__(79); var ExecutionEnvironment = __webpack_require__(15); var FallbackCompositionState = __webpack_require__(80); var SyntheticCompositionEvent = __webpack_require__(82); var SyntheticInputEvent = __webpack_require__(84); var keyOf = __webpack_require__(85); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window; var documentMode = null; if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) { documentMode = document.documentMode; } // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto(); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. Japanese ideographic // spaces, for instance (\u3000) are not recorded correctly. var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12; } var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); var topLevelTypes = EventConstants.topLevelTypes; // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: keyOf({ onBeforeInput: null }), captured: keyOf({ onBeforeInputCapture: null }) }, dependencies: [topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste] }, compositionEnd: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionEnd: null }), captured: keyOf({ onCompositionEndCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] }, compositionStart: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionStart: null }), captured: keyOf({ onCompositionStartCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] }, compositionUpdate: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionUpdate: null }), captured: keyOf({ onCompositionUpdateCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] } }; // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey); } /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case topLevelTypes.topCompositionStart: return eventTypes.compositionStart; case topLevelTypes.topCompositionEnd: return eventTypes.compositionEnd; case topLevelTypes.topCompositionUpdate: return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionStart(topLevelType, nativeEvent) { return topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE; } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topKeyUp: // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case topLevelTypes.topKeyDown: // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case topLevelTypes.topKeyPress: case topLevelTypes.topMouseDown: case topLevelTypes.topBlur: // Events are not possible without cancelling IME. return true; default: return false; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if (typeof detail === 'object' && 'data' in detail) { return detail.data; } return null; } // Track the current IME composition fallback object, if any. var currentComposition = null; /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackCompositionStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (!eventType) { return null; } if (useFallbackCompositionData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = FallbackCompositionState.getPooled(topLevelTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { fallbackData = currentComposition.getData(); } } } var event = SyntheticCompositionEvent.getPooled(eventType, topLevelTargetID, nativeEvent, nativeEventTarget); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The string corresponding to this `beforeInput` event. */ function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topCompositionEnd: return getDataFromCustomEvent(nativeEvent); case topLevelTypes.topKeyPress: /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case topLevelTypes.topTextInput: // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The fallback string for this `beforeInput` event. */ function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. if (currentComposition) { if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) { var chars = currentComposition.getData(); FallbackCompositionState.release(currentComposition); currentComposition = null; return chars; } return null; } switch (topLevelType) { case topLevelTypes.topPaste: // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case topLevelTypes.topKeyPress: /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { return String.fromCharCode(nativeEvent.which); } return null; case topLevelTypes.topCompositionEnd: return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, topLevelTargetID, nativeEvent, nativeEventTarget); event.data = chars; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ var BeforeInputEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { return [extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget)]; } }; module.exports = BeforeInputEventPlugin; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPropagators */ 'use strict'; var EventConstants = __webpack_require__(36); var EventPluginHub = __webpack_require__(37); var warning = __webpack_require__(31); var accumulateInto = __webpack_require__(41); var forEachAccumulated = __webpack_require__(42); var PropagationPhases = EventConstants.PropagationPhases; var getListener = EventPluginHub.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(id, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(id, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(domID, upwards, event) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(domID, 'Dispatching id must not be null') : undefined; } var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; var listener = listenerAtPhase(domID, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(event._dispatchIDs, domID); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We cannot perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginHub.injection.getInstanceHandle().traverseTwoPhase(event.dispatchMarker, accumulateDirectionalDispatches, event); } } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginHub.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(event.dispatchMarker, accumulateDirectionalDispatches, event); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(id, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(id, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(event._dispatchIDs, id); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event.dispatchMarker, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) { EventPluginHub.injection.getInstanceHandle().traverseEnterLeave(fromID, toID, accumulateDispatches, leave, enter); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing event a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FallbackCompositionState * @typechecks static-only */ 'use strict'; var PooledClass = __webpack_require__(62); var assign = __webpack_require__(45); var getTextContentAccessor = __webpack_require__(81); /** * This helper class stores information about text content of a target node, * allowing comparison of content before and after a given event. * * Identify the node where selection currently begins, then observe * both its text content and its current position in the DOM. Since the * browser may natively replace the target node during composition, we can * use its position to find its replacement. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this._root = root; this._startText = this.getText(); this._fallbackText = null; } assign(FallbackCompositionState.prototype, { destructor: function () { this._root = null; this._startText = null; this._fallbackText = null; }, /** * Get current text of input. * * @return {string} */ getText: function () { if ('value' in this._root) { return this._root.value; } return this._root[getTextContentAccessor()]; }, /** * Determine the differing substring between the initially stored * text content and the current content. * * @return {string} */ getData: function () { if (this._fallbackText) { return this._fallbackText; } var start; var startValue = this._startText; var startLength = startValue.length; var end; var endValue = this.getText(); var endLength = endValue.length; for (start = 0; start < startLength; start++) { if (startValue[start] !== endValue[start]) { break; } } var minEnd = startLength - start; for (end = 1; end <= minEnd; end++) { if (startValue[startLength - end] !== endValue[endLength - end]) { break; } } var sliceTail = end > 1 ? 1 - end : undefined; this._fallbackText = endValue.slice(start, sliceTail); return this._fallbackText; } }); PooledClass.addPoolingTo(FallbackCompositionState); module.exports = FallbackCompositionState; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getTextContentAccessor */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var contentKey = null; /** * Gets the key used to access text content on a DOM node. * * @return {?string} Key used to access text content. * @internal */ function getTextContentAccessor() { if (!contentKey && ExecutionEnvironment.canUseDOM) { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticCompositionEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = __webpack_require__(83); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface); module.exports = SyntheticCompositionEvent; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticEvent * @typechecks static-only */ 'use strict'; var PooledClass = __webpack_require__(62); var assign = __webpack_require__(45); var emptyFunction = __webpack_require__(21); var warning = __webpack_require__(31); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: null, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. */ function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { this.dispatchConfig = dispatchConfig; this.dispatchMarker = dispatchMarker; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } else { this[propName] = nativeEvent[propName]; } } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; } assign(SyntheticEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `preventDefault` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined; } if (!event) { return; } if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `stopPropagation` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined; } if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } this.isPropagationStopped = emptyFunction.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function () { var Interface = this.constructor.Interface; for (var propName in Interface) { this[propName] = null; } this.dispatchConfig = null; this.dispatchMarker = null; this.nativeEvent = null; } }); SyntheticEvent.Interface = EventInterface; /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function (Class, Interface) { var Super = this; var prototype = Object.create(Super.prototype); assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler); module.exports = SyntheticEvent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticInputEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = __webpack_require__(83); /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ var InputEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface); module.exports = SyntheticInputEvent; /***/ }, /* 85 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without losing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ "use strict"; var keyOf = function (oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ChangeEventPlugin */ 'use strict'; var EventConstants = __webpack_require__(36); var EventPluginHub = __webpack_require__(37); var EventPropagators = __webpack_require__(79); var ExecutionEnvironment = __webpack_require__(15); var ReactUpdates = __webpack_require__(60); var SyntheticEvent = __webpack_require__(83); var getEventTarget = __webpack_require__(87); var isEventSupported = __webpack_require__(46); var isTextInputElement = __webpack_require__(88); var keyOf = __webpack_require__(85); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { change: { phasedRegistrationNames: { bubbled: keyOf({ onChange: null }), captured: keyOf({ onChangeCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange] } }; /** * For IE shims */ var activeElement = null; var activeElementID = null; var activeElementValue = null; var activeElementValueProp = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && (!('documentMode' in document) || document.documentMode > 8); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled(eventTypes.change, activeElementID, nativeEvent, getEventTarget(nativeEvent)); EventPropagators.accumulateTwoPhaseDispatches(event); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactUpdates.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(false); } function startWatchingForChangeEventIE8(target, targetID) { activeElement = target; activeElementID = targetID; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementID = null; } function getTargetIDForChangeEvent(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topChange) { return topLevelTargetID; } } function handleEventsForChangeEventIE8(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topFocus) { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForChangeEventIE8(); } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 9); } /** * (For old IE.) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function () { return activeElementValueProp.get.call(this); }, set: function (val) { // Cast to a string so we can do equality checks. activeElementValue = '' + val; activeElementValueProp.set.call(this, val); } }; /** * (For old IE.) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetID) { activeElement = target; activeElementID = targetID; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value'); // Not guarded in a canDefineProperty check: IE8 supports defineProperty only // on DOM elements Object.defineProperty(activeElement, 'value', newValueProp); activeElement.attachEvent('onpropertychange', handlePropertyChange); } /** * (For old IE.) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; activeElement.detachEvent('onpropertychange', handlePropertyChange); activeElement = null; activeElementID = null; activeElementValue = null; activeElementValueProp = null; } /** * (For old IE.) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } var value = nativeEvent.srcElement.value; if (value === activeElementValue) { return; } activeElementValue = value; manualDispatchChangeEvent(nativeEvent); } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetIDForInputEvent(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topInput) { // In modern browsers (i.e., not IE8 or IE9), the input event is exactly // what we want so fall through here and trigger an abstract event return topLevelTargetID; } } // For IE8 and IE9. function handleEventsForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topFocus) { // In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetIDForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. if (activeElement && activeElement.value !== activeElementValue) { activeElementValue = activeElement.value; return activeElementID; } } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); } function getTargetIDForClickEvent(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topClick) { return topLevelTargetID; } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var getTargetIDFunc, handleEventFunc; if (shouldUseChangeEvent(topLevelTarget)) { if (doesChangeEventBubble) { getTargetIDFunc = getTargetIDForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(topLevelTarget)) { if (isInputEventSupported) { getTargetIDFunc = getTargetIDForInputEvent; } else { getTargetIDFunc = getTargetIDForInputEventIE; handleEventFunc = handleEventsForInputEventIE; } } else if (shouldUseClickEvent(topLevelTarget)) { getTargetIDFunc = getTargetIDForClickEvent; } if (getTargetIDFunc) { var targetID = getTargetIDFunc(topLevelType, topLevelTarget, topLevelTargetID); if (targetID) { var event = SyntheticEvent.getPooled(eventTypes.change, targetID, nativeEvent, nativeEventTarget); event.type = 'change'; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } if (handleEventFunc) { handleEventFunc(topLevelType, topLevelTarget, topLevelTargetID); } } }; module.exports = ChangeEventPlugin; /***/ }, /* 87 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventTarget * @typechecks static-only */ 'use strict'; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === 3 ? target.parentNode : target; } module.exports = getEventTarget; /***/ }, /* 88 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextInputElement */ 'use strict'; /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { 'color': true, 'date': true, 'datetime': true, 'datetime-local': true, 'email': true, 'month': true, 'number': true, 'password': true, 'range': true, 'search': true, 'tel': true, 'text': true, 'time': true, 'url': true, 'week': true }; function isTextInputElement(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && supportedInputTypes[elem.type] || nodeName === 'textarea'); } module.exports = isTextInputElement; /***/ }, /* 89 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ClientReactRootIndex * @typechecks */ 'use strict'; var nextReactRootIndex = 0; var ClientReactRootIndex = { createReactRootIndex: function () { return nextReactRootIndex++; } }; module.exports = ClientReactRootIndex; /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DefaultEventPluginOrder */ 'use strict'; var keyOf = __webpack_require__(85); /** * Module that is injectable into `EventPluginHub`, that specifies a * deterministic ordering of `EventPlugin`s. A convenient way to reason about * plugins, without having to package every one of them. This is better than * having plugins be ordered in the same order that they are injected because * that ordering would be influenced by the packaging order. * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that * preventing default on events is convenient in `SimpleEventPlugin` handlers. */ var DefaultEventPluginOrder = [keyOf({ ResponderEventPlugin: null }), keyOf({ SimpleEventPlugin: null }), keyOf({ TapEventPlugin: null }), keyOf({ EnterLeaveEventPlugin: null }), keyOf({ ChangeEventPlugin: null }), keyOf({ SelectEventPlugin: null }), keyOf({ BeforeInputEventPlugin: null })]; module.exports = DefaultEventPluginOrder; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EnterLeaveEventPlugin * @typechecks static-only */ 'use strict'; var EventConstants = __webpack_require__(36); var EventPropagators = __webpack_require__(79); var SyntheticMouseEvent = __webpack_require__(92); var ReactMount = __webpack_require__(34); var keyOf = __webpack_require__(85); var topLevelTypes = EventConstants.topLevelTypes; var getFirstReactDOM = ReactMount.getFirstReactDOM; var eventTypes = { mouseEnter: { registrationName: keyOf({ onMouseEnter: null }), dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] }, mouseLeave: { registrationName: keyOf({ onMouseLeave: null }), dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] } }; var extractedEvents = [null, null]; var EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (topLevelTarget.window === topLevelTarget) { // `topLevelTarget` is probably a window object. win = topLevelTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = topLevelTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from; var to; var fromID = ''; var toID = ''; if (topLevelType === topLevelTypes.topMouseOut) { from = topLevelTarget; fromID = topLevelTargetID; to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement); if (to) { toID = ReactMount.getID(to); } else { to = win; } to = to || win; } else { from = win; to = topLevelTarget; toID = topLevelTargetID; } if (from === to) { // Nothing pertains to our managed components. return null; } var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, fromID, nativeEvent, nativeEventTarget); leave.type = 'mouseleave'; leave.target = from; leave.relatedTarget = to; var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, toID, nativeEvent, nativeEventTarget); enter.type = 'mouseenter'; enter.target = to; enter.relatedTarget = from; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID); extractedEvents[0] = leave; extractedEvents[1] = enter; return extractedEvents; } }; module.exports = EnterLeaveEventPlugin; /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticMouseEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = __webpack_require__(93); var ViewportMetrics = __webpack_require__(44); var getEventModifierState = __webpack_require__(94); /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = { screenX: null, screenY: null, clientX: null, clientY: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, getModifierState: getEventModifierState, button: function (event) { // Webkit, Firefox, IE9+ // which: 1 2 3 // button: 0 1 2 (standard) var button = event.button; if ('which' in event) { return button; } // IE<9 // which: undefined // button: 0 0 0 // button: 1 4 2 (onmouseup) return button === 2 ? 2 : button === 4 ? 1 : 0; }, buttons: null, relatedTarget: function (event) { return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); }, // "Proprietary" Interface. pageX: function (event) { return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; }, pageY: function (event) { return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticUIEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = __webpack_require__(83); var getEventTarget = __webpack_require__(87); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: function (event) { if (event.view) { return event.view; } var target = getEventTarget(event); if (target != null && target.window === target) { // target is a window object return target; } var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. if (doc) { return doc.defaultView || doc.parentWindow; } else { return window; } }, detail: function (event) { return event.detail || 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; /***/ }, /* 94 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventModifierState * @typechecks static-only */ 'use strict'; /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { 'Alt': 'altKey', 'Control': 'ctrlKey', 'Meta': 'metaKey', 'Shift': 'shiftKey' }; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. function modifierStateGetter(keyArg) { var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } module.exports = getEventModifierState; /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule HTMLDOMPropertyConfig */ 'use strict'; var DOMProperty = __webpack_require__(29); var ExecutionEnvironment = __webpack_require__(15); var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS; var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var hasSVG; if (ExecutionEnvironment.canUseDOM) { var implementation = document.implementation; hasSVG = implementation && implementation.hasFeature && implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1'); } var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/), Properties: { /** * Standard Properties */ accept: null, acceptCharset: null, accessKey: null, action: null, allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, allowTransparency: MUST_USE_ATTRIBUTE, alt: null, async: HAS_BOOLEAN_VALUE, autoComplete: null, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, capture: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, cellPadding: null, cellSpacing: null, charSet: MUST_USE_ATTRIBUTE, challenge: MUST_USE_ATTRIBUTE, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, classID: MUST_USE_ATTRIBUTE, // To set className on SVG elements, it's necessary to use .setAttribute; // this works on HTML elements too in all browsers except IE8. Conveniently, // IE8 doesn't support SVG and so we can simply use the attribute in // browsers that support SVG and the property in browsers that don't, // regardless of whether the element is HTML or SVG. className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY, cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, colSpan: null, content: null, contentEditable: null, contextMenu: MUST_USE_ATTRIBUTE, controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, coords: null, crossOrigin: null, data: null, // For `<object />` acts as `src`. dateTime: MUST_USE_ATTRIBUTE, 'default': HAS_BOOLEAN_VALUE, defer: HAS_BOOLEAN_VALUE, dir: null, disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: null, encType: null, form: MUST_USE_ATTRIBUTE, formAction: MUST_USE_ATTRIBUTE, formEncType: MUST_USE_ATTRIBUTE, formMethod: MUST_USE_ATTRIBUTE, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: MUST_USE_ATTRIBUTE, frameBorder: MUST_USE_ATTRIBUTE, headers: null, height: MUST_USE_ATTRIBUTE, hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, high: null, href: null, hrefLang: null, htmlFor: null, httpEquiv: null, icon: null, id: MUST_USE_PROPERTY, inputMode: MUST_USE_ATTRIBUTE, integrity: null, is: MUST_USE_ATTRIBUTE, keyParams: MUST_USE_ATTRIBUTE, keyType: MUST_USE_ATTRIBUTE, kind: null, label: null, lang: null, list: MUST_USE_ATTRIBUTE, loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, low: null, manifest: MUST_USE_ATTRIBUTE, marginHeight: null, marginWidth: null, max: null, maxLength: MUST_USE_ATTRIBUTE, media: MUST_USE_ATTRIBUTE, mediaGroup: null, method: null, min: null, minLength: MUST_USE_ATTRIBUTE, multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: null, nonce: MUST_USE_ATTRIBUTE, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: null, pattern: null, placeholder: null, poster: null, preload: null, radioGroup: null, readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, rel: null, required: HAS_BOOLEAN_VALUE, reversed: HAS_BOOLEAN_VALUE, role: MUST_USE_ATTRIBUTE, rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, rowSpan: null, sandbox: null, scope: null, scoped: HAS_BOOLEAN_VALUE, scrolling: null, seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: null, size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, sizes: MUST_USE_ATTRIBUTE, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: null, src: null, srcDoc: MUST_USE_PROPERTY, srcLang: null, srcSet: MUST_USE_ATTRIBUTE, start: HAS_NUMERIC_VALUE, step: null, style: null, summary: null, tabIndex: null, target: null, title: null, type: null, useMap: null, value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS, width: MUST_USE_ATTRIBUTE, wmode: MUST_USE_ATTRIBUTE, wrap: null, /** * RDFa Properties */ about: MUST_USE_ATTRIBUTE, datatype: MUST_USE_ATTRIBUTE, inlist: MUST_USE_ATTRIBUTE, prefix: MUST_USE_ATTRIBUTE, // property is also supported for OpenGraph in meta tags. property: MUST_USE_ATTRIBUTE, resource: MUST_USE_ATTRIBUTE, 'typeof': MUST_USE_ATTRIBUTE, vocab: MUST_USE_ATTRIBUTE, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: MUST_USE_ATTRIBUTE, autoCorrect: MUST_USE_ATTRIBUTE, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: null, // color is for Safari mask-icon link color: null, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: MUST_USE_ATTRIBUTE, itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, itemType: MUST_USE_ATTRIBUTE, // itemID and itemRef are for Microdata support as well but // only specified in the the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: MUST_USE_ATTRIBUTE, itemRef: MUST_USE_ATTRIBUTE, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: null, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: MUST_USE_ATTRIBUTE, // IE-only attribute that controls focus behavior unselectable: MUST_USE_ATTRIBUTE }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: { autoComplete: 'autocomplete', autoFocus: 'autofocus', autoPlay: 'autoplay', autoSave: 'autosave', // `encoding` is equivalent to `enctype`, IE8 lacks an `enctype` setter. // http://www.w3.org/TR/html5/forms.html#dom-fs-encoding encType: 'encoding', hrefLang: 'hreflang', radioGroup: 'radiogroup', spellCheck: 'spellcheck', srcDoc: 'srcdoc', srcSet: 'srcset' } }; module.exports = HTMLDOMPropertyConfig; /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserComponentMixin */ 'use strict'; var ReactInstanceMap = __webpack_require__(53); var findDOMNode = __webpack_require__(97); var warning = __webpack_require__(31); var didWarnKey = '_getDOMNodeDidWarn'; var ReactBrowserComponentMixin = { /** * Returns the DOM node rendered by this component. * * @return {DOMElement} The root node of this component. * @final * @protected */ getDOMNode: function () { process.env.NODE_ENV !== 'production' ? warning(this.constructor[didWarnKey], '%s.getDOMNode(...) is deprecated. Please use ' + 'ReactDOM.findDOMNode(instance) instead.', ReactInstanceMap.get(this).getName() || this.tagName || 'Unknown') : undefined; this.constructor[didWarnKey] = true; return findDOMNode(this); } }; module.exports = ReactBrowserComponentMixin; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule findDOMNode * @typechecks static-only */ 'use strict'; var ReactCurrentOwner = __webpack_require__(11); var ReactInstanceMap = __webpack_require__(53); var ReactMount = __webpack_require__(34); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); /** * Returns the DOM node rendered by this element. * * @param {ReactComponent|DOMElement} componentOrElement * @return {?DOMElement} The root node of this element. */ function findDOMNode(componentOrElement) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing getDOMNode or findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined; owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === 1) { return componentOrElement; } if (ReactInstanceMap.has(componentOrElement)) { return ReactMount.getNodeFromInstance(componentOrElement); } !(componentOrElement.render == null || typeof componentOrElement.render !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : invariant(false) : undefined; true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : invariant(false) : undefined; } module.exports = findDOMNode; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultBatchingStrategy */ 'use strict'; var ReactUpdates = __webpack_require__(60); var Transaction = __webpack_require__(63); var assign = __webpack_require__(45); var emptyFunction = __webpack_require__(21); var RESET_BATCHED_UPDATES = { initialize: emptyFunction, close: function () { ReactDefaultBatchingStrategy.isBatchingUpdates = false; } }; var FLUSH_BATCHED_UPDATES = { initialize: emptyFunction, close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) }; var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; function ReactDefaultBatchingStrategyTransaction() { this.reinitializeTransaction(); } assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; } }); var transaction = new ReactDefaultBatchingStrategyTransaction(); var ReactDefaultBatchingStrategy = { isBatchingUpdates: false, /** * Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function (callback, a, b, c, d, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(a, b, c, d, e); } else { transaction.perform(callback, null, a, b, c, d, e); } } }; module.exports = ReactDefaultBatchingStrategy; /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponent * @typechecks static-only */ /* global hasOwnProperty:true */ 'use strict'; var AutoFocusUtils = __webpack_require__(100); var CSSPropertyOperations = __webpack_require__(102); var DOMProperty = __webpack_require__(29); var DOMPropertyOperations = __webpack_require__(28); var EventConstants = __webpack_require__(36); var ReactBrowserEventEmitter = __webpack_require__(35); var ReactComponentBrowserEnvironment = __webpack_require__(32); var ReactDOMButton = __webpack_require__(110); var ReactDOMInput = __webpack_require__(111); var ReactDOMOption = __webpack_require__(115); var ReactDOMSelect = __webpack_require__(118); var ReactDOMTextarea = __webpack_require__(119); var ReactMount = __webpack_require__(34); var ReactMultiChild = __webpack_require__(120); var ReactPerf = __webpack_require__(24); var ReactUpdateQueue = __webpack_require__(59); var assign = __webpack_require__(45); var canDefineProperty = __webpack_require__(49); var escapeTextContentForBrowser = __webpack_require__(27); var invariant = __webpack_require__(19); var isEventSupported = __webpack_require__(46); var keyOf = __webpack_require__(85); var setInnerHTML = __webpack_require__(25); var setTextContent = __webpack_require__(26); var shallowEqual = __webpack_require__(123); var validateDOMNesting = __webpack_require__(76); var warning = __webpack_require__(31); var deleteListener = ReactBrowserEventEmitter.deleteListener; var listenTo = ReactBrowserEventEmitter.listenTo; var registrationNameModules = ReactBrowserEventEmitter.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = { 'string': true, 'number': true }; var CHILDREN = keyOf({ children: null }); var STYLE = keyOf({ style: null }); var HTML = keyOf({ __html: null }); var ELEMENT_NODE_TYPE = 1; function getDeclarationErrorAddendum(internalInstance) { if (internalInstance) { var owner = internalInstance._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' This DOM node was rendered by `' + name + '`.'; } } } return ''; } var legacyPropsDescriptor; if (process.env.NODE_ENV !== 'production') { legacyPropsDescriptor = { props: { enumerable: false, get: function () { var component = this._reactInternalComponent; process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .props of a DOM node; instead, ' + 'recreate the props as `render` did originally or read the DOM ' + 'properties/attributes directly from this node (e.g., ' + 'this.refs.box.className).%s', getDeclarationErrorAddendum(component)) : undefined; return component._currentElement.props; } } }; } function legacyGetDOMNode() { if (process.env.NODE_ENV !== 'production') { var component = this._reactInternalComponent; process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .getDOMNode() of a DOM node; ' + 'instead, use the node directly.%s', getDeclarationErrorAddendum(component)) : undefined; } return this; } function legacyIsMounted() { var component = this._reactInternalComponent; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .isMounted() of a DOM node.%s', getDeclarationErrorAddendum(component)) : undefined; } return !!component; } function legacySetStateEtc() { if (process.env.NODE_ENV !== 'production') { var component = this._reactInternalComponent; process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setState(), .replaceState(), or ' + '.forceUpdate() of a DOM node. This is a no-op.%s', getDeclarationErrorAddendum(component)) : undefined; } } function legacySetProps(partialProps, callback) { var component = this._reactInternalComponent; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined; } if (!component) { return; } ReactUpdateQueue.enqueueSetPropsInternal(component, partialProps); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(component, callback); } } function legacyReplaceProps(partialProps, callback) { var component = this._reactInternalComponent; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .replaceProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined; } if (!component) { return; } ReactUpdateQueue.enqueueReplacePropsInternal(component, partialProps); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(component, callback); } } function friendlyStringify(obj) { if (typeof obj === 'object') { if (Array.isArray(obj)) { return '[' + obj.map(friendlyStringify).join(', ') + ']'; } else { var pairs = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key); pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key])); } } return '{' + pairs.join(', ') + '}'; } } else if (typeof obj === 'string') { return JSON.stringify(obj); } else if (typeof obj === 'function') { return '[function object]'; } // Differs from JSON.stringify in that undefined becauses undefined and that // inf and nan don't become null return String(obj); } var styleMutationWarning = {}; function checkAndWarnForMutatedStyle(style1, style2, component) { if (style1 == null || style2 == null) { return; } if (shallowEqual(style1, style2)) { return; } var componentName = component._tag; var owner = component._currentElement._owner; var ownerName; if (owner) { ownerName = owner.getName(); } var hash = ownerName + '|' + componentName; if (styleMutationWarning.hasOwnProperty(hash)) { return; } styleMutationWarning[hash] = true; process.env.NODE_ENV !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : undefined; } /** * @param {object} component * @param {?object} props */ function assertValidProps(component, props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (process.env.NODE_ENV !== 'production') { if (voidElementTags[component._tag]) { process.env.NODE_ENV !== 'production' ? warning(props.children == null && props.dangerouslySetInnerHTML == null, '%s is a void element tag and must not have `children` or ' + 'use `props.dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : undefined; } } if (props.dangerouslySetInnerHTML != null) { !(props.children == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : invariant(false) : undefined; !(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' + 'for more information.') : invariant(false) : undefined; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : undefined; process.env.NODE_ENV !== 'production' ? warning(!props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : undefined; } !(props.style == null || typeof props.style === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, ' + 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' + 'using JSX.%s', getDeclarationErrorAddendum(component)) : invariant(false) : undefined; } function enqueuePutListener(id, registrationName, listener, transaction) { if (process.env.NODE_ENV !== 'production') { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. process.env.NODE_ENV !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : undefined; } var container = ReactMount.findReactContainerForID(id); if (container) { var doc = container.nodeType === ELEMENT_NODE_TYPE ? container.ownerDocument : container; listenTo(registrationName, doc); } transaction.getReactMountReady().enqueue(putListener, { id: id, registrationName: registrationName, listener: listener }); } function putListener() { var listenerToPut = this; ReactBrowserEventEmitter.putListener(listenerToPut.id, listenerToPut.registrationName, listenerToPut.listener); } // There are so many media events, it makes sense to just // maintain a list rather than create a `trapBubbledEvent` for each var mediaEvents = { topAbort: 'abort', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topSeeked: 'seeked', topSeeking: 'seeking', topStalled: 'stalled', topSuspend: 'suspend', topTimeUpdate: 'timeupdate', topVolumeChange: 'volumechange', topWaiting: 'waiting' }; function trapBubbledEventsLocal() { var inst = this; // If a component renders to null or if another component fatals and causes // the state of the tree to be corrupted, `node` here can be null. !inst._rootNodeID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Must be mounted to trap events') : invariant(false) : undefined; var node = ReactMount.getNode(inst._rootNodeID); !node ? process.env.NODE_ENV !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : invariant(false) : undefined; switch (inst._tag) { case 'iframe': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; break; case 'video': case 'audio': inst._wrapperState.listeners = []; // create listener for each media event for (var event in mediaEvents) { if (mediaEvents.hasOwnProperty(event)) { inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node)); } } break; case 'img': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; break; case 'form': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit', node)]; break; } } function mountReadyInputWrapper() { ReactDOMInput.mountReadyWrapper(this); } function postUpdateSelectWrapper() { ReactDOMSelect.postUpdateWrapper(this); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special cased tags. var omittedCloseTags = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true }; // NOTE: menuitem's close tag should be omitted, but that causes problems. var newlineEatingTags = { 'listing': true, 'pre': true, 'textarea': true }; // For HTML, certain tags cannot have children. This has the same purpose as // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = assign({ 'menuitem': true }, omittedCloseTags); // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; var hasOwnProperty = ({}).hasOwnProperty; function validateDangerousTag(tag) { if (!hasOwnProperty.call(validatedTagCache, tag)) { !VALID_TAG_REGEX.test(tag) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : invariant(false) : undefined; validatedTagCache[tag] = true; } } function processChildContextDev(context, inst) { // Pass down our tag name to child components for validation purposes context = assign({}, context); var info = context[validateDOMNesting.ancestorInfoContextKey]; context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(info, inst._tag, inst); return context; } function isCustomComponent(tagName, props) { return tagName.indexOf('-') >= 0 || props.is != null; } /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @constructor ReactDOMComponent * @extends ReactMultiChild */ function ReactDOMComponent(tag) { validateDangerousTag(tag); this._tag = tag.toLowerCase(); this._renderedChildren = null; this._previousStyle = null; this._previousStyleCopy = null; this._rootNodeID = null; this._wrapperState = null; this._topLevelWrapper = null; this._nodeWithLegacyProperties = null; if (process.env.NODE_ENV !== 'production') { this._unprocessedContextDev = null; this._processedContextDev = null; } } ReactDOMComponent.displayName = 'ReactDOMComponent'; ReactDOMComponent.Mixin = { construct: function (element) { this._currentElement = element; }, /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {string} rootID The root DOM ID for this node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context * @return {string} The computed markup. */ mountComponent: function (rootID, transaction, context) { this._rootNodeID = rootID; var props = this._currentElement.props; switch (this._tag) { case 'iframe': case 'img': case 'form': case 'video': case 'audio': this._wrapperState = { listeners: null }; transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'button': props = ReactDOMButton.getNativeProps(this, props, context); break; case 'input': ReactDOMInput.mountWrapper(this, props, context); props = ReactDOMInput.getNativeProps(this, props, context); break; case 'option': ReactDOMOption.mountWrapper(this, props, context); props = ReactDOMOption.getNativeProps(this, props, context); break; case 'select': ReactDOMSelect.mountWrapper(this, props, context); props = ReactDOMSelect.getNativeProps(this, props, context); context = ReactDOMSelect.processChildContext(this, props, context); break; case 'textarea': ReactDOMTextarea.mountWrapper(this, props, context); props = ReactDOMTextarea.getNativeProps(this, props, context); break; } assertValidProps(this, props); if (process.env.NODE_ENV !== 'production') { if (context[validateDOMNesting.ancestorInfoContextKey]) { validateDOMNesting(this._tag, this, context[validateDOMNesting.ancestorInfoContextKey]); } } if (process.env.NODE_ENV !== 'production') { this._unprocessedContextDev = context; this._processedContextDev = processChildContextDev(context, this); context = this._processedContextDev; } var mountImage; if (transaction.useCreateElement) { var ownerDocument = context[ReactMount.ownerDocumentContextKey]; var el = ownerDocument.createElement(this._currentElement.type); DOMPropertyOperations.setAttributeForID(el, this._rootNodeID); // Populate node cache ReactMount.getID(el); this._updateDOMProperties({}, props, transaction, el); this._createInitialChildren(transaction, props, context, el); mountImage = el; } else { var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props); var tagContent = this._createContentMarkup(transaction, props, context); if (!tagContent && omittedCloseTags[this._tag]) { mountImage = tagOpen + '/>'; } else { mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>'; } } switch (this._tag) { case 'input': transaction.getReactMountReady().enqueue(mountReadyInputWrapper, this); // falls through case 'button': case 'select': case 'textarea': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; } return mountImage; }, /** * Creates markup for the open tag and all attributes. * * This method has side effects because events get registered. * * Iterating over object properties is faster than iterating over arrays. * @see http://jsperf.com/obj-vs-arr-iteration * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function (transaction, props) { var ret = '<' + this._currentElement.type; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { if (propValue) { enqueuePutListener(this._rootNodeID, propKey, propValue, transaction); } } else { if (propKey === STYLE) { if (propValue) { if (process.env.NODE_ENV !== 'production') { // See `_updateDOMProperties`. style block this._previousStyle = propValue; } propValue = this._previousStyleCopy = assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue); } var markup = null; if (this._tag != null && isCustomComponent(this._tag, props)) { if (propKey !== CHILDREN) { markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue); } } else { markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret; } var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID); return ret + ' ' + markupForID; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @param {object} context * @return {string} Content markup. */ _createContentMarkup: function (transaction, props, context) { var ret = ''; // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { ret = innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node ret = escapeTextContentForBrowser(contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); ret = mountImages.join(''); } } if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') { // text/html ignores the first character in these tags if it's a newline // Prefer to break application/xml over text/html (for now) by adding // a newline specifically to get eaten by the parser. (Alternately for // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first // \r is normalized out by HTMLTextAreaElement#value.) // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> // See: Parsing of "textarea" "listing" and "pre" elements // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> return '\n' + ret; } else { return ret; } }, _createInitialChildren: function (transaction, props, context, el) { // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { setInnerHTML(el, innerHTML.__html); } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node setTextContent(el, contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); for (var i = 0; i < mountImages.length; i++) { el.appendChild(mountImages[i]); } } } }, /** * Receives a next element and updates the component. * * @internal * @param {ReactElement} nextElement * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context */ receiveComponent: function (nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }, /** * Updates a native DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @param {ReactElement} nextElement * @internal * @overridable */ updateComponent: function (transaction, prevElement, nextElement, context) { var lastProps = prevElement.props; var nextProps = this._currentElement.props; switch (this._tag) { case 'button': lastProps = ReactDOMButton.getNativeProps(this, lastProps); nextProps = ReactDOMButton.getNativeProps(this, nextProps); break; case 'input': ReactDOMInput.updateWrapper(this); lastProps = ReactDOMInput.getNativeProps(this, lastProps); nextProps = ReactDOMInput.getNativeProps(this, nextProps); break; case 'option': lastProps = ReactDOMOption.getNativeProps(this, lastProps); nextProps = ReactDOMOption.getNativeProps(this, nextProps); break; case 'select': lastProps = ReactDOMSelect.getNativeProps(this, lastProps); nextProps = ReactDOMSelect.getNativeProps(this, nextProps); break; case 'textarea': ReactDOMTextarea.updateWrapper(this); lastProps = ReactDOMTextarea.getNativeProps(this, lastProps); nextProps = ReactDOMTextarea.getNativeProps(this, nextProps); break; } if (process.env.NODE_ENV !== 'production') { // If the context is reference-equal to the old one, pass down the same // processed object so the update bailout in ReactReconciler behaves // correctly (and identically in dev and prod). See #5005. if (this._unprocessedContextDev !== context) { this._unprocessedContextDev = context; this._processedContextDev = processChildContextDev(context, this); } context = this._processedContextDev; } assertValidProps(this, nextProps); this._updateDOMProperties(lastProps, nextProps, transaction, null); this._updateDOMChildren(lastProps, nextProps, transaction, context); if (!canDefineProperty && this._nodeWithLegacyProperties) { this._nodeWithLegacyProperties.props = nextProps; } if (this._tag === 'select') { // <select> value update needs to occur after <option> children // reconciliation transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this); } }, /** * Reconciles the properties by detecting differences in property values and * updating the DOM as necessary. This function is probably the single most * critical path for performance optimization. * * TODO: Benchmark whether checking for changed values in memory actually * improves performance (especially statically positioned elements). * TODO: Benchmark the effects of putting this at the top since 99% of props * do not change for a given reconciliation. * TODO: Benchmark areas that can be improved with caching. * * @private * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {?DOMElement} node */ _updateDOMProperties: function (lastProps, nextProps, transaction, node) { var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey)) { continue; } if (propKey === STYLE) { var lastStyle = this._previousStyleCopy; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } this._previousStyleCopy = null; } else if (registrationNameModules.hasOwnProperty(propKey)) { if (lastProps[propKey]) { // Only call deleteListener if there was a listener previously or // else willDeleteListener gets called when there wasn't actually a // listener (e.g., onClick={null}) deleteListener(this._rootNodeID, propKey); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { if (!node) { node = ReactMount.getNode(this._rootNodeID); } DOMPropertyOperations.deleteValueForProperty(node, propKey); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps[propKey]; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) { continue; } if (propKey === STYLE) { if (nextProp) { if (process.env.NODE_ENV !== 'production') { checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this); this._previousStyle = nextProp; } nextProp = this._previousStyleCopy = assign({}, nextProp); } else { this._previousStyleCopy = null; } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (registrationNameModules.hasOwnProperty(propKey)) { if (nextProp) { enqueuePutListener(this._rootNodeID, propKey, nextProp, transaction); } else if (lastProp) { deleteListener(this._rootNodeID, propKey); } } else if (isCustomComponent(this._tag, nextProps)) { if (!node) { node = ReactMount.getNode(this._rootNodeID); } if (propKey === CHILDREN) { nextProp = null; } DOMPropertyOperations.setValueForAttribute(node, propKey, nextProp); } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { if (!node) { node = ReactMount.getNode(this._rootNodeID); } // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertantly setting to a string. This // brings us in line with the same behavior we have on initial render. if (nextProp != null) { DOMPropertyOperations.setValueForProperty(node, propKey, nextProp); } else { DOMPropertyOperations.deleteValueForProperty(node, propKey); } } } if (styleUpdates) { if (!node) { node = ReactMount.getNode(this._rootNodeID); } CSSPropertyOperations.setValueForStyles(node, styleUpdates); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {object} context */ _updateDOMChildren: function (lastProps, nextProps, transaction, context) { var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction, context); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { this.updateMarkup('' + nextHtml); } } else if (nextChildren != null) { this.updateChildren(nextChildren, transaction, context); } }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function () { switch (this._tag) { case 'iframe': case 'img': case 'form': case 'video': case 'audio': var listeners = this._wrapperState.listeners; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].remove(); } } break; case 'input': ReactDOMInput.unmountWrapper(this); break; case 'html': case 'head': case 'body': /** * Components like <html> <head> and <body> can't be removed or added * easily in a cross-browser way, however it's valuable to be able to * take advantage of React's reconciliation for styling and <title> * management. So we just document it and throw in dangerous cases. */ true ? process.env.NODE_ENV !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is ' + 'impossible to unmount some top-level components (eg <html>, ' + '<head>, and <body>) reliably and efficiently. To fix this, have a ' + 'single top-level component that never unmounts render these ' + 'elements.', this._tag) : invariant(false) : undefined; break; } this.unmountChildren(); ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID); ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); this._rootNodeID = null; this._wrapperState = null; if (this._nodeWithLegacyProperties) { var node = this._nodeWithLegacyProperties; node._reactInternalComponent = null; this._nodeWithLegacyProperties = null; } }, getPublicInstance: function () { if (!this._nodeWithLegacyProperties) { var node = ReactMount.getNode(this._rootNodeID); node._reactInternalComponent = this; node.getDOMNode = legacyGetDOMNode; node.isMounted = legacyIsMounted; node.setState = legacySetStateEtc; node.replaceState = legacySetStateEtc; node.forceUpdate = legacySetStateEtc; node.setProps = legacySetProps; node.replaceProps = legacyReplaceProps; if (process.env.NODE_ENV !== 'production') { if (canDefineProperty) { Object.defineProperties(node, legacyPropsDescriptor); } else { // updateComponent will update this property on subsequent renders node.props = this._currentElement.props; } } else { // updateComponent will update this property on subsequent renders node.props = this._currentElement.props; } this._nodeWithLegacyProperties = node; } return this._nodeWithLegacyProperties; } }; ReactPerf.measureMethods(ReactDOMComponent, 'ReactDOMComponent', { mountComponent: 'mountComponent', updateComponent: 'updateComponent' }); assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin); module.exports = ReactDOMComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule AutoFocusUtils * @typechecks static-only */ 'use strict'; var ReactMount = __webpack_require__(34); var findDOMNode = __webpack_require__(97); var focusNode = __webpack_require__(101); var Mixin = { componentDidMount: function () { if (this.props.autoFocus) { focusNode(findDOMNode(this)); } } }; var AutoFocusUtils = { Mixin: Mixin, focusDOMComponent: function () { focusNode(ReactMount.getNode(this._rootNodeID)); } }; module.exports = AutoFocusUtils; /***/ }, /* 101 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule focusNode */ 'use strict'; /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch (e) {} } module.exports = focusNode; /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSPropertyOperations * @typechecks static-only */ 'use strict'; var CSSProperty = __webpack_require__(103); var ExecutionEnvironment = __webpack_require__(15); var ReactPerf = __webpack_require__(24); var camelizeStyleName = __webpack_require__(104); var dangerousStyleValue = __webpack_require__(106); var hyphenateStyleName = __webpack_require__(107); var memoizeStringOnly = __webpack_require__(109); var warning = __webpack_require__(31); var processStyleName = memoizeStringOnly(function (styleName) { return hyphenateStyleName(styleName); }); var hasShorthandPropertyBug = false; var styleFloatAccessor = 'cssFloat'; if (ExecutionEnvironment.canUseDOM) { var tempStyle = document.createElement('div').style; try { // IE8 throws "Invalid argument." if resetting shorthand style properties. tempStyle.font = ''; } catch (e) { hasShorthandPropertyBug = true; } // IE8 only supports accessing cssFloat (standard) as styleFloat if (document.documentElement.style.cssFloat === undefined) { styleFloatAccessor = 'styleFloat'; } } if (process.env.NODE_ENV !== 'production') { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnHyphenatedStyleName = function (name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?', name, camelizeStyleName(name)) : undefined; }; var warnBadVendoredStyleName = function (name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)) : undefined; }; var warnStyleValueWithSemicolon = function (name, value) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon. ' + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')) : undefined; }; /** * @param {string} name * @param {*} value */ var warnValidStyle = function (name, value) { if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value); } }; } /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @return {?string} */ createMarkupForStyles: function (styles) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if (process.env.NODE_ENV !== 'production') { warnValidStyle(styleName, styleValue); } if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles */ setValueForStyles: function (node, styles) { var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if (process.env.NODE_ENV !== 'production') { warnValidStyle(styleName, styles[styleName]); } var styleValue = dangerousStyleValue(styleName, styles[styleName]); if (styleName === 'float') { styleName = styleFloatAccessor; } if (styleValue) { style[styleName] = styleValue; } else { var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName]; if (expansion) { // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) { style[individualStyleName] = ''; } } else { style[styleName] = ''; } } } } }; ReactPerf.measureMethods(CSSPropertyOperations, 'CSSPropertyOperations', { setValueForStyles: 'setValueForStyles' }); module.exports = CSSPropertyOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 103 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSProperty */ 'use strict'; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { animationIterationCount: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, stopOpacity: true, strokeDashoffset: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundAttachment: true, backgroundColor: true, backgroundImage: true, backgroundPositionX: true, backgroundPositionY: true, backgroundRepeat: true }, backgroundPosition: { backgroundPositionX: true, backgroundPositionY: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true }, outline: { outlineWidth: true, outlineStyle: true, outlineColor: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule camelizeStyleName * @typechecks */ 'use strict'; var camelize = __webpack_require__(105); var msPattern = /^-ms-/; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < "backgroundColor" * > camelizeStyleName('-moz-transition') * < "MozTransition" * > camelizeStyleName('-ms-transition') * < "msTransition" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); } module.exports = camelizeStyleName; /***/ }, /* 105 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule camelize * @typechecks */ "use strict"; var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } module.exports = camelize; /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule dangerousStyleValue * @typechecks static-only */ 'use strict'; var CSSProperty = __webpack_require__(103); var isUnitlessNumber = CSSProperty.isUnitlessNumber; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } var isNonNumeric = isNaN(value); if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { return '' + value; // cast to string } if (typeof value === 'string') { value = value.trim(); } return value + 'px'; } module.exports = dangerousStyleValue; /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule hyphenateStyleName * @typechecks */ 'use strict'; var hyphenate = __webpack_require__(108); var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); } module.exports = hyphenateStyleName; /***/ }, /* 108 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule hyphenate * @typechecks */ 'use strict'; var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; /***/ }, /* 109 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule memoizeStringOnly * @typechecks static-only */ 'use strict'; /** * Memoizes the return value of a function that accepts one string argument. * * @param {function} callback * @return {function} */ function memoizeStringOnly(callback) { var cache = {}; return function (string) { if (!cache.hasOwnProperty(string)) { cache[string] = callback.call(this, string); } return cache[string]; }; } module.exports = memoizeStringOnly; /***/ }, /* 110 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMButton */ 'use strict'; var mouseListenerNames = { onClick: true, onDoubleClick: true, onMouseDown: true, onMouseMove: true, onMouseUp: true, onClickCapture: true, onDoubleClickCapture: true, onMouseDownCapture: true, onMouseMoveCapture: true, onMouseUpCapture: true }; /** * Implements a <button> native component that does not receive mouse events * when `disabled` is set. */ var ReactDOMButton = { getNativeProps: function (inst, props, context) { if (!props.disabled) { return props; } // Copy the props, except the mouse listeners var nativeProps = {}; for (var key in props) { if (props.hasOwnProperty(key) && !mouseListenerNames[key]) { nativeProps[key] = props[key]; } } return nativeProps; } }; module.exports = ReactDOMButton; /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMInput */ 'use strict'; var ReactDOMIDOperations = __webpack_require__(33); var LinkedValueUtils = __webpack_require__(112); var ReactMount = __webpack_require__(34); var ReactUpdates = __webpack_require__(60); var assign = __webpack_require__(45); var invariant = __webpack_require__(19); var instancesByReactID = {}; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMInput.updateWrapper(this); } } /** * Implements an <input> native component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ var ReactDOMInput = { getNativeProps: function (inst, props, context) { var value = LinkedValueUtils.getValue(props); var checked = LinkedValueUtils.getChecked(props); var nativeProps = assign({}, props, { defaultChecked: undefined, defaultValue: undefined, value: value != null ? value : inst._wrapperState.initialValue, checked: checked != null ? checked : inst._wrapperState.initialChecked, onChange: inst._wrapperState.onChange }); return nativeProps; }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner); } var defaultValue = props.defaultValue; inst._wrapperState = { initialChecked: props.defaultChecked || false, initialValue: defaultValue != null ? defaultValue : null, onChange: _handleChange.bind(inst) }; }, mountReadyWrapper: function (inst) { // Can't be in mountWrapper or else server rendering leaks. instancesByReactID[inst._rootNodeID] = inst; }, unmountWrapper: function (inst) { delete instancesByReactID[inst._rootNodeID]; }, updateWrapper: function (inst) { var props = inst._currentElement.props; // TODO: Shouldn't this be getChecked(props)? var checked = props.checked; if (checked != null) { ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'checked', checked || false); } var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value); } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); // Here we use asap to wait until all updates have propagated, which // is important when using controlled components within layers: // https://github.com/facebook/react/issues/1698 ReactUpdates.asap(forceUpdateIfMounted, this); var name = props.name; if (props.type === 'radio' && name != null) { var rootNode = ReactMount.getNode(this._rootNodeID); var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form, let's just use the global // `querySelectorAll` to ensure we don't miss anything. var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0; i < group.length; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React with non-React. var otherID = ReactMount.getID(otherNode); !otherID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.') : invariant(false) : undefined; var otherInstance = instancesByReactID[otherID]; !otherInstance ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Unknown radio button ID %s.', otherID) : invariant(false) : undefined; // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. ReactUpdates.asap(forceUpdateIfMounted, otherInstance); } } return returnValue; } module.exports = ReactDOMInput; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LinkedValueUtils * @typechecks static-only */ 'use strict'; var ReactPropTypes = __webpack_require__(113); var ReactPropTypeLocations = __webpack_require__(71); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; function _assertSingleLink(inputProps) { !(inputProps.checkedLink == null || inputProps.valueLink == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.') : invariant(false) : undefined; } function _assertValueLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.value == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.') : invariant(false) : undefined; } function _assertCheckedLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.checked == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don\'t want to ' + 'use checkedLink') : invariant(false) : undefined; } var propTypes = { value: function (props, propName, componentName) { if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, checked: function (props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, onChange: ReactPropTypes.func }; var loggedTypeFailures = {}; function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var LinkedValueUtils = { checkPropTypes: function (tagName, props, owner) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(owner); process.env.NODE_ENV !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : undefined; } } }, /** * @param {object} inputProps Props for form component * @return {*} current value of the input either from value prop or link. */ getValue: function (inputProps) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.value; } return inputProps.value; }, /** * @param {object} inputProps Props for form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function (inputProps) { if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.value; } return inputProps.checked; }, /** * @param {object} inputProps Props for form component * @param {SyntheticEvent} event change event to handle */ executeOnChange: function (inputProps, event) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.requestChange(event.target.value); } else if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.requestChange(event.target.checked); } else if (inputProps.onChange) { return inputProps.onChange.call(undefined, event); } } }; module.exports = LinkedValueUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypes */ 'use strict'; var ReactElement = __webpack_require__(48); var ReactPropTypeLocationNames = __webpack_require__(72); var emptyFunction = __webpack_require__(21); var getIteratorFn = __webpack_require__(114); /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location, propFullName) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (props[propName] == null) { var locationName = ReactPropTypeLocationNames[location]; if (isRequired) { return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { var locationName = ReactPropTypeLocationNames[location]; // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturns(null)); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!Array.isArray(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']'); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!ReactElement.isValidElement(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var locationName = ReactPropTypeLocationNames[location]; var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { return createChainableTypeChecker(function () { return new Error('Invalid argument supplied to oneOf, expected an instance of array.'); }); } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (propValue === expectedValues[i]) { return null; } } var locationName = ReactPropTypeLocationNames[location]; var valuesString = JSON.stringify(expectedValues); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { return createChainableTypeChecker(function () { return new Error('Invalid argument supplied to oneOfType, expected an instance of array.'); }); } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName) == null) { return null; } } var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || ReactElement.isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return '<<anonymous>>'; } return propValue.constructor.name; } module.exports = ReactPropTypes; /***/ }, /* 114 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getIteratorFn * @typechecks static-only */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMOption */ 'use strict'; var ReactChildren = __webpack_require__(116); var ReactDOMSelect = __webpack_require__(118); var assign = __webpack_require__(45); var warning = __webpack_require__(31); var valueContextKey = ReactDOMSelect.valueContextKey; /** * Implements an <option> native component that warns when `selected` is set. */ var ReactDOMOption = { mountWrapper: function (inst, props, context) { // TODO (yungsters): Remove support for `selected` in <option>. if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : undefined; } // Look up whether this option is 'selected' via context var selectValue = context[valueContextKey]; // If context key is null (e.g., no specified value or after initial mount) // or missing (e.g., for <datalist>), we don't change props.selected var selected = null; if (selectValue != null) { selected = false; if (Array.isArray(selectValue)) { // multiple for (var i = 0; i < selectValue.length; i++) { if ('' + selectValue[i] === '' + props.value) { selected = true; break; } } } else { selected = '' + selectValue === '' + props.value; } } inst._wrapperState = { selected: selected }; }, getNativeProps: function (inst, props, context) { var nativeProps = assign({ selected: undefined, children: undefined }, props); // Read state only from initial mount because <select> updates value // manually; we need the initial state only for server rendering if (inst._wrapperState.selected != null) { nativeProps.selected = inst._wrapperState.selected; } var content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. ReactChildren.forEach(props.children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : undefined; } }); if (content) { nativeProps.children = content; } return nativeProps; } }; module.exports = ReactDOMOption; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 116 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildren */ 'use strict'; var PooledClass = __webpack_require__(62); var ReactElement = __webpack_require__(48); var emptyFunction = __webpack_require__(21); var traverseAllChildren = __webpack_require__(117); var twoArgumentPooler = PooledClass.twoArgumentPooler; var fourArgumentPooler = PooledClass.fourArgumentPooler; var userProvidedKeyEscapeRegex = /\/(?!\/)/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '//'); } /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.func = forEachFunction; this.context = forEachContext; this.count = 0; } ForEachBookKeeping.prototype.destructor = function () { this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func; var context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) { this.result = mapResult; this.keyPrefix = keyPrefix; this.func = mapFunction; this.context = mapContext; this.count = 0; } MapBookKeeping.prototype.destructor = function () { this.result = null; this.keyPrefix = null; this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler); function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result; var keyPrefix = bookKeeping.keyPrefix; var func = bookKeeping.func; var context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument); } else if (mappedChild != null) { if (ReactElement.isValidElement(mappedChild)) { mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild !== child ? escapeUserProvidedKey(mappedChild.key || '') + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } function forEachSingleChildDummy(traverseContext, child, name) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument); return result; } var ReactChildren = { forEach: forEachChildren, map: mapChildren, mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal, count: countChildren, toArray: toArray }; module.exports = ReactChildren; /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule traverseAllChildren */ 'use strict'; var ReactCurrentOwner = __webpack_require__(11); var ReactElement = __webpack_require__(48); var ReactInstanceHandles = __webpack_require__(51); var getIteratorFn = __webpack_require__(114); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); var SEPARATOR = ReactInstanceHandles.SEPARATOR; var SUBSEPARATOR = ':'; /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var userProvidedKeyEscaperLookup = { '=': '=0', '.': '=1', ':': '=2' }; var userProvidedKeyEscapeRegex = /[=.:]/g; var didWarnAboutMaps = false; function userProvidedKeyEscaper(match) { return userProvidedKeyEscaperLookup[match]; } /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { if (component && component.key != null) { // Explicit key return wrapUserProvidedKey(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * Escape a component key so that it is safe to use in a reactid. * * @param {*} text Component key to be escaped. * @return {string} An escaped string. */ function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, userProvidedKeyEscaper); } /** * Wrap a `key` value explicitly provided by the user to distinguish it from * implicitly-generated keys generated by a component's index in its parent. * * @param {string} key Value of a user-provided `key` attribute * @return {string} */ function wrapUserProvidedKey(key) { return '$' + escapeUserProvidedKey(key); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.') : undefined; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + wrapUserProvidedKey(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if (process.env.NODE_ENV !== 'production') { addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : invariant(false) : undefined; } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } module.exports = traverseAllChildren; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelect */ 'use strict'; var LinkedValueUtils = __webpack_require__(112); var ReactMount = __webpack_require__(34); var ReactUpdates = __webpack_require__(60); var assign = __webpack_require__(45); var warning = __webpack_require__(31); var valueContextKey = '__ReactDOMSelect_value$' + Math.random().toString(36).slice(2); function updateOptionsIfPendingUpdateAndMounted() { if (this._rootNodeID && this._wrapperState.pendingUpdate) { this._wrapperState.pendingUpdate = false; var props = this._currentElement.props; var value = LinkedValueUtils.getValue(props); if (value != null) { updateOptions(this, Boolean(props.multiple), value); } } } function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } var valuePropNames = ['value', 'defaultValue']; /** * Validation function for `value` and `defaultValue`. * @private */ function checkSelectPropTypes(inst, props) { var owner = inst._currentElement._owner; LinkedValueUtils.checkPropTypes('select', props, owner); for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } if (props.multiple) { process.env.NODE_ENV !== 'production' ? warning(Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : undefined; } else { process.env.NODE_ENV !== 'production' ? warning(!Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : undefined; } } } /** * @param {ReactDOMComponent} inst * @param {boolean} multiple * @param {*} propValue A stringable (with `multiple`, a list of stringables). * @private */ function updateOptions(inst, multiple, propValue) { var selectedValue, i; var options = ReactMount.getNode(inst._rootNodeID).options; if (multiple) { selectedValue = {}; for (i = 0; i < propValue.length; i++) { selectedValue['' + propValue[i]] = true; } for (i = 0; i < options.length; i++) { var selected = selectedValue.hasOwnProperty(options[i].value); if (options[i].selected !== selected) { options[i].selected = selected; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. selectedValue = '' + propValue; for (i = 0; i < options.length; i++) { if (options[i].value === selectedValue) { options[i].selected = true; return; } } if (options.length) { options[0].selected = true; } } } /** * Implements a <select> native component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ var ReactDOMSelect = { valueContextKey: valueContextKey, getNativeProps: function (inst, props, context) { return assign({}, props, { onChange: inst._wrapperState.onChange, value: undefined }); }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { checkSelectPropTypes(inst, props); } var value = LinkedValueUtils.getValue(props); inst._wrapperState = { pendingUpdate: false, initialValue: value != null ? value : props.defaultValue, onChange: _handleChange.bind(inst), wasMultiple: Boolean(props.multiple) }; }, processChildContext: function (inst, props, context) { // Pass down initial value so initial generated markup has correct // `selected` attributes var childContext = assign({}, context); childContext[valueContextKey] = inst._wrapperState.initialValue; return childContext; }, postUpdateWrapper: function (inst) { var props = inst._currentElement.props; // After the initial mount, we control selected-ness manually so don't pass // the context value down inst._wrapperState.initialValue = undefined; var wasMultiple = inst._wrapperState.wasMultiple; inst._wrapperState.wasMultiple = Boolean(props.multiple); var value = LinkedValueUtils.getValue(props); if (value != null) { inst._wrapperState.pendingUpdate = false; updateOptions(inst, Boolean(props.multiple), value); } else if (wasMultiple !== Boolean(props.multiple)) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (props.defaultValue != null) { updateOptions(inst, Boolean(props.multiple), props.defaultValue); } else { // Revert the select back to its default unselected state. updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : ''); } } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); this._wrapperState.pendingUpdate = true; ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this); return returnValue; } module.exports = ReactDOMSelect; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextarea */ 'use strict'; var LinkedValueUtils = __webpack_require__(112); var ReactDOMIDOperations = __webpack_require__(33); var ReactUpdates = __webpack_require__(60); var assign = __webpack_require__(45); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMTextarea.updateWrapper(this); } } /** * Implements a <textarea> native component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ var ReactDOMTextarea = { getNativeProps: function (inst, props, context) { !(props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : invariant(false) : undefined; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. var nativeProps = assign({}, props, { defaultValue: undefined, value: undefined, children: inst._wrapperState.initialValue, onChange: inst._wrapperState.onChange }); return nativeProps; }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner); } var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = props.children; if (children != null) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : undefined; } !(defaultValue == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : invariant(false) : undefined; if (Array.isArray(children)) { !(children.length <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : invariant(false) : undefined; children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } var value = LinkedValueUtils.getValue(props); inst._wrapperState = { // We save the initial value so that `ReactDOMComponent` doesn't update // `textContent` (unnecessary since we update value). // The initial value can be a boolean or object so that's why it's // forced to be a string. initialValue: '' + (value != null ? value : defaultValue), onChange: _handleChange.bind(inst) }; }, updateWrapper: function (inst) { var props = inst._currentElement.props; var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value); } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); ReactUpdates.asap(forceUpdateIfMounted, this); return returnValue; } module.exports = ReactDOMTextarea; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChild * @typechecks static-only */ 'use strict'; var ReactComponentEnvironment = __webpack_require__(70); var ReactMultiChildUpdateTypes = __webpack_require__(22); var ReactCurrentOwner = __webpack_require__(11); var ReactReconciler = __webpack_require__(56); var ReactChildReconciler = __webpack_require__(121); var flattenChildren = __webpack_require__(122); /** * Updating children of a component may trigger recursive updates. The depth is * used to batch recursive updates to render markup more efficiently. * * @type {number} * @private */ var updateDepth = 0; /** * Queue of update configuration objects. * * Each object has a `type` property that is in `ReactMultiChildUpdateTypes`. * * @type {array<object>} * @private */ var updateQueue = []; /** * Queue of markup to be rendered. * * @type {array<string>} * @private */ var markupQueue = []; /** * Enqueues markup to be rendered and inserted at a supplied index. * * @param {string} parentID ID of the parent component. * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function enqueueInsertMarkup(parentID, markup, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.INSERT_MARKUP, markupIndex: markupQueue.push(markup) - 1, content: null, fromIndex: null, toIndex: toIndex }); } /** * Enqueues moving an existing element to another index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function enqueueMove(parentID, fromIndex, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.MOVE_EXISTING, markupIndex: null, content: null, fromIndex: fromIndex, toIndex: toIndex }); } /** * Enqueues removing an element at an index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Index of the element to remove. * @private */ function enqueueRemove(parentID, fromIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.REMOVE_NODE, markupIndex: null, content: null, fromIndex: fromIndex, toIndex: null }); } /** * Enqueues setting the markup of a node. * * @param {string} parentID ID of the parent component. * @param {string} markup Markup that renders into an element. * @private */ function enqueueSetMarkup(parentID, markup) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.SET_MARKUP, markupIndex: null, content: markup, fromIndex: null, toIndex: null }); } /** * Enqueues setting the text content. * * @param {string} parentID ID of the parent component. * @param {string} textContent Text content to set. * @private */ function enqueueTextContent(parentID, textContent) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.TEXT_CONTENT, markupIndex: null, content: textContent, fromIndex: null, toIndex: null }); } /** * Processes any enqueued updates. * * @private */ function processQueue() { if (updateQueue.length) { ReactComponentEnvironment.processChildrenUpdates(updateQueue, markupQueue); clearQueue(); } } /** * Clears any enqueued updates. * * @private */ function clearQueue() { updateQueue.length = 0; markupQueue.length = 0; } /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { _reconcilerInstantiateChildren: function (nestedChildren, transaction, context) { if (process.env.NODE_ENV !== 'production') { if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); } finally { ReactCurrentOwner.current = null; } } } return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); }, _reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, transaction, context) { var nextChildren; if (process.env.NODE_ENV !== 'production') { if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; nextChildren = flattenChildren(nextNestedChildrenElements); } finally { ReactCurrentOwner.current = null; } return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context); } } nextChildren = flattenChildren(nextNestedChildrenElements); return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context); }, /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildren Nested child maps. * @return {array} An array of mounted representations. * @internal */ mountChildren: function (nestedChildren, transaction, context) { var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); this._renderedChildren = children; var mountImages = []; var index = 0; for (var name in children) { if (children.hasOwnProperty(name)) { var child = children[name]; // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context); child._mountIndex = index++; mountImages.push(mountImage); } } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function (nextContent) { updateDepth++; var errorThrown = true; try { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren); // TODO: The setTextContent operation should be enough for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { this._unmountChild(prevChildren[name]); } } // Set new text content. this.setTextContent(nextContent); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { if (errorThrown) { clearQueue(); } else { processQueue(); } } } }, /** * Replaces any rendered children with a markup string. * * @param {string} nextMarkup String of markup. * @internal */ updateMarkup: function (nextMarkup) { updateDepth++; var errorThrown = true; try { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { this._unmountChildByName(prevChildren[name], name); } } this.setMarkup(nextMarkup); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { if (errorThrown) { clearQueue(); } else { processQueue(); } } } }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function (nextNestedChildrenElements, transaction, context) { updateDepth++; var errorThrown = true; try { this._updateChildren(nextNestedChildrenElements, transaction, context); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { if (errorThrown) { clearQueue(); } else { processQueue(); } } } }, /** * Improve performance by isolating this hot code path from the try/catch * block in `updateChildren`. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function (nextNestedChildrenElements, transaction, context) { var prevChildren = this._renderedChildren; var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, transaction, context); this._renderedChildren = nextChildren; if (!nextChildren && !prevChildren) { return; } var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var lastIndex = 0; var nextIndex = 0; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var nextChild = nextChildren[name]; if (prevChild === nextChild) { this.moveChild(prevChild, nextIndex, lastIndex); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); this._unmountChild(prevChild); } // The child must be instantiated before it's mounted. this._mountChildByNameAtIndex(nextChild, name, nextIndex, transaction, context); } nextIndex++; } // Remove children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { this._unmountChild(prevChildren[name]); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @internal */ unmountChildren: function () { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren); this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function (child, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { enqueueMove(this._rootNodeID, child._mountIndex, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function (child, mountImage) { enqueueInsertMarkup(this._rootNodeID, mountImage, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function (child) { enqueueRemove(this._rootNodeID, child._mountIndex); }, /** * Sets this text content string. * * @param {string} textContent Text content to set. * @protected */ setTextContent: function (textContent) { enqueueTextContent(this._rootNodeID, textContent); }, /** * Sets this markup string. * * @param {string} markup Markup to set. * @protected */ setMarkup: function (markup) { enqueueSetMarkup(this._rootNodeID, markup); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildByNameAtIndex: function (child, name, index, transaction, context) { // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context); child._mountIndex = index; this.createChild(child, mountImage); }, /** * Unmounts a rendered child. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @private */ _unmountChild: function (child) { this.removeChild(child); child._mountIndex = null; } } }; module.exports = ReactMultiChild; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildReconciler * @typechecks static-only */ 'use strict'; var ReactReconciler = __webpack_require__(56); var instantiateReactComponent = __webpack_require__(68); var shouldUpdateReactComponent = __webpack_require__(73); var traverseAllChildren = __webpack_require__(117); var warning = __webpack_require__(31); function instantiateChild(childInstances, child, name) { // We found a component instance. var keyUnique = childInstances[name] === undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined; } if (child != null && keyUnique) { childInstances[name] = instantiateReactComponent(child, null); } } /** * ReactChildReconciler provides helpers for initializing or updating a set of * children. Its output is suitable for passing it onto ReactMultiChild which * does diffed reordering and insertion. */ var ReactChildReconciler = { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildNodes Nested child maps. * @return {?object} A set of child instances. * @internal */ instantiateChildren: function (nestedChildNodes, transaction, context) { if (nestedChildNodes == null) { return null; } var childInstances = {}; traverseAllChildren(nestedChildNodes, instantiateChild, childInstances); return childInstances; }, /** * Updates the rendered children and returns a new set of children. * * @param {?object} prevChildren Previously initialized set of children. * @param {?object} nextChildren Flat child element maps. * @param {ReactReconcileTransaction} transaction * @param {object} context * @return {?object} A new set of child instances. * @internal */ updateChildren: function (prevChildren, nextChildren, transaction, context) { // We currently don't have a way to track moves here but if we use iterators // instead of for..in we can zip the iterators and check if an item has // moved. // TODO: If nothing has changed, return the prevChildren object so that we // can quickly bailout if nothing has changed. if (!nextChildren && !prevChildren) { return null; } var name; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var prevElement = prevChild && prevChild._currentElement; var nextElement = nextChildren[name]; if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) { ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context); nextChildren[name] = prevChild; } else { if (prevChild) { ReactReconciler.unmountComponent(prevChild, name); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent(nextElement, null); nextChildren[name] = nextChildInstance; } } // Unmount children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { ReactReconciler.unmountComponent(prevChildren[name]); } } return nextChildren; }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @param {?object} renderedChildren Previously initialized set of children. * @internal */ unmountChildren: function (renderedChildren) { for (var name in renderedChildren) { if (renderedChildren.hasOwnProperty(name)) { var renderedChild = renderedChildren[name]; ReactReconciler.unmountComponent(renderedChild); } } } }; module.exports = ReactChildReconciler; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 122 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule flattenChildren */ 'use strict'; var traverseAllChildren = __webpack_require__(117); var warning = __webpack_require__(31); /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. */ function flattenSingleChildIntoContext(traverseContext, child, name) { // We found a component instance. var result = traverseContext; var keyUnique = result[name] === undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined; } if (keyUnique && child != null) { result[name] = child; } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children) { if (children == null) { return children; } var result = {}; traverseAllChildren(children, flattenSingleChildIntoContext, result); return result; } module.exports = flattenChildren; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 123 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shallowEqual * @typechecks * */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var bHasOwnProperty = hasOwnProperty.bind(objB); for (var i = 0; i < keysA.length; i++) { if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } module.exports = shallowEqual; /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventListener * @typechecks static-only */ 'use strict'; var EventListener = __webpack_require__(125); var ExecutionEnvironment = __webpack_require__(15); var PooledClass = __webpack_require__(62); var ReactInstanceHandles = __webpack_require__(51); var ReactMount = __webpack_require__(34); var ReactUpdates = __webpack_require__(60); var assign = __webpack_require__(45); var getEventTarget = __webpack_require__(87); var getUnboundedScrollPosition = __webpack_require__(126); var DOCUMENT_FRAGMENT_NODE_TYPE = 11; /** * Finds the parent React component of `node`. * * @param {*} node * @return {?DOMEventTarget} Parent container, or `null` if the specified node * is not nested. */ function findParent(node) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. var nodeID = ReactMount.getID(node); var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); var container = ReactMount.findReactContainerForID(rootID); var parent = ReactMount.getFirstReactDOM(container); return parent; } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.ancestors = []; } assign(TopLevelCallbackBookKeeping.prototype, { destructor: function () { this.topLevelType = null; this.nativeEvent = null; this.ancestors.length = 0; } }); PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler); function handleTopLevelImpl(bookKeeping) { // TODO: Re-enable event.path handling // // if (bookKeeping.nativeEvent.path && bookKeeping.nativeEvent.path.length > 1) { // // New browsers have a path attribute on native events // handleTopLevelWithPath(bookKeeping); // } else { // // Legacy browsers don't have a path attribute on native events // handleTopLevelWithoutPath(bookKeeping); // } void handleTopLevelWithPath; // temporarily unused handleTopLevelWithoutPath(bookKeeping); } // Legacy browsers don't have a path attribute on native events function handleTopLevelWithoutPath(bookKeeping) { var topLevelTarget = ReactMount.getFirstReactDOM(getEventTarget(bookKeeping.nativeEvent)) || window; // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = topLevelTarget; while (ancestor) { bookKeeping.ancestors.push(ancestor); ancestor = findParent(ancestor); } for (var i = 0; i < bookKeeping.ancestors.length; i++) { topLevelTarget = bookKeeping.ancestors[i]; var topLevelTargetID = ReactMount.getID(topLevelTarget) || ''; ReactEventListener._handleTopLevel(bookKeeping.topLevelType, topLevelTarget, topLevelTargetID, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); } } // New browsers have a path attribute on native events function handleTopLevelWithPath(bookKeeping) { var path = bookKeeping.nativeEvent.path; var currentNativeTarget = path[0]; var eventsFired = 0; for (var i = 0; i < path.length; i++) { var currentPathElement = path[i]; if (currentPathElement.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE) { currentNativeTarget = path[i + 1]; } // TODO: slow var reactParent = ReactMount.getFirstReactDOM(currentPathElement); if (reactParent === currentPathElement) { var currentPathElementID = ReactMount.getID(currentPathElement); var newRootID = ReactInstanceHandles.getReactRootIDFromNodeID(currentPathElementID); bookKeeping.ancestors.push(currentPathElement); var topLevelTargetID = ReactMount.getID(currentPathElement) || ''; eventsFired++; ReactEventListener._handleTopLevel(bookKeeping.topLevelType, currentPathElement, topLevelTargetID, bookKeeping.nativeEvent, currentNativeTarget); // Jump to the root of this React render tree while (currentPathElementID !== newRootID) { i++; currentPathElement = path[i]; currentPathElementID = ReactMount.getID(currentPathElement); } } } if (eventsFired === 0) { ReactEventListener._handleTopLevel(bookKeeping.topLevelType, window, '', bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); } } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition(window); cb(scrollPosition); } var ReactEventListener = { _enabled: true, _handleTopLevel: null, WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, setHandleTopLevel: function (handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function (enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function () { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, monitorScrollValue: function (refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener.listen(window, 'scroll', callback); }, dispatchEvent: function (topLevelType, nativeEvent) { if (!ReactEventListener._enabled) { return; } var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } }; module.exports = ReactEventListener; /***/ }, /* 125 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule EventListener * @typechecks */ 'use strict'; var emptyFunction = __webpack_require__(21); /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function (target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function () { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function () { target.detachEvent('on' + eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function (target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, true); return { remove: function () { target.removeEventListener(eventType, callback, true); } }; } else { if (process.env.NODE_ENV !== 'production') { console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); } return { remove: emptyFunction }; } }, registerDefault: function () {} }; module.exports = EventListener; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 126 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getUnboundedScrollPosition * @typechecks */ 'use strict'; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable === window) { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInjection */ 'use strict'; var DOMProperty = __webpack_require__(29); var EventPluginHub = __webpack_require__(37); var ReactComponentEnvironment = __webpack_require__(70); var ReactClass = __webpack_require__(128); var ReactEmptyComponent = __webpack_require__(74); var ReactBrowserEventEmitter = __webpack_require__(35); var ReactNativeComponent = __webpack_require__(75); var ReactPerf = __webpack_require__(24); var ReactRootIndex = __webpack_require__(52); var ReactUpdates = __webpack_require__(60); var ReactInjection = { Component: ReactComponentEnvironment.injection, Class: ReactClass.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, EventEmitter: ReactBrowserEventEmitter.injection, NativeComponent: ReactNativeComponent.injection, Perf: ReactPerf.injection, RootIndex: ReactRootIndex.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactClass */ 'use strict'; var ReactComponent = __webpack_require__(129); var ReactElement = __webpack_require__(48); var ReactPropTypeLocations = __webpack_require__(71); var ReactPropTypeLocationNames = __webpack_require__(72); var ReactNoopUpdateQueue = __webpack_require__(130); var assign = __webpack_require__(45); var emptyObject = __webpack_require__(64); var invariant = __webpack_require__(19); var keyMirror = __webpack_require__(23); var keyOf = __webpack_require__(85); var warning = __webpack_require__(31); var MIXINS_KEY = keyOf({ mixins: null }); /** * Policies that describe methods in `ReactClassInterface`. */ var SpecPolicy = keyMirror({ /** * These methods may be defined only once by the class specification or mixin. */ DEFINE_ONCE: null, /** * These methods may be defined by both the class specification and mixins. * Subsequent definitions will be chained. These methods must return void. */ DEFINE_MANY: null, /** * These methods are overriding the base class. */ OVERRIDE_BASE: null, /** * These methods are similar to DEFINE_MANY, except we assume they return * objects. We try to merge the keys of the return values of all the mixed in * functions. If there is a key conflict we throw. */ DEFINE_MANY_MERGED: null }); var injectedMixins = []; var warnedSetProps = false; function warnSetProps() { if (!warnedSetProps) { warnedSetProps = true; process.env.NODE_ENV !== 'production' ? warning(false, 'setProps(...) and replaceProps(...) are deprecated. ' + 'Instead, call render again at the top level.') : undefined; } } /** * Composite components are higher-level components that compose other composite * or native components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: SpecPolicy.DEFINE_MANY, /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: SpecPolicy.DEFINE_MANY, /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: SpecPolicy.DEFINE_MANY, // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED, /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: SpecPolicy.DEFINE_MANY_MERGED, /** * @return {object} * @optional */ getChildContext: SpecPolicy.DEFINE_MANY_MERGED, /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: SpecPolicy.DEFINE_ONCE, // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: SpecPolicy.DEFINE_MANY, /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: SpecPolicy.DEFINE_MANY, /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: SpecPolicy.DEFINE_MANY, /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: SpecPolicy.DEFINE_ONCE, /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: SpecPolicy.DEFINE_MANY, // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: SpecPolicy.OVERRIDE_BASE }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function (Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function (Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function (Constructor, childContextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext); } Constructor.childContextTypes = assign({}, Constructor.childContextTypes, childContextTypes); }, contextTypes: function (Constructor, contextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context); } Constructor.contextTypes = assign({}, Constructor.contextTypes, contextTypes); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function (Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function (Constructor, propTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop); } Constructor.propTypes = assign({}, Constructor.propTypes, propTypes); }, statics: function (Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function () {} }; // noop function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an invariant so components // don't show up in prod but not in __DEV__ process.env.NODE_ENV !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : undefined; } } } function validateMethodOverride(proto, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { !(specPolicy === SpecPolicy.OVERRIDE_BASE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name) : invariant(false) : undefined; } // Disallow defining methods more than once unless explicitly allowed. if (proto.hasOwnProperty(name)) { !(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) : invariant(false) : undefined; } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classses. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { return; } !(typeof spec !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.') : invariant(false) : undefined; !!ReactElement.isValidElement(spec) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.') : invariant(false) : undefined; var proto = Constructor.prototype; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; validateMethodOverride(proto, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isAlreadyDefined = proto.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { if (!proto.__reactAutoBindMap) { proto.__reactAutoBindMap = {}; } proto.__reactAutoBindMap[name] = property; proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. !(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name) : invariant(false) : undefined; // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === SpecPolicy.DEFINE_MANY) { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if (process.env.NODE_ENV !== 'production') { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = (name in RESERVED_SPEC_KEYS); !!isReserved ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name) : invariant(false) : undefined; var isInherited = (name in Constructor); !!isInherited ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name) : invariant(false) : undefined; Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { !(one && two && typeof one === 'object' && typeof two === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : invariant(false) : undefined; for (var key in two) { if (two.hasOwnProperty(key)) { !(one[key] === undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key) : invariant(false) : undefined; one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if (process.env.NODE_ENV !== 'production') { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; /* eslint-disable block-scoped-var, no-undef */ boundMethod.bind = function (newThis) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : undefined; } else if (!args.length) { process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : undefined; return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; /* eslint-enable */ }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { for (var autoBindKey in component.__reactAutoBindMap) { if (component.__reactAutoBindMap.hasOwnProperty(autoBindKey)) { var method = component.__reactAutoBindMap[autoBindKey]; component[autoBindKey] = bindAutoBindMethod(component, method); } } } /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function (newState, callback) { this.updater.enqueueReplaceState(this, newState); if (callback) { this.updater.enqueueCallback(this, callback); } }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function () { return this.updater.isMounted(this); }, /** * Sets a subset of the props. * * @param {object} partialProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @public * @deprecated */ setProps: function (partialProps, callback) { if (process.env.NODE_ENV !== 'production') { warnSetProps(); } this.updater.enqueueSetProps(this, partialProps); if (callback) { this.updater.enqueueCallback(this, callback); } }, /** * Replace all the props. * * @param {object} newProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @public * @deprecated */ replaceProps: function (newProps, callback) { if (process.env.NODE_ENV !== 'production') { warnSetProps(); } this.updater.enqueueReplaceProps(this, newProps); if (callback) { this.updater.enqueueCallback(this, callback); } } }; var ReactClassComponent = function () {}; assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin); /** * Module for creating composite components. * * @class ReactClass */ var ReactClass = { /** * Creates a composite component class given a class specification. * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function (spec) { var Constructor = function (props, context, updater) { // This constructor is overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : undefined; } // Wire up auto-binding if (this.__reactAutoBindMap) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if (process.env.NODE_ENV !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (typeof initialState === 'undefined' && this.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : invariant(false) : undefined; this.state = initialState; }; Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if (process.env.NODE_ENV !== 'production') { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } !Constructor.prototype.render ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : invariant(false) : undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : undefined; process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : undefined; } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; }, injection: { injectMixin: function (mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactClass; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponent */ 'use strict'; var ReactNoopUpdateQueue = __webpack_require__(130); var canDefineProperty = __webpack_require__(49); var emptyObject = __webpack_require__(64); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } ReactComponent.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ ReactComponent.prototype.setState = function (partialState, callback) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.') : invariant(false) : undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : undefined; } this.updater.enqueueSetState(this, partialState); if (callback) { this.updater.enqueueCallback(this, callback); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ ReactComponent.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this); if (callback) { this.updater.enqueueCallback(this, callback); } }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if (process.env.NODE_ENV !== 'production') { var deprecatedAPIs = { getDOMNode: ['getDOMNode', 'Use ReactDOM.findDOMNode(component) instead.'], isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceProps: ['replaceProps', 'Instead, call render again at the top level.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'], setProps: ['setProps', 'Instead, call render again at the top level.'] }; var defineDeprecationWarning = function (methodName, info) { if (canDefineProperty) { Object.defineProperty(ReactComponent.prototype, methodName, { get: function () { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : undefined; return undefined; } }); } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } module.exports = ReactComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNoopUpdateQueue */ 'use strict'; var warning = __webpack_require__(31); function warnTDZ(publicInstance, callerName) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor && publicInstance.constructor.displayName || '') : undefined; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function (publicInstance, callback) {}, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { warnTDZ(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { warnTDZ(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { warnTDZ(publicInstance, 'setState'); }, /** * Sets a subset of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialProps Subset of the next props. * @internal */ enqueueSetProps: function (publicInstance, partialProps) { warnTDZ(publicInstance, 'setProps'); }, /** * Replaces all of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} props New props. * @internal */ enqueueReplaceProps: function (publicInstance, props) { warnTDZ(publicInstance, 'replaceProps'); } }; module.exports = ReactNoopUpdateQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconcileTransaction * @typechecks static-only */ 'use strict'; var CallbackQueue = __webpack_require__(61); var PooledClass = __webpack_require__(62); var ReactBrowserEventEmitter = __webpack_require__(35); var ReactDOMFeatureFlags = __webpack_require__(47); var ReactInputSelection = __webpack_require__(132); var Transaction = __webpack_require__(63); var assign = __webpack_require__(45); /** * Ensures that, when possible, the selection range (currently selected text * input) is not disturbed by performing the transaction. */ var SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection.restoreSelection }; /** * Suppresses events (blur/focus) that could be inadvertently dispatched due to * high level DOM manipulations (like temporarily removing a text input from the * DOM). */ var EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function () { var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); ReactBrowserEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occurred. `close` * restores the previous value. */ close: function (previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function () { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function () { this.reactMountReady.notifyAll(); } }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING]; /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction(forceHTML) { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.getPooled(null); this.useCreateElement = !forceHTML && ReactDOMFeatureFlags.useCreateElement; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap procedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return this.reactMountReady; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; } }; assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInputSelection */ 'use strict'; var ReactDOMSelection = __webpack_require__(133); var containsNode = __webpack_require__(65); var focusNode = __webpack_require__(101); var getActiveElement = __webpack_require__(135); function isInDocument(node) { return containsNode(document.documentElement, node); } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ var ReactInputSelection = { hasSelectionCapabilities: function (elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); }, getSelectionInformation: function () { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function (priorSelectionInformation) { var curFocusedElem = getActiveElement(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange); } focusNode(priorFocusedElem); } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function (input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || { start: 0, end: 0 }; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function (input, offsets) { var start = offsets.start; var end = offsets.end; if (typeof end === 'undefined') { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end - start); range.select(); } else { ReactDOMSelection.setOffsets(input, offsets); } } }; module.exports = ReactInputSelection; /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelection */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var getNodeForCharacterOffset = __webpack_require__(134); var getTextContentAccessor = __webpack_require__(81); /** * While `isCollapsed` is available on the Selection object and `collapsed` * is available on the Range object, IE11 sometimes gets them wrong. * If the anchor/focus nodes and offsets are the same, the range is collapsed. */ function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { return anchorNode === focusNode && anchorOffset === focusOffset; } /** * Get the appropriate anchor and focus node/offset pairs for IE. * * The catch here is that IE's selection API doesn't provide information * about whether the selection is forward or backward, so we have to * behave as though it's always forward. * * IE text differs from modern selection in that it behaves as though * block elements end with a new line. This means character offsets will * differ between the two APIs. * * @param {DOMElement} node * @return {object} */ function getIEOffsets(node) { var selection = document.selection; var selectedRange = selection.createRange(); var selectedLength = selectedRange.text.length; // Duplicate selection so we can move range without breaking user selection. var fromStart = selectedRange.duplicate(); fromStart.moveToElementText(node); fromStart.setEndPoint('EndToStart', selectedRange); var startOffset = fromStart.text.length; var endOffset = startOffset + selectedLength; return { start: startOffset, end: endOffset }; } /** * @param {DOMElement} node * @return {?object} */ function getModernOffsets(node) { var selection = window.getSelection && window.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode; var anchorOffset = selection.anchorOffset; var focusNode = selection.focusNode; var focusOffset = selection.focusOffset; var currentRange = selection.getRangeAt(0); // In Firefox, range.startContainer and range.endContainer can be "anonymous // divs", e.g. the up/down buttons on an <input type="number">. Anonymous // divs do not seem to expose properties, triggering a "Permission denied // error" if any of its properties are accessed. The only seemingly possible // way to avoid erroring is to access a property that typically works for // non-anonymous divs and catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ currentRange.startContainer.nodeType; currentRange.endContainer.nodeType; /* eslint-enable no-unused-expressions */ } catch (e) { return null; } // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset); var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var range = document.selection.createRange().duplicate(); var start, end; if (typeof offsets.end === 'undefined') { start = offsets.start; end = start; } else if (offsets.start > offsets.end) { start = offsets.end; end = offsets.start; } else { start = offsets.start; end = offsets.end; } range.moveToElementText(node); range.moveStart('character', start); range.setEndPoint('EndToStart', range); range.moveEnd('character', end - start); range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (!window.getSelection) { return; } var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = typeof offsets.end === 'undefined' ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window); var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; /***/ }, /* 134 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getNodeForCharacterOffset */ 'use strict'; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === 3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } module.exports = getNodeForCharacterOffset; /***/ }, /* 135 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getActiveElement * @typechecks */ /* eslint-disable fb-www/typeof-undefined */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document or document body is not * yet defined. */ 'use strict'; function getActiveElement() /*?DOMElement*/{ if (typeof document === 'undefined') { return null; } try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SelectEventPlugin */ 'use strict'; var EventConstants = __webpack_require__(36); var EventPropagators = __webpack_require__(79); var ExecutionEnvironment = __webpack_require__(15); var ReactInputSelection = __webpack_require__(132); var SyntheticEvent = __webpack_require__(83); var getActiveElement = __webpack_require__(135); var isTextInputElement = __webpack_require__(88); var keyOf = __webpack_require__(85); var shallowEqual = __webpack_require__(123); var topLevelTypes = EventConstants.topLevelTypes; var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11; var eventTypes = { select: { phasedRegistrationNames: { bubbled: keyOf({ onSelect: null }), captured: keyOf({ onSelectCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange] } }; var activeElement = null; var activeElementID = null; var lastSelection = null; var mouseDown = false; // Track whether a listener exists for this plugin. If none exist, we do // not extract events. var hasListener = false; var ON_SELECT_KEY = keyOf({ onSelect: null }); /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @return {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementID, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { if (!hasListener) { return null; } switch (topLevelType) { // Track the input node that has focus. case topLevelTypes.topFocus: if (isTextInputElement(topLevelTarget) || topLevelTarget.contentEditable === 'true') { activeElement = topLevelTarget; activeElementID = topLevelTargetID; lastSelection = null; } break; case topLevelTypes.topBlur: activeElement = null; activeElementID = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case topLevelTypes.topMouseDown: mouseDown = true; break; case topLevelTypes.topContextMenu: case topLevelTypes.topMouseUp: mouseDown = false; return constructSelectEvent(nativeEvent, nativeEventTarget); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case topLevelTypes.topSelectionChange: if (skipSelectionChangeEvent) { break; } // falls through case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: return constructSelectEvent(nativeEvent, nativeEventTarget); } return null; }, didPutListener: function (id, registrationName, listener) { if (registrationName === ON_SELECT_KEY) { hasListener = true; } } }; module.exports = SelectEventPlugin; /***/ }, /* 137 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ServerReactRootIndex * @typechecks */ 'use strict'; /** * Size of the reactRoot ID space. We generate random numbers for React root * IDs and if there's a collision the events and DOM update system will * get confused. In the future we need a way to generate GUIDs but for * now this will work on a smaller scale. */ var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53); var ServerReactRootIndex = { createReactRootIndex: function () { return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX); } }; module.exports = ServerReactRootIndex; /***/ }, /* 138 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SimpleEventPlugin */ 'use strict'; var EventConstants = __webpack_require__(36); var EventListener = __webpack_require__(125); var EventPropagators = __webpack_require__(79); var ReactMount = __webpack_require__(34); var SyntheticClipboardEvent = __webpack_require__(139); var SyntheticEvent = __webpack_require__(83); var SyntheticFocusEvent = __webpack_require__(140); var SyntheticKeyboardEvent = __webpack_require__(141); var SyntheticMouseEvent = __webpack_require__(92); var SyntheticDragEvent = __webpack_require__(144); var SyntheticTouchEvent = __webpack_require__(145); var SyntheticUIEvent = __webpack_require__(93); var SyntheticWheelEvent = __webpack_require__(146); var emptyFunction = __webpack_require__(21); var getEventCharCode = __webpack_require__(142); var invariant = __webpack_require__(19); var keyOf = __webpack_require__(85); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { abort: { phasedRegistrationNames: { bubbled: keyOf({ onAbort: true }), captured: keyOf({ onAbortCapture: true }) } }, blur: { phasedRegistrationNames: { bubbled: keyOf({ onBlur: true }), captured: keyOf({ onBlurCapture: true }) } }, canPlay: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlay: true }), captured: keyOf({ onCanPlayCapture: true }) } }, canPlayThrough: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlayThrough: true }), captured: keyOf({ onCanPlayThroughCapture: true }) } }, click: { phasedRegistrationNames: { bubbled: keyOf({ onClick: true }), captured: keyOf({ onClickCapture: true }) } }, contextMenu: { phasedRegistrationNames: { bubbled: keyOf({ onContextMenu: true }), captured: keyOf({ onContextMenuCapture: true }) } }, copy: { phasedRegistrationNames: { bubbled: keyOf({ onCopy: true }), captured: keyOf({ onCopyCapture: true }) } }, cut: { phasedRegistrationNames: { bubbled: keyOf({ onCut: true }), captured: keyOf({ onCutCapture: true }) } }, doubleClick: { phasedRegistrationNames: { bubbled: keyOf({ onDoubleClick: true }), captured: keyOf({ onDoubleClickCapture: true }) } }, drag: { phasedRegistrationNames: { bubbled: keyOf({ onDrag: true }), captured: keyOf({ onDragCapture: true }) } }, dragEnd: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnd: true }), captured: keyOf({ onDragEndCapture: true }) } }, dragEnter: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnter: true }), captured: keyOf({ onDragEnterCapture: true }) } }, dragExit: { phasedRegistrationNames: { bubbled: keyOf({ onDragExit: true }), captured: keyOf({ onDragExitCapture: true }) } }, dragLeave: { phasedRegistrationNames: { bubbled: keyOf({ onDragLeave: true }), captured: keyOf({ onDragLeaveCapture: true }) } }, dragOver: { phasedRegistrationNames: { bubbled: keyOf({ onDragOver: true }), captured: keyOf({ onDragOverCapture: true }) } }, dragStart: { phasedRegistrationNames: { bubbled: keyOf({ onDragStart: true }), captured: keyOf({ onDragStartCapture: true }) } }, drop: { phasedRegistrationNames: { bubbled: keyOf({ onDrop: true }), captured: keyOf({ onDropCapture: true }) } }, durationChange: { phasedRegistrationNames: { bubbled: keyOf({ onDurationChange: true }), captured: keyOf({ onDurationChangeCapture: true }) } }, emptied: { phasedRegistrationNames: { bubbled: keyOf({ onEmptied: true }), captured: keyOf({ onEmptiedCapture: true }) } }, encrypted: { phasedRegistrationNames: { bubbled: keyOf({ onEncrypted: true }), captured: keyOf({ onEncryptedCapture: true }) } }, ended: { phasedRegistrationNames: { bubbled: keyOf({ onEnded: true }), captured: keyOf({ onEndedCapture: true }) } }, error: { phasedRegistrationNames: { bubbled: keyOf({ onError: true }), captured: keyOf({ onErrorCapture: true }) } }, focus: { phasedRegistrationNames: { bubbled: keyOf({ onFocus: true }), captured: keyOf({ onFocusCapture: true }) } }, input: { phasedRegistrationNames: { bubbled: keyOf({ onInput: true }), captured: keyOf({ onInputCapture: true }) } }, keyDown: { phasedRegistrationNames: { bubbled: keyOf({ onKeyDown: true }), captured: keyOf({ onKeyDownCapture: true }) } }, keyPress: { phasedRegistrationNames: { bubbled: keyOf({ onKeyPress: true }), captured: keyOf({ onKeyPressCapture: true }) } }, keyUp: { phasedRegistrationNames: { bubbled: keyOf({ onKeyUp: true }), captured: keyOf({ onKeyUpCapture: true }) } }, load: { phasedRegistrationNames: { bubbled: keyOf({ onLoad: true }), captured: keyOf({ onLoadCapture: true }) } }, loadedData: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedData: true }), captured: keyOf({ onLoadedDataCapture: true }) } }, loadedMetadata: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedMetadata: true }), captured: keyOf({ onLoadedMetadataCapture: true }) } }, loadStart: { phasedRegistrationNames: { bubbled: keyOf({ onLoadStart: true }), captured: keyOf({ onLoadStartCapture: true }) } }, // Note: We do not allow listening to mouseOver events. Instead, use the // onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`. mouseDown: { phasedRegistrationNames: { bubbled: keyOf({ onMouseDown: true }), captured: keyOf({ onMouseDownCapture: true }) } }, mouseMove: { phasedRegistrationNames: { bubbled: keyOf({ onMouseMove: true }), captured: keyOf({ onMouseMoveCapture: true }) } }, mouseOut: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOut: true }), captured: keyOf({ onMouseOutCapture: true }) } }, mouseOver: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOver: true }), captured: keyOf({ onMouseOverCapture: true }) } }, mouseUp: { phasedRegistrationNames: { bubbled: keyOf({ onMouseUp: true }), captured: keyOf({ onMouseUpCapture: true }) } }, paste: { phasedRegistrationNames: { bubbled: keyOf({ onPaste: true }), captured: keyOf({ onPasteCapture: true }) } }, pause: { phasedRegistrationNames: { bubbled: keyOf({ onPause: true }), captured: keyOf({ onPauseCapture: true }) } }, play: { phasedRegistrationNames: { bubbled: keyOf({ onPlay: true }), captured: keyOf({ onPlayCapture: true }) } }, playing: { phasedRegistrationNames: { bubbled: keyOf({ onPlaying: true }), captured: keyOf({ onPlayingCapture: true }) } }, progress: { phasedRegistrationNames: { bubbled: keyOf({ onProgress: true }), captured: keyOf({ onProgressCapture: true }) } }, rateChange: { phasedRegistrationNames: { bubbled: keyOf({ onRateChange: true }), captured: keyOf({ onRateChangeCapture: true }) } }, reset: { phasedRegistrationNames: { bubbled: keyOf({ onReset: true }), captured: keyOf({ onResetCapture: true }) } }, scroll: { phasedRegistrationNames: { bubbled: keyOf({ onScroll: true }), captured: keyOf({ onScrollCapture: true }) } }, seeked: { phasedRegistrationNames: { bubbled: keyOf({ onSeeked: true }), captured: keyOf({ onSeekedCapture: true }) } }, seeking: { phasedRegistrationNames: { bubbled: keyOf({ onSeeking: true }), captured: keyOf({ onSeekingCapture: true }) } }, stalled: { phasedRegistrationNames: { bubbled: keyOf({ onStalled: true }), captured: keyOf({ onStalledCapture: true }) } }, submit: { phasedRegistrationNames: { bubbled: keyOf({ onSubmit: true }), captured: keyOf({ onSubmitCapture: true }) } }, suspend: { phasedRegistrationNames: { bubbled: keyOf({ onSuspend: true }), captured: keyOf({ onSuspendCapture: true }) } }, timeUpdate: { phasedRegistrationNames: { bubbled: keyOf({ onTimeUpdate: true }), captured: keyOf({ onTimeUpdateCapture: true }) } }, touchCancel: { phasedRegistrationNames: { bubbled: keyOf({ onTouchCancel: true }), captured: keyOf({ onTouchCancelCapture: true }) } }, touchEnd: { phasedRegistrationNames: { bubbled: keyOf({ onTouchEnd: true }), captured: keyOf({ onTouchEndCapture: true }) } }, touchMove: { phasedRegistrationNames: { bubbled: keyOf({ onTouchMove: true }), captured: keyOf({ onTouchMoveCapture: true }) } }, touchStart: { phasedRegistrationNames: { bubbled: keyOf({ onTouchStart: true }), captured: keyOf({ onTouchStartCapture: true }) } }, volumeChange: { phasedRegistrationNames: { bubbled: keyOf({ onVolumeChange: true }), captured: keyOf({ onVolumeChangeCapture: true }) } }, waiting: { phasedRegistrationNames: { bubbled: keyOf({ onWaiting: true }), captured: keyOf({ onWaitingCapture: true }) } }, wheel: { phasedRegistrationNames: { bubbled: keyOf({ onWheel: true }), captured: keyOf({ onWheelCapture: true }) } } }; var topLevelEventsToDispatchConfig = { topAbort: eventTypes.abort, topBlur: eventTypes.blur, topCanPlay: eventTypes.canPlay, topCanPlayThrough: eventTypes.canPlayThrough, topClick: eventTypes.click, topContextMenu: eventTypes.contextMenu, topCopy: eventTypes.copy, topCut: eventTypes.cut, topDoubleClick: eventTypes.doubleClick, topDrag: eventTypes.drag, topDragEnd: eventTypes.dragEnd, topDragEnter: eventTypes.dragEnter, topDragExit: eventTypes.dragExit, topDragLeave: eventTypes.dragLeave, topDragOver: eventTypes.dragOver, topDragStart: eventTypes.dragStart, topDrop: eventTypes.drop, topDurationChange: eventTypes.durationChange, topEmptied: eventTypes.emptied, topEncrypted: eventTypes.encrypted, topEnded: eventTypes.ended, topError: eventTypes.error, topFocus: eventTypes.focus, topInput: eventTypes.input, topKeyDown: eventTypes.keyDown, topKeyPress: eventTypes.keyPress, topKeyUp: eventTypes.keyUp, topLoad: eventTypes.load, topLoadedData: eventTypes.loadedData, topLoadedMetadata: eventTypes.loadedMetadata, topLoadStart: eventTypes.loadStart, topMouseDown: eventTypes.mouseDown, topMouseMove: eventTypes.mouseMove, topMouseOut: eventTypes.mouseOut, topMouseOver: eventTypes.mouseOver, topMouseUp: eventTypes.mouseUp, topPaste: eventTypes.paste, topPause: eventTypes.pause, topPlay: eventTypes.play, topPlaying: eventTypes.playing, topProgress: eventTypes.progress, topRateChange: eventTypes.rateChange, topReset: eventTypes.reset, topScroll: eventTypes.scroll, topSeeked: eventTypes.seeked, topSeeking: eventTypes.seeking, topStalled: eventTypes.stalled, topSubmit: eventTypes.submit, topSuspend: eventTypes.suspend, topTimeUpdate: eventTypes.timeUpdate, topTouchCancel: eventTypes.touchCancel, topTouchEnd: eventTypes.touchEnd, topTouchMove: eventTypes.touchMove, topTouchStart: eventTypes.touchStart, topVolumeChange: eventTypes.volumeChange, topWaiting: eventTypes.waiting, topWheel: eventTypes.wheel }; for (var type in topLevelEventsToDispatchConfig) { topLevelEventsToDispatchConfig[type].dependencies = [type]; } var ON_CLICK_KEY = keyOf({ onClick: null }); var onClickListeners = {}; var SimpleEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case topLevelTypes.topAbort: case topLevelTypes.topCanPlay: case topLevelTypes.topCanPlayThrough: case topLevelTypes.topDurationChange: case topLevelTypes.topEmptied: case topLevelTypes.topEncrypted: case topLevelTypes.topEnded: case topLevelTypes.topError: case topLevelTypes.topInput: case topLevelTypes.topLoad: case topLevelTypes.topLoadedData: case topLevelTypes.topLoadedMetadata: case topLevelTypes.topLoadStart: case topLevelTypes.topPause: case topLevelTypes.topPlay: case topLevelTypes.topPlaying: case topLevelTypes.topProgress: case topLevelTypes.topRateChange: case topLevelTypes.topReset: case topLevelTypes.topSeeked: case topLevelTypes.topSeeking: case topLevelTypes.topStalled: case topLevelTypes.topSubmit: case topLevelTypes.topSuspend: case topLevelTypes.topTimeUpdate: case topLevelTypes.topVolumeChange: case topLevelTypes.topWaiting: // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case topLevelTypes.topKeyPress: // FireFox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return null; } /* falls through */ case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: EventConstructor = SyntheticKeyboardEvent; break; case topLevelTypes.topBlur: case topLevelTypes.topFocus: EventConstructor = SyntheticFocusEvent; break; case topLevelTypes.topClick: // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case topLevelTypes.topContextMenu: case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break; case topLevelTypes.topDrag: case topLevelTypes.topDragEnd: case topLevelTypes.topDragEnter: case topLevelTypes.topDragExit: case topLevelTypes.topDragLeave: case topLevelTypes.topDragOver: case topLevelTypes.topDragStart: case topLevelTypes.topDrop: EventConstructor = SyntheticDragEvent; break; case topLevelTypes.topTouchCancel: case topLevelTypes.topTouchEnd: case topLevelTypes.topTouchMove: case topLevelTypes.topTouchStart: EventConstructor = SyntheticTouchEvent; break; case topLevelTypes.topScroll: EventConstructor = SyntheticUIEvent; break; case topLevelTypes.topWheel: EventConstructor = SyntheticWheelEvent; break; case topLevelTypes.topCopy: case topLevelTypes.topCut: case topLevelTypes.topPaste: EventConstructor = SyntheticClipboardEvent; break; } !EventConstructor ? process.env.NODE_ENV !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : invariant(false) : undefined; var event = EventConstructor.getPooled(dispatchConfig, topLevelTargetID, nativeEvent, nativeEventTarget); EventPropagators.accumulateTwoPhaseDispatches(event); return event; }, didPutListener: function (id, registrationName, listener) { // Mobile Safari does not fire properly bubble click events on // non-interactive elements, which means delegated click listeners do not // fire. The workaround for this bug involves attaching an empty click // listener on the target node. if (registrationName === ON_CLICK_KEY) { var node = ReactMount.getNode(id); if (!onClickListeners[id]) { onClickListeners[id] = EventListener.listen(node, 'click', emptyFunction); } } }, willDeleteListener: function (id, registrationName) { if (registrationName === ON_CLICK_KEY) { onClickListeners[id].remove(); delete onClickListeners[id]; } } }; module.exports = SimpleEventPlugin; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticClipboardEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = __webpack_require__(83); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = { clipboardData: function (event) { return 'clipboardData' in event ? event.clipboardData : window.clipboardData; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticFocusEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = __webpack_require__(93); /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = { relatedTarget: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticKeyboardEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = __webpack_require__(93); var getEventCharCode = __webpack_require__(142); var getEventKey = __webpack_require__(143); var getEventModifierState = __webpack_require__(94); /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = { key: getEventKey, location: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, repeat: null, locale: null, getModifierState: getEventModifierState, // Legacy Interface charCode: function (event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode(event); } return 0; }, keyCode: function (event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function (event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; /***/ }, /* 142 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventCharCode * @typechecks static-only */ 'use strict'; /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } module.exports = getEventCharCode; /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventKey * @typechecks static-only */ 'use strict'; var getEventCharCode = __webpack_require__(142); /** * Normalization of deprecated HTML5 `key` values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var normalizeKey = { 'Esc': 'Escape', 'Spacebar': ' ', 'Left': 'ArrowLeft', 'Up': 'ArrowUp', 'Right': 'ArrowRight', 'Down': 'ArrowDown', 'Del': 'Delete', 'Win': 'OS', 'Menu': 'ContextMenu', 'Apps': 'ContextMenu', 'Scroll': 'ScrollLock', 'MozPrintableKey': 'Unidentified' }; /** * Translation from legacy `keyCode` to HTML5 `key` * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var translateToKey = { 8: 'Backspace', 9: 'Tab', 12: 'Clear', 13: 'Enter', 16: 'Shift', 17: 'Control', 18: 'Alt', 19: 'Pause', 20: 'CapsLock', 27: 'Escape', 32: ' ', 33: 'PageUp', 34: 'PageDown', 35: 'End', 36: 'Home', 37: 'ArrowLeft', 38: 'ArrowUp', 39: 'ArrowRight', 40: 'ArrowDown', 45: 'Insert', 46: 'Delete', 112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6', 118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12', 144: 'NumLock', 145: 'ScrollLock', 224: 'Meta' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } module.exports = getEventKey; /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticDragEvent * @typechecks static-only */ 'use strict'; var SyntheticMouseEvent = __webpack_require__(92); /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = { dataTransfer: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticTouchEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = __webpack_require__(93); var getEventModifierState = __webpack_require__(94); /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = { touches: null, targetTouches: null, changedTouches: null, altKey: null, metaKey: null, ctrlKey: null, shiftKey: null, getModifierState: getEventModifierState }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticWheelEvent * @typechecks static-only */ 'use strict'; var SyntheticMouseEvent = __webpack_require__(92); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = { deltaX: function (event) { return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; }, deltaY: function (event) { return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0; }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SVGDOMPropertyConfig */ 'use strict'; var DOMProperty = __webpack_require__(29); var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; var NS = { xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace' }; var SVGDOMPropertyConfig = { Properties: { clipPath: MUST_USE_ATTRIBUTE, cx: MUST_USE_ATTRIBUTE, cy: MUST_USE_ATTRIBUTE, d: MUST_USE_ATTRIBUTE, dx: MUST_USE_ATTRIBUTE, dy: MUST_USE_ATTRIBUTE, fill: MUST_USE_ATTRIBUTE, fillOpacity: MUST_USE_ATTRIBUTE, fontFamily: MUST_USE_ATTRIBUTE, fontSize: MUST_USE_ATTRIBUTE, fx: MUST_USE_ATTRIBUTE, fy: MUST_USE_ATTRIBUTE, gradientTransform: MUST_USE_ATTRIBUTE, gradientUnits: MUST_USE_ATTRIBUTE, markerEnd: MUST_USE_ATTRIBUTE, markerMid: MUST_USE_ATTRIBUTE, markerStart: MUST_USE_ATTRIBUTE, offset: MUST_USE_ATTRIBUTE, opacity: MUST_USE_ATTRIBUTE, patternContentUnits: MUST_USE_ATTRIBUTE, patternUnits: MUST_USE_ATTRIBUTE, points: MUST_USE_ATTRIBUTE, preserveAspectRatio: MUST_USE_ATTRIBUTE, r: MUST_USE_ATTRIBUTE, rx: MUST_USE_ATTRIBUTE, ry: MUST_USE_ATTRIBUTE, spreadMethod: MUST_USE_ATTRIBUTE, stopColor: MUST_USE_ATTRIBUTE, stopOpacity: MUST_USE_ATTRIBUTE, stroke: MUST_USE_ATTRIBUTE, strokeDasharray: MUST_USE_ATTRIBUTE, strokeLinecap: MUST_USE_ATTRIBUTE, strokeOpacity: MUST_USE_ATTRIBUTE, strokeWidth: MUST_USE_ATTRIBUTE, textAnchor: MUST_USE_ATTRIBUTE, transform: MUST_USE_ATTRIBUTE, version: MUST_USE_ATTRIBUTE, viewBox: MUST_USE_ATTRIBUTE, x1: MUST_USE_ATTRIBUTE, x2: MUST_USE_ATTRIBUTE, x: MUST_USE_ATTRIBUTE, xlinkActuate: MUST_USE_ATTRIBUTE, xlinkArcrole: MUST_USE_ATTRIBUTE, xlinkHref: MUST_USE_ATTRIBUTE, xlinkRole: MUST_USE_ATTRIBUTE, xlinkShow: MUST_USE_ATTRIBUTE, xlinkTitle: MUST_USE_ATTRIBUTE, xlinkType: MUST_USE_ATTRIBUTE, xmlBase: MUST_USE_ATTRIBUTE, xmlLang: MUST_USE_ATTRIBUTE, xmlSpace: MUST_USE_ATTRIBUTE, y1: MUST_USE_ATTRIBUTE, y2: MUST_USE_ATTRIBUTE, y: MUST_USE_ATTRIBUTE }, DOMAttributeNamespaces: { xlinkActuate: NS.xlink, xlinkArcrole: NS.xlink, xlinkHref: NS.xlink, xlinkRole: NS.xlink, xlinkShow: NS.xlink, xlinkTitle: NS.xlink, xlinkType: NS.xlink, xmlBase: NS.xml, xmlLang: NS.xml, xmlSpace: NS.xml }, DOMAttributeNames: { clipPath: 'clip-path', fillOpacity: 'fill-opacity', fontFamily: 'font-family', fontSize: 'font-size', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', patternContentUnits: 'patternContentUnits', patternUnits: 'patternUnits', preserveAspectRatio: 'preserveAspectRatio', spreadMethod: 'spreadMethod', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strokeDasharray: 'stroke-dasharray', strokeLinecap: 'stroke-linecap', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', textAnchor: 'text-anchor', viewBox: 'viewBox', xlinkActuate: 'xlink:actuate', xlinkArcrole: 'xlink:arcrole', xlinkHref: 'xlink:href', xlinkRole: 'xlink:role', xlinkShow: 'xlink:show', xlinkTitle: 'xlink:title', xlinkType: 'xlink:type', xmlBase: 'xml:base', xmlLang: 'xml:lang', xmlSpace: 'xml:space' } }; module.exports = SVGDOMPropertyConfig; /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultPerf * @typechecks static-only */ 'use strict'; var DOMProperty = __webpack_require__(29); var ReactDefaultPerfAnalysis = __webpack_require__(149); var ReactMount = __webpack_require__(34); var ReactPerf = __webpack_require__(24); var performanceNow = __webpack_require__(150); function roundFloat(val) { return Math.floor(val * 100) / 100; } function addValue(obj, key, val) { obj[key] = (obj[key] || 0) + val; } var ReactDefaultPerf = { _allMeasurements: [], // last item in the list is the current one _mountStack: [0], _injected: false, start: function () { if (!ReactDefaultPerf._injected) { ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure); } ReactDefaultPerf._allMeasurements.length = 0; ReactPerf.enableMeasure = true; }, stop: function () { ReactPerf.enableMeasure = false; }, getLastMeasurements: function () { return ReactDefaultPerf._allMeasurements; }, printExclusive: function (measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements); console.table(summary.map(function (item) { return { 'Component class name': item.componentName, 'Total inclusive time (ms)': roundFloat(item.inclusive), 'Exclusive mount time (ms)': roundFloat(item.exclusive), 'Exclusive render time (ms)': roundFloat(item.render), 'Mount time per instance (ms)': roundFloat(item.exclusive / item.count), 'Render time per instance (ms)': roundFloat(item.render / item.count), 'Instances': item.count }; })); // TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct // number. }, printInclusive: function (measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements); console.table(summary.map(function (item) { return { 'Owner > component': item.componentName, 'Inclusive time (ms)': roundFloat(item.time), 'Instances': item.count }; })); console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'); }, getMeasurementsSummaryMap: function (measurements) { var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements, true); return summary.map(function (item) { return { 'Owner > component': item.componentName, 'Wasted time (ms)': item.time, 'Instances': item.count }; }); }, printWasted: function (measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; console.table(ReactDefaultPerf.getMeasurementsSummaryMap(measurements)); console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'); }, printDOM: function (measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements); console.table(summary.map(function (item) { var result = {}; result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id; result.type = item.type; result.args = JSON.stringify(item.args); return result; })); console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'); }, _recordWrite: function (id, fnName, totalTime, args) { // TODO: totalTime isn't that useful since it doesn't count paints/reflows var writes = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].writes; writes[id] = writes[id] || []; writes[id].push({ type: fnName, time: totalTime, args: args }); }, measure: function (moduleName, fnName, func) { return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var totalTime; var rv; var start; if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') { // A "measurement" is a set of metrics recorded for each flush. We want // to group the metrics for a given flush together so we can look at the // components that rendered and the DOM operations that actually // happened to determine the amount of "wasted work" performed. ReactDefaultPerf._allMeasurements.push({ exclusive: {}, inclusive: {}, render: {}, counts: {}, writes: {}, displayNames: {}, totalTime: 0, created: {} }); start = performanceNow(); rv = func.apply(this, args); ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].totalTime = performanceNow() - start; return rv; } else if (fnName === '_mountImageIntoNode' || moduleName === 'ReactBrowserEventEmitter' || moduleName === 'ReactDOMIDOperations' || moduleName === 'CSSPropertyOperations' || moduleName === 'DOMChildrenOperations' || moduleName === 'DOMPropertyOperations') { start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (fnName === '_mountImageIntoNode') { var mountID = ReactMount.getID(args[1]); ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]); } else if (fnName === 'dangerouslyProcessChildrenUpdates') { // special format args[0].forEach(function (update) { var writeArgs = {}; if (update.fromIndex !== null) { writeArgs.fromIndex = update.fromIndex; } if (update.toIndex !== null) { writeArgs.toIndex = update.toIndex; } if (update.textContent !== null) { writeArgs.textContent = update.textContent; } if (update.markupIndex !== null) { writeArgs.markup = args[1][update.markupIndex]; } ReactDefaultPerf._recordWrite(update.parentID, update.type, totalTime, writeArgs); }); } else { // basic format var id = args[0]; if (typeof id === 'object') { id = ReactMount.getID(args[0]); } ReactDefaultPerf._recordWrite(id, fnName, totalTime, Array.prototype.slice.call(args, 1)); } return rv; } else if (moduleName === 'ReactCompositeComponent' && (fnName === 'mountComponent' || fnName === 'updateComponent' || // TODO: receiveComponent()? fnName === '_renderValidatedComponent')) { if (this._currentElement.type === ReactMount.TopLevelWrapper) { return func.apply(this, args); } var rootNodeID = fnName === 'mountComponent' ? args[0] : this._rootNodeID; var isRender = fnName === '_renderValidatedComponent'; var isMount = fnName === 'mountComponent'; var mountStack = ReactDefaultPerf._mountStack; var entry = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1]; if (isRender) { addValue(entry.counts, rootNodeID, 1); } else if (isMount) { entry.created[rootNodeID] = true; mountStack.push(0); } start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (isRender) { addValue(entry.render, rootNodeID, totalTime); } else if (isMount) { var subMountTime = mountStack.pop(); mountStack[mountStack.length - 1] += totalTime; addValue(entry.exclusive, rootNodeID, totalTime - subMountTime); addValue(entry.inclusive, rootNodeID, totalTime); } else { addValue(entry.inclusive, rootNodeID, totalTime); } entry.displayNames[rootNodeID] = { current: this.getName(), owner: this._currentElement._owner ? this._currentElement._owner.getName() : '<root>' }; return rv; } else { return func.apply(this, args); } }; } }; module.exports = ReactDefaultPerf; /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultPerfAnalysis */ 'use strict'; var assign = __webpack_require__(45); // Don't try to save users less than 1.2ms (a number I made up) var DONT_CARE_THRESHOLD = 1.2; var DOM_OPERATION_TYPES = { '_mountImageIntoNode': 'set innerHTML', INSERT_MARKUP: 'set innerHTML', MOVE_EXISTING: 'move', REMOVE_NODE: 'remove', SET_MARKUP: 'set innerHTML', TEXT_CONTENT: 'set textContent', 'setValueForProperty': 'update attribute', 'setValueForAttribute': 'update attribute', 'deleteValueForProperty': 'remove attribute', 'setValueForStyles': 'update styles', 'replaceNodeWithMarkup': 'replace', 'updateTextContent': 'set textContent' }; function getTotalTime(measurements) { // TODO: return number of DOM ops? could be misleading. // TODO: measure dropped frames after reconcile? // TODO: log total time of each reconcile and the top-level component // class that triggered it. var totalTime = 0; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; totalTime += measurement.totalTime; } return totalTime; } function getDOMSummary(measurements) { var items = []; measurements.forEach(function (measurement) { Object.keys(measurement.writes).forEach(function (id) { measurement.writes[id].forEach(function (write) { items.push({ id: id, type: DOM_OPERATION_TYPES[write.type] || write.type, args: write.args }); }); }); }); return items; } function getExclusiveSummary(measurements) { var candidates = {}; var displayName; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = assign({}, measurement.exclusive, measurement.inclusive); for (var id in allIDs) { displayName = measurement.displayNames[id].current; candidates[displayName] = candidates[displayName] || { componentName: displayName, inclusive: 0, exclusive: 0, render: 0, count: 0 }; if (measurement.render[id]) { candidates[displayName].render += measurement.render[id]; } if (measurement.exclusive[id]) { candidates[displayName].exclusive += measurement.exclusive[id]; } if (measurement.inclusive[id]) { candidates[displayName].inclusive += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[displayName].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (displayName in candidates) { if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) { arr.push(candidates[displayName]); } } arr.sort(function (a, b) { return b.exclusive - a.exclusive; }); return arr; } function getInclusiveSummary(measurements, onlyClean) { var candidates = {}; var inclusiveKey; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = assign({}, measurement.exclusive, measurement.inclusive); var cleanComponents; if (onlyClean) { cleanComponents = getUnchangedComponents(measurement); } for (var id in allIDs) { if (onlyClean && !cleanComponents[id]) { continue; } var displayName = measurement.displayNames[id]; // Inclusive time is not useful for many components without knowing where // they are instantiated. So we aggregate inclusive time with both the // owner and current displayName as the key. inclusiveKey = displayName.owner + ' > ' + displayName.current; candidates[inclusiveKey] = candidates[inclusiveKey] || { componentName: inclusiveKey, time: 0, count: 0 }; if (measurement.inclusive[id]) { candidates[inclusiveKey].time += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[inclusiveKey].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (inclusiveKey in candidates) { if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) { arr.push(candidates[inclusiveKey]); } } arr.sort(function (a, b) { return b.time - a.time; }); return arr; } function getUnchangedComponents(measurement) { // For a given reconcile, look at which components did not actually // render anything to the DOM and return a mapping of their ID to // the amount of time it took to render the entire subtree. var cleanComponents = {}; var dirtyLeafIDs = Object.keys(measurement.writes); var allIDs = assign({}, measurement.exclusive, measurement.inclusive); for (var id in allIDs) { var isDirty = false; // For each component that rendered, see if a component that triggered // a DOM op is in its subtree. for (var i = 0; i < dirtyLeafIDs.length; i++) { if (dirtyLeafIDs[i].indexOf(id) === 0) { isDirty = true; break; } } // check if component newly created if (measurement.created[id]) { isDirty = true; } if (!isDirty && measurement.counts[id] > 0) { cleanComponents[id] = true; } } return cleanComponents; } var ReactDefaultPerfAnalysis = { getExclusiveSummary: getExclusiveSummary, getInclusiveSummary: getInclusiveSummary, getDOMSummary: getDOMSummary, getTotalTime: getTotalTime }; module.exports = ReactDefaultPerfAnalysis; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule performanceNow * @typechecks */ 'use strict'; var performance = __webpack_require__(151); var performanceNow; /** * Detect if we can use `window.performance.now()` and gracefully fallback to * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now * because of Facebook's testing infrastructure. */ if (performance.now) { performanceNow = function () { return performance.now(); }; } else { performanceNow = function () { return Date.now(); }; } module.exports = performanceNow; /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule performance * @typechecks */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var performance; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.msPerformance || window.webkitPerformance; } module.exports = performance || {}; /***/ }, /* 152 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactVersion */ 'use strict'; module.exports = '0.14.7'; /***/ }, /* 153 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule renderSubtreeIntoContainer */ 'use strict'; var ReactMount = __webpack_require__(34); module.exports = ReactMount.renderSubtreeIntoContainer; /***/ }, /* 154 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMServer */ 'use strict'; var ReactDefaultInjection = __webpack_require__(77); var ReactServerRendering = __webpack_require__(155); var ReactVersion = __webpack_require__(152); ReactDefaultInjection.inject(); var ReactDOMServer = { renderToString: ReactServerRendering.renderToString, renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup, version: ReactVersion }; module.exports = ReactDOMServer; /***/ }, /* 155 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks static-only * @providesModule ReactServerRendering */ 'use strict'; var ReactDefaultBatchingStrategy = __webpack_require__(98); var ReactElement = __webpack_require__(48); var ReactInstanceHandles = __webpack_require__(51); var ReactMarkupChecksum = __webpack_require__(54); var ReactServerBatchingStrategy = __webpack_require__(156); var ReactServerRenderingTransaction = __webpack_require__(157); var ReactUpdates = __webpack_require__(60); var emptyObject = __webpack_require__(64); var instantiateReactComponent = __webpack_require__(68); var invariant = __webpack_require__(19); /** * @param {ReactElement} element * @return {string} the HTML markup */ function renderToString(element) { !ReactElement.isValidElement(element) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : invariant(false) : undefined; var transaction; try { ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(false); return transaction.perform(function () { var componentInstance = instantiateReactComponent(element, null); var markup = componentInstance.mountComponent(id, transaction, emptyObject); return ReactMarkupChecksum.addChecksumToMarkup(markup); }, null); } finally { ReactServerRenderingTransaction.release(transaction); // Revert to the DOM batching strategy since these two renderers // currently share these stateful modules. ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); } } /** * @param {ReactElement} element * @return {string} the HTML markup, without the extra React ID and checksum * (for generating static pages) */ function renderToStaticMarkup(element) { !ReactElement.isValidElement(element) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : invariant(false) : undefined; var transaction; try { ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(true); return transaction.perform(function () { var componentInstance = instantiateReactComponent(element, null); return componentInstance.mountComponent(id, transaction, emptyObject); }, null); } finally { ReactServerRenderingTransaction.release(transaction); // Revert to the DOM batching strategy since these two renderers // currently share these stateful modules. ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); } } module.exports = { renderToString: renderToString, renderToStaticMarkup: renderToStaticMarkup }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 156 */ /***/ function(module, exports) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerBatchingStrategy * @typechecks */ 'use strict'; var ReactServerBatchingStrategy = { isBatchingUpdates: false, batchedUpdates: function (callback) { // Don't do anything here. During the server rendering we don't want to // schedule any updates. We will simply ignore them. } }; module.exports = ReactServerBatchingStrategy; /***/ }, /* 157 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerRenderingTransaction * @typechecks */ 'use strict'; var PooledClass = __webpack_require__(62); var CallbackQueue = __webpack_require__(61); var Transaction = __webpack_require__(63); var assign = __webpack_require__(45); var emptyFunction = __webpack_require__(21); /** * Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks * during the performing of the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function () { this.reactMountReady.reset(); }, close: emptyFunction }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [ON_DOM_READY_QUEUEING]; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.reactMountReady = CallbackQueue.getPooled(null); this.useCreateElement = false; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap procedures. */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return this.reactMountReady; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; } }; assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; /***/ }, /* 158 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactIsomorphic */ 'use strict'; var ReactChildren = __webpack_require__(116); var ReactComponent = __webpack_require__(129); var ReactClass = __webpack_require__(128); var ReactDOMFactories = __webpack_require__(159); var ReactElement = __webpack_require__(48); var ReactElementValidator = __webpack_require__(160); var ReactPropTypes = __webpack_require__(113); var ReactVersion = __webpack_require__(152); var assign = __webpack_require__(45); var onlyChild = __webpack_require__(162); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; var cloneElement = ReactElement.cloneElement; if (process.env.NODE_ENV !== 'production') { createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; cloneElement = ReactElementValidator.cloneElement; } var React = { // Modern Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, toArray: ReactChildren.toArray, only: onlyChild }, Component: ReactComponent, createElement: createElement, cloneElement: cloneElement, isValidElement: ReactElement.isValidElement, // Classic PropTypes: ReactPropTypes, createClass: ReactClass.createClass, createFactory: createFactory, createMixin: function (mixin) { // Currently a noop. Will be used to validate and trace mixins. return mixin; }, // This looks DOM specific but these are actually isomorphic helpers // since they are just generating DOM strings. DOM: ReactDOMFactories, version: ReactVersion, // Hook for JSX spread, don't use this for anything else. __spread: assign }; module.exports = React; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMFactories * @typechecks static-only */ 'use strict'; var ReactElement = __webpack_require__(48); var ReactElementValidator = __webpack_require__(160); var mapObject = __webpack_require__(161); /** * Create a factory that creates HTML tag elements. * * @param {string} tag Tag name (e.g. `div`). * @private */ function createDOMFactory(tag) { if (process.env.NODE_ENV !== 'production') { return ReactElementValidator.createFactory(tag); } return ReactElement.createFactory(tag); } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOMFactories = mapObject({ a: 'a', abbr: 'abbr', address: 'address', area: 'area', article: 'article', aside: 'aside', audio: 'audio', b: 'b', base: 'base', bdi: 'bdi', bdo: 'bdo', big: 'big', blockquote: 'blockquote', body: 'body', br: 'br', button: 'button', canvas: 'canvas', caption: 'caption', cite: 'cite', code: 'code', col: 'col', colgroup: 'colgroup', data: 'data', datalist: 'datalist', dd: 'dd', del: 'del', details: 'details', dfn: 'dfn', dialog: 'dialog', div: 'div', dl: 'dl', dt: 'dt', em: 'em', embed: 'embed', fieldset: 'fieldset', figcaption: 'figcaption', figure: 'figure', footer: 'footer', form: 'form', h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', h5: 'h5', h6: 'h6', head: 'head', header: 'header', hgroup: 'hgroup', hr: 'hr', html: 'html', i: 'i', iframe: 'iframe', img: 'img', input: 'input', ins: 'ins', kbd: 'kbd', keygen: 'keygen', label: 'label', legend: 'legend', li: 'li', link: 'link', main: 'main', map: 'map', mark: 'mark', menu: 'menu', menuitem: 'menuitem', meta: 'meta', meter: 'meter', nav: 'nav', noscript: 'noscript', object: 'object', ol: 'ol', optgroup: 'optgroup', option: 'option', output: 'output', p: 'p', param: 'param', picture: 'picture', pre: 'pre', progress: 'progress', q: 'q', rp: 'rp', rt: 'rt', ruby: 'ruby', s: 's', samp: 'samp', script: 'script', section: 'section', select: 'select', small: 'small', source: 'source', span: 'span', strong: 'strong', style: 'style', sub: 'sub', summary: 'summary', sup: 'sup', table: 'table', tbody: 'tbody', td: 'td', textarea: 'textarea', tfoot: 'tfoot', th: 'th', thead: 'thead', time: 'time', title: 'title', tr: 'tr', track: 'track', u: 'u', ul: 'ul', 'var': 'var', video: 'video', wbr: 'wbr', // SVG circle: 'circle', clipPath: 'clipPath', defs: 'defs', ellipse: 'ellipse', g: 'g', image: 'image', line: 'line', linearGradient: 'linearGradient', mask: 'mask', path: 'path', pattern: 'pattern', polygon: 'polygon', polyline: 'polyline', radialGradient: 'radialGradient', rect: 'rect', stop: 'stop', svg: 'svg', text: 'text', tspan: 'tspan' }, createDOMFactory); module.exports = ReactDOMFactories; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElementValidator */ /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ 'use strict'; var ReactElement = __webpack_require__(48); var ReactPropTypeLocations = __webpack_require__(71); var ReactPropTypeLocationNames = __webpack_require__(72); var ReactCurrentOwner = __webpack_require__(11); var canDefineProperty = __webpack_require__(49); var getIteratorFn = __webpack_require__(114); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; var loggedTypeFailures = {}; /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var addenda = getAddendaForKeyUse('uniqueKey', element, parentType); if (addenda === null) { // we already showed the warning return; } process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s%s', addenda.parentOrOwner || '', addenda.childOwner || '', addenda.url || '') : undefined; } /** * Shared warning and monitoring code for the key warnings. * * @internal * @param {string} messageType A key used for de-duping warnings. * @param {ReactElement} element Component that requires a key. * @param {*} parentType element's parent's type. * @returns {?object} A set of addenda to use in the warning message, or null * if the warning has already been shown before (and shouldn't be shown again). */ function getAddendaForKeyUse(messageType, element, parentType) { var addendum = getDeclarationErrorAddendum(); if (!addendum) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { addendum = ' Check the top-level render call using <' + parentName + '>.'; } } var memoizer = ownerHasKeyUseWarning[messageType] || (ownerHasKeyUseWarning[messageType] = {}); if (memoizer[addendum]) { return null; } memoizer[addendum] = true; var addenda = { parentOrOwner: addendum, url: ' See https://fb.me/react-warning-keys for more information.', childOwner: null }; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. addenda.childOwner = ' It was passed a child from ' + element._owner.getName() + '.'; } return addenda; } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); // Entry iterators provide implicit keys. if (iteratorFn) { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (ReactElement.isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Assert that the props are valid * * @param {string} componentName Name of the component for error messages. * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ function checkPropTypes(componentName, propTypes, props, location) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof propTypes[propName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined; error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], propName, typeof error) : undefined; if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(); process.env.NODE_ENV !== 'production' ? warning(false, 'Failed propType: %s%s', error.message, addendum) : undefined; } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { var componentClass = element.type; if (typeof componentClass !== 'function') { return; } var name = componentClass.displayName || componentClass.name; if (componentClass.propTypes) { checkPropTypes(name, componentClass.propTypes, element.props, ReactPropTypeLocations.prop); } if (typeof componentClass.getDefaultProps === 'function') { process.env.NODE_ENV !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : undefined; } } var ReactElementValidator = { createElement: function (type, props, children) { var validType = typeof type === 'string' || typeof type === 'function'; // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. process.env.NODE_ENV !== 'production' ? warning(validType, 'React.createElement: type should not be null, undefined, boolean, or ' + 'number. It should be a string (for DOM elements) or a ReactClass ' + '(for composite components).%s', getDeclarationErrorAddendum()) : undefined; var element = ReactElement.createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } validatePropTypes(element); return element; }, createFactory: function (type) { var validatedFactory = ReactElementValidator.createElement.bind(null, type); // Legacy hook TODO: Warn if this is accessed validatedFactory.type = type; if (process.env.NODE_ENV !== 'production') { if (canDefineProperty) { Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { process.env.NODE_ENV !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : undefined; Object.defineProperty(this, 'type', { value: type }); return type; } }); } } return validatedFactory; }, cloneElement: function (element, props, children) { var newElement = ReactElement.cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } }; module.exports = ReactElementValidator; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 161 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule mapObject */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Executes the provided `callback` once for each enumerable own property in the * object and constructs a new object from the results. The `callback` is * invoked with three arguments: * * - the property value * - the property name * - the object being traversed * * Properties that are added after the call to `mapObject` will not be visited * by `callback`. If the values of existing properties are changed, the value * passed to `callback` will be the value at the time `mapObject` visits them. * Properties that are deleted before being visited are not visited. * * @grep function objectMap() * @grep function objMap() * * @param {?object} object * @param {function} callback * @param {*} context * @return {?object} */ function mapObject(object, callback, context) { if (!object) { return null; } var result = {}; for (var name in object) { if (hasOwnProperty.call(object, name)) { result[name] = callback.call(context, object[name], name, object); } } return result; } module.exports = mapObject; /***/ }, /* 162 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule onlyChild */ 'use strict'; var ReactElement = __webpack_require__(48); var invariant = __webpack_require__(19); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. The current implementation of this * function assumes that a single child gets passed without a wrapper, but the * purpose of this helper function is to abstract away the particular structure * of children. * * @param {?object} children Child collection structure. * @return {ReactComponent} The first and only `ReactComponent` contained in the * structure. */ function onlyChild(children) { !ReactElement.isValidElement(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'onlyChild must be passed a children with exactly one child.') : invariant(false) : undefined; return children; } module.exports = onlyChild; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 163 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule deprecated */ 'use strict'; var assign = __webpack_require__(45); var warning = __webpack_require__(31); /** * This will log a single deprecation notice per function and forward the call * on to the new API. * * @param {string} fnName The name of the function * @param {string} newModule The module that fn will exist in * @param {string} newPackage The module that fn will exist in * @param {*} ctx The context this forwarded call should run in * @param {function} fn The function to forward on to * @return {function} The function that will warn once and then call fn */ function deprecated(fnName, newModule, newPackage, ctx, fn) { var warned = false; if (process.env.NODE_ENV !== 'production') { var newFn = function () { process.env.NODE_ENV !== 'production' ? warning(warned, // Require examples in this string must be split to prevent React's // build tools from mistaking them for real requires. // Otherwise the build tools will attempt to build a '%s' module. 'React.%s is deprecated. Please use %s.%s from require' + '(\'%s\') ' + 'instead.', fnName, newModule, fnName, newPackage) : undefined; warned = true; return fn.apply(ctx, arguments); }; // We need to make sure all properties of the original fn are copied over. // In particular, this is needed to support PropTypes return assign(newFn, fn); } return fn; } module.exports = deprecated; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 164 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin module.exports = {"handle":"react-ios-switch-Switch-handle","input":"react-ios-switch-Switch-input","offState":"react-ios-switch-Switch-offState","switch":"react-ios-switch-Switch-switch","switch--disabled":"react-ios-switch-Switch-switch--disabled"}; /***/ } /******/ ]) }); ;
ajax/libs/jquery/1.6.2/jquery.min.js
koggdal/cdnjs
/*! * jQuery JavaScript Library v1.6.2 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu Jun 30 14:16:56 2011 -0400 */ (function(a,b){function cv(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cs(a){if(!cg[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ch||(ch=c.createElement("iframe"),ch.frameBorder=ch.width=ch.height=0),b.appendChild(ch);if(!ci||!ch.createElement)ci=(ch.contentWindow||ch.contentDocument).document,ci.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),ci.close();d=ci.createElement(a),ci.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ch)}cg[a]=e}return cg[a]}function cr(a,b){var c={};f.each(cm.concat.apply([],cm.slice(0,b)),function(){c[this]=a});return c}function cq(){cn=b}function cp(){setTimeout(cq,0);return cn=f.now()}function cf(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ce(){try{return new a.XMLHttpRequest}catch(b){}}function b$(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 bZ(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 bY(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bC.test(a)?d(a,e):bY(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)bY(a+"["+e+"]",b[e],c,d);else d(a,b)}function bX(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===bR,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=bX(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bX(a,c,d,e,"*",g));return l}function bW(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bN),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 bA(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bv:bw;if(d>0){c!=="border"&&f.each(e,function(){c||(d-=parseFloat(f.css(a,"padding"+this))||0),c==="margin"?d+=parseFloat(f.css(a,c+this))||0:d-=parseFloat(f.css(a,"border"+this+"Width"))||0});return d+"px"}d=bx(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0,c&&f.each(e,function(){d+=parseFloat(f.css(a,"padding"+this))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+this+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+this))||0)});return d+"px"}function bm(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(be,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bl(a){f.nodeName(a,"input")?bk(a):"getElementsByTagName"in a&&f.grep(a.getElementsByTagName("input"),bk)}function bk(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bj(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function bi(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 bh(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c=f.expando,d=f.data(a),e=f.data(b,d);if(d=d[c]){var g=d.events;e=e[c]=f.extend({},d);if(g){delete e.handle,e.events={};for(var h in g)for(var i=0,j=g[h].length;i<j;i++)f.event.add(b,h+(g[h][i].namespace?".":"")+g[h][i].namespace,g[h][i],g[h][i].data)}}}}function bg(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function W(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(R.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 V(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function N(a,b){return(a&&a!=="*"?a+".":"")+b.replace(z,"`").replace(A,"&")}function M(a){var b,c,d,e,g,h,i,j,k,l,m,n,o,p=[],q=[],r=f._data(this,"events");if(!(a.liveFired===this||!r||!r.live||a.target.disabled||a.button&&a.type==="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var s=r.live.slice(0);for(i=0;i<s.length;i++)g=s[i],g.origType.replace(x,"")===a.type?q.push(g.selector):s.splice(i--,1);e=f(a.target).closest(q,a.currentTarget);for(j=0,k=e.length;j<k;j++){m=e[j];for(i=0;i<s.length;i++){g=s[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,d=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,d=f(a.relatedTarget).closest(g.selector)[0],d&&f.contains(h,d)&&(d=h);(!d||d!==h)&&p.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=p.length;j<k;j++){e=p[j];if(c&&e.level>c)break;a.currentTarget=e.elem,a.data=e.handleObj.data,a.handleObj=e.handleObj,o=e.handleObj.origHandler.apply(e.elem,arguments);if(o===!1||a.isPropagationStopped()){c=e.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}function K(a,c,d){var e=f.extend({},d[0]);e.type=a,e.originalEvent={},e.liveFired=b,f.event.handle.call(c,e),e.isDefaultPrevented()&&d[0].preventDefault()}function E(){return!0}function D(){return!1}function m(a,c,d){var e=c+"defer",g=c+"queue",h=c+"mark",i=f.data(a,e,b,!0);i&&(d==="queue"||!f.data(a,g,b,!0))&&(d==="mark"||!f.data(a,h,b,!0))&&setTimeout(function(){!f.data(a,g,b,!0)&&!f.data(a,h,b,!0)&&(f.removeData(a,e,!0),i.resolve())},0)}function l(a){for(var b in a)if(b!=="toJSON")return!1;return!0}function k(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(j,"$1-$2").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNaN(d)?i.test(d)?f.parseJSON(d):d:parseFloat(d)}catch(g){}f.data(a,c,d)}else d=b}return d}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=/\d/,n=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,o=/^[\],:{}\s]*$/,p=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,q=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,r=/(?:^|:|,)(?:\s*\[)+/g,s=/(webkit)[ \/]([\w.]+)/,t=/(opera)(?:.*version)?[ \/]([\w.]+)/,u=/(msie) ([\w.]+)/,v=/(mozilla)(?:.*? rv:([\w.]+))?/,w=/-([a-z])/ig,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=n.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.6.2",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.done(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(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.resolveWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!A){A=e._Deferred();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},isNaN:function(a){return a==null||!m.test(a)||isNaN(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;if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1;var c;for(c in a);return c===b||D.call(a,c)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(o.test(b.replace(p,"@").replace(q,"]").replace(r,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(b,c,d){a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b)),d=c.documentElement,(!d||!d.nodeName||d.nodeName==="parsererror")&&e.error("Invalid XML: "+b);return c},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,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){if(H)return H.call(b,a);for(var c=0,d=b.length;c<d;c++)if(b[c]===a)return c;return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,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=s.exec(a)||t.exec(a)||u.exec(a)||a.indexOf("compatible")<0&&v.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="done fail isResolved isRejected promise then always pipe".split(" "),h=[].slice;f.extend({_Deferred:function(){var a=[],b,c,d,e={done:function(){if(!d){var c=arguments,g,h,i,j,k;b&&(k=b,b=0);for(g=0,h=c.length;g<h;g++)i=c[g],j=f.type(i),j==="array"?e.done.apply(e,i):j==="function"&&a.push(i);k&&e.resolveWith(k[0],k[1])}return this},resolveWith:function(e,f){if(!d&&!b&&!c){f=f||[],c=1;try{while(a[0])a.shift().apply(e,f)}finally{b=[e,f],c=0}}return this},resolve:function(){e.resolveWith(this,arguments);return this},isResolved:function(){return!!c||!!b},cancel:function(){d=1,a=[];return this}};return e},Deferred:function(a){var b=f._Deferred(),c=f._Deferred(),d;f.extend(b,{then:function(a,c){b.done(a).fail(c);return this},always:function(){return b.done.apply(b,arguments).fail.apply(this,arguments)},fail:c.done,rejectWith:c.resolveWith,reject:c.resolve,isRejected:c.isResolved,pipe:function(a,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[c,"reject"]},function(a,c){var e=c[0],g=c[1],h;f.isFunction(e)?b[a](function(){h=e.apply(this,arguments),h&&f.isFunction(h.promise)?h.promise().then(d.resolve,d.reject):d[g](h)}):b[a](d[g])})}).promise()},promise:function(a){if(a==null){if(d)return d;d=a={}}var c=g.length;while(c--)a[g[c]]=b[g[c]];return a}}),b.done(c.cancel).fail(b.cancel),delete b.cancel,a&&a.call(b,b);return b},when:function(a){function i(a){return function(c){b[a]=arguments.length>1?h.call(arguments,0):c,--e||g.resolveWith(g,h.call(b,0))}}var b=arguments,c=0,d=b.length,e=d,g=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred();if(d>1){for(;c<d;c++)b[c]&&f.isFunction(b[c].promise)?b[c].promise().then(i(c),g.reject):--e;e||g.resolveWith(g,b)}else g!==a&&g.resolveWith(g,d?[a]:[]);return g.promise()}}),f.support=function(){var a=c.createElement("div"),b=c.documentElement,d,e,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;a.setAttribute("className","t"),a.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=a.getElementsByTagName("*"),e=a.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=a.getElementsByTagName("input")[0],k={leadingWhitespace:a.firstChild.nodeType===3,tbody:!a.getElementsByTagName("tbody").length,htmlSerialize:!!a.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:a.className!=="t",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,k.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,k.optDisabled=!h.disabled;try{delete a.test}catch(v){k.deleteExpando=!1}!a.addEventListener&&a.attachEvent&&a.fireEvent&&(a.attachEvent("onclick",function(){k.noCloneEvent=!1}),a.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),k.radioValue=i.value==="t",i.setAttribute("checked","checked"),a.appendChild(i),l=c.createDocumentFragment(),l.appendChild(a.firstChild),k.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,a.innerHTML="",a.style.width=a.style.paddingLeft="1px",m=c.getElementsByTagName("body")[0],o=c.createElement(m?"div":"body"),p={visibility:"hidden",width:0,height:0,border:0,margin:0},m&&f.extend(p,{position:"absolute",left:-1e3,top:-1e3});for(t in p)o.style[t]=p[t];o.appendChild(a),n=m||b,n.insertBefore(o,n.firstChild),k.appendChecked=i.checked,k.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,k.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",k.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",q=a.getElementsByTagName("td"),u=q[0].offsetHeight===0,q[0].style.display="",q[1].style.display="none",k.reliableHiddenOffsets=u&&q[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",a.appendChild(j),k.reliableMarginRight=(parseInt((c.defaultView.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0),o.innerHTML="",n.removeChild(o);if(a.attachEvent)for(t in{submit:1,change:1,focusin:1})s="on"+t,u=s in a,u||(a.setAttribute(s,"return;"),u=typeof a[s]=="function"),k[t+"Bubbles"]=u;o=l=g=h=m=j=a=i=null;return k}(),f.boxModel=f.support.boxModel;var i=/^(?:\{.*\}|\[.*\])$/,j=/([a-z])([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&&!l(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g=f.expando,h=typeof c=="string",i,j=a.nodeType,k=j?f.cache:a,l=j?a[f.expando]:a[f.expando]&&f.expando;if((!l||e&&l&&!k[l][g])&&h&&d===b)return;l||(j?a[f.expando]=l=++f.uuid:l=f.expando),k[l]||(k[l]={},j||(k[l].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?k[l][g]=f.extend(k[l][g],c):k[l]=f.extend(k[l],c);i=k[l],e&&(i[g]||(i[g]={}),i=i[g]),d!==b&&(i[f.camelCase(c)]=d);if(c==="events"&&!i[c])return i[g]&&i[g].events;return h?i[f.camelCase(c)]||i[c]:i}},removeData:function(b,c,d){if(!!f.acceptData(b)){var e=f.expando,g=b.nodeType,h=g?f.cache:b,i=g?b[f.expando]:f.expando;if(!h[i])return;if(c){var j=d?h[i][e]:h[i];if(j){delete j[c];if(!l(j))return}}if(d){delete h[i][e];if(!l(h[i]))return}var k=h[i][e];f.support.deleteExpando||h!=a?delete h[i]:h[i]=null,k?(h[i]={},g||(h[i].toJSON=f.noop),h[i][e]=k):g&&(f.support.deleteExpando?delete b[f.expando]:b.removeAttribute?b.removeAttribute(f.expando):b[f.expando]=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=null;if(typeof a=="undefined"){if(this.length){d=f.data(this[0]);if(this[0].nodeType===1){var e=this[0].attributes,g;for(var h=0,i=e.length;h<i;h++)g=e[h].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),k(this[0],g,d[g]))}}return d}if(typeof a=="object")return this.each(function(){f.data(this,a)});var j=a.split(".");j[1]=j[1]?"."+j[1]:"";if(c===b){d=this.triggerHandler("getData"+j[1]+"!",[j[0]]),d===b&&this.length&&(d=f.data(this[0],a),d=k(this[0],a,d));return d===b&&j[1]?this.data(j[0]):d}return this.each(function(){var b=f(this),d=[j[0],c];b.triggerHandler("setData"+j[1]+"!",d),f.data(this,a,c),b.triggerHandler("changeData"+j[1]+"!",d)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,c){a&&(c=(c||"fx")+"mark",f.data(a,c,(f.data(a,c,b,!0)||0)+1,!0))},_unmark:function(a,c,d){a!==!0&&(d=c,c=a,a=!1);if(c){d=d||"fx";var e=d+"mark",g=a?0:(f.data(c,e,b,!0)||1)-1;g?f.data(c,e,g,!0):(f.removeData(c,e,!0),m(c,d,"mark"))}},queue:function(a,c,d){if(a){c=(c||"fx")+"queue";var e=f.data(a,c,b,!0);d&&(!e||f.isArray(d)?e=f.data(a,c,f.makeArray(d),!0):e.push(d));return e||[]}},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"),d.call(a,function(){f.dequeue(a,b)})),c.length||(f.removeData(a,b+"queue",!0),m(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(){var c=this;setTimeout(function(){f.dequeue(c,b)},a)})},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._Deferred(),!0))h++,l.done(m);m();return d.promise()}});var n=/[\n\t\r]/g,o=/\s+/,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=/\:|^on/,v,w;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(o);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(o);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(n," ");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(o);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+" ";for(var c=0,d=this.length;c<d;c++)if((" "+this[c].className+" ").replace(n," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e=this[0];if(!arguments.length){if(e){c=f.valHooks[e.nodeName.toLowerCase()]||f.valHooks[e.type];if(c&&"get"in c&&(d=c.get(e,"value"))!==b)return d;d=e.value;return typeof d=="string"?d.replace(p,""):d==null?"":d}return b}var g=f.isFunction(a);return this.each(function(d){var e=f(this),h;if(this.nodeType===1){g?h=a.call(this,d,e.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}})}}),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=a.selectedIndex,d=[],e=a.options,g=a.type==="select-one";if(c<0)return null;for(var h=g?c:0,i=g?c+1:e.length;h<i;h++){var j=e[h];if(j.selected&&(f.support.optDisabled?!j.disabled:j.getAttribute("disabled")===null)&&(!j.parentNode.disabled||!f.nodeName(j.parentNode,"optgroup"))){b=f(j).val();if(g)return b;d.push(b)}}if(g&&!d.length&&e.length)return f(e[c]).val();return d},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},attrFix:{tabindex:"tabIndex"},attr:function(a,c,d,e){var g=a.nodeType;if(!a||g===3||g===8||g===2)return b;if(e&&c in f.attrFn)return f(a)[c](d);if(!("getAttribute"in a))return f.prop(a,c,d);var h,i,j=g!==1||!f.isXMLDoc(a);j&&(c=f.attrFix[c]||c,i=f.attrHooks[c],i||(t.test(c)?i=w:v&&c!=="className"&&(f.nodeName(a,"form")||u.test(c))&&(i=v)));if(d!==b){if(d===null){f.removeAttr(a,c);return b}if(i&&"set"in i&&j&&(h=i.set(a,d,c))!==b)return h;a.setAttribute(c,""+d);return d}if(i&&"get"in i&&j&&(h=i.get(a,c))!==null)return h;h=a.getAttribute(c);return h===null?b:h},removeAttr:function(a,b){var c;a.nodeType===1&&(b=f.attrFix[b]||b,f.support.getSetAttribute?a.removeAttribute(b):(f.attr(a,b,""),a.removeAttributeNode(a.getAttributeNode(b))),t.test(b)&&(c=f.propFix[b]||b)in a&&(a[c]=!1))},attrHooks:{type:{set:function(a,b){if(q.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}}},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}},value:{get:function(a,b){if(v&&f.nodeName(a,"button"))return v.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(v&&f.nodeName(a,"button"))return v.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=a.nodeType;if(!a||e===3||e===8||e===2)return b;var g,h,i=e!==1||!f.isXMLDoc(a);i&&(c=f.propFix[c]||c,h=f.propHooks[c]);return d!==b?h&&"set"in h&&(g=h.set(a,d,c))!==b?g:a[c]=d:h&&"get"in h&&(g=h.get(a,c))!==b?g:a[c]},propHooks:{}}),w={get:function(a,c){return f.prop(a,c)?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}},f.support.getSetAttribute||(f.attrFix=f.propFix,v=f.attrHooks.name=f.attrHooks.title=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&d.nodeValue!==""?d.nodeValue:b},set:function(a,b,c){var d=a.getAttributeNode(c);if(d){d.nodeValue=b;return b}}},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.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)}})),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 x=/\.(.*)$/,y=/^(?:textarea|input|select)$/i,z=/\./g,A=/ /g,B=/[^\w\s.|`]/g,C=function(a){return a.replace(B,"\\$&")};f.event={add:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){if(d===!1)d=D;else if(!d)return;var g,h;d.handler&&(g=d,d=g.handler),d.guid||(d.guid=f.guid++);var i=f._data(a);if(!i)return;var j=i.events,k=i.handle;j||(i.events=j={}),k||(i.handle=k=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.handle.apply(k.elem,arguments):b}),k.elem=a,c=c.split(" ");var l,m=0,n;while(l=c[m++]){h=g?f.extend({},g):{handler:d,data:e},l.indexOf(".")>-1?(n=l.split("."),l=n.shift(),h.namespace=n.slice(0).sort().join(".")):(n=[],h.namespace=""),h.type=l,h.guid||(h.guid=d.guid);var o=j[l],p=f.event.special[l]||{};if(!o){o=j[l]=[];if(!p.setup||p.setup.call(a,e,n,k)===!1)a.addEventListener?a.addEventListener(l,k,!1):a.attachEvent&&a.attachEvent("on"+l,k)}p.add&&(p.add.call(a,h),h.handler.guid||(h.handler.guid=d.guid)),o.push(h),f.event.global[l]=!0}a=null}},global:{},remove:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){d===!1&&(d=D);var g,h,i,j,k=0,l,m,n,o,p,q,r,s=f.hasData(a)&&f._data(a),t=s&&s.events;if(!s||!t)return;c&&c.type&&(d=c.handler,c=c.type);if(!c||typeof c=="string"&&c.charAt(0)==="."){c=c||"";for(h in t)f.event.remove(a,h+c);return}c=c.split(" ");while(h=c[k++]){r=h,q=null,l=h.indexOf(".")<0,m=[],l||(m=h.split("."),h=m.shift(),n=new RegExp("(^|\\.)"+f.map(m.slice(0).sort(),C).join("\\.(?:.*\\.)?")+"(\\.|$)")),p=t[h];if(!p)continue;if(!d){for(j=0;j<p.length;j++){q=p[j];if(l||n.test(q.namespace))f.event.remove(a,r,q.handler,j),p.splice(j--,1)}continue}o=f.event.special[h]||{};for(j=e||0;j<p.length;j++){q=p[j];if(d.guid===q.guid){if(l||n.test(q.namespace))e==null&&p.splice(j--,1),o.remove&&o.remove.call(a,q);if(e!=null)break}}if(p.length===0||e!=null&&p.length===1)(!o.teardown||o.teardown.call(a,m)===!1)&&f.removeEvent(a,h,s.handle),g=null,delete t[h]}if(f.isEmptyObject(t)){var u=s.handle;u&&(u.elem=null),delete s.events,delete s.handle,f.isEmptyObject(s)&&f.removeData(a,b,!0)}}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){var h=c.type||c,i=[],j;h.indexOf("!")>=0&&(h=h.slice(0,-1),j=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i. shift(),i.sort());if(!!e&&!f.event.customEvent[h]||!!f.event.global[h]){c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.exclusive=j,c.namespace=i.join("."),c.namespace_re=new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)");if(g||!e)c.preventDefault(),c.stopPropagation();if(!e){f.each(f.cache,function(){var a=f.expando,b=this[a];b&&b.events&&b.events[h]&&f.event.trigger(c,d,b.handle.elem)});return}if(e.nodeType===3||e.nodeType===8)return;c.result=b,c.target=e,d=d!=null?f.makeArray(d):[],d.unshift(c);var k=e,l=h.indexOf(":")<0?"on"+h:"";do{var m=f._data(k,"handle");c.currentTarget=k,m&&m.apply(k,d),l&&f.acceptData(k)&&k[l]&&k[l].apply(k,d)===!1&&(c.result=!1,c.preventDefault()),k=k.parentNode||k.ownerDocument||k===c.target.ownerDocument&&a}while(k&&!c.isPropagationStopped());if(!c.isDefaultPrevented()){var n,o=f.event.special[h]||{};if((!o._default||o._default.call(e.ownerDocument,c)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)){try{l&&e[h]&&(n=e[l],n&&(e[l]=null),f.event.triggered=h,e[h]())}catch(p){}n&&(e[l]=n),f.event.triggered=b}}return c.result}},handle:function(c){c=f.event.fix(c||a.event);var d=((f._data(this,"events")||{})[c.type]||[]).slice(0),e=!c.exclusive&&!c.namespace,g=Array.prototype.slice.call(arguments,0);g[0]=c,c.currentTarget=this;for(var h=0,i=d.length;h<i;h++){var j=d[h];if(e||c.namespace_re.test(j.namespace)){c.handler=j.handler,c.data=j.data,c.handleObj=j;var k=j.handler.apply(this,g);k!==b&&(c.result=k,k===!1&&(c.preventDefault(),c.stopPropagation()));if(c.isImmediatePropagationStopped())break}}return c.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a){if(a[f.expando])return a;var d=a;a=f.Event(d);for(var e=this.props.length,g;e;)g=this.props[--e],a[g]=d[g];a.target||(a.target=a.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),!a.relatedTarget&&a.fromElement&&(a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement);if(a.pageX==null&&a.clientX!=null){var h=a.target.ownerDocument||c,i=h.documentElement,j=h.body;a.pageX=a.clientX+(i&&i.scrollLeft||j&&j.scrollLeft||0)-(i&&i.clientLeft||j&&j.clientLeft||0),a.pageY=a.clientY+(i&&i.scrollTop||j&&j.scrollTop||0)-(i&&i.clientTop||j&&j.clientTop||0)}a.which==null&&(a.charCode!=null||a.keyCode!=null)&&(a.which=a.charCode!=null?a.charCode:a.keyCode),!a.metaKey&&a.ctrlKey&&(a.metaKey=a.ctrlKey),!a.which&&a.button!==b&&(a.which=a.button&1?1:a.button&2?3:a.button&4?2:0);return a},guid:1e8,proxy:f.proxy,special:{ready:{setup:f.bindReady,teardown:f.noop},live:{add:function(a){f.event.add(this,N(a.origType,a.selector),f.extend({},a,{handler:M,guid:a.handler.guid}))},remove:function(a){f.event.remove(this,N(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}}},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.preventDefault)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()?E:D):this.type=a,b&&f.extend(this,b),this.timeStamp=f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=E;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=E;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=E,this.stopPropagation()},isDefaultPrevented:D,isPropagationStopped:D,isImmediatePropagationStopped:D};var F=function(a){var b=a.relatedTarget,c=!1,d=a.type;a.type=a.data,b!==this&&(b&&(c=f.contains(this,b)),c||(f.event.handle.apply(this,arguments),a.type=d))},G=function(a){a.type=a.data,f.event.handle.apply(this,arguments)};f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={setup:function(c){f.event.add(this,b,c&&c.selector?G:F,a)},teardown:function(a){f.event.remove(this,b,a&&a.selector?G:F)}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(a,b){if(!f.nodeName(this,"form"))f.event.add(this,"click.specialSubmit",function(a){var b=a.target,c=b.type;(c==="submit"||c==="image")&&f(b).closest("form").length&&K("submit",this,arguments)}),f.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=b.type;(c==="text"||c==="password")&&f(b).closest("form").length&&a.keyCode===13&&K("submit",this,arguments)});else return!1},teardown:function(a){f.event.remove(this,".specialSubmit")}});if(!f.support.changeBubbles){var H,I=function(a){var b=a.type,c=a.value;b==="radio"||b==="checkbox"?c=a.checked:b==="select-multiple"?c=a.selectedIndex>-1?f.map(a.options,function(a){return a.selected}).join("-"):"":f.nodeName(a,"select")&&(c=a.selectedIndex);return c},J=function(c){var d=c.target,e,g;if(!!y.test(d.nodeName)&&!d.readOnly){e=f._data(d,"_change_data"),g=I(d),(c.type!=="focusout"||d.type!=="radio")&&f._data(d,"_change_data",g);if(e===b||g===e)return;if(e!=null||g)c.type="change",c.liveFired=b,f.event.trigger(c,arguments[1],d)}};f.event.special.change={filters:{focusout:J,beforedeactivate:J,click:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(c==="radio"||c==="checkbox"||f.nodeName(b,"select"))&&J.call(this,a)},keydown:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(a.keyCode===13&&!f.nodeName(b,"textarea")||a.keyCode===32&&(c==="checkbox"||c==="radio")||c==="select-multiple")&&J.call(this,a)},beforeactivate:function(a){var b=a.target;f._data(b,"_change_data",I(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in H)f.event.add(this,c+".specialChange",H[c]);return y.test(this.nodeName)},teardown:function(a){f.event.remove(this,".specialChange");return y.test(this.nodeName)}},H=f.event.special.change.filters,H.focus=H.beforeactivate}f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){function e(a){var c=f.event.fix(a);c.type=b,c.originalEvent={},f.event.trigger(c,null,c.target),c.isDefaultPrevented()&&a.preventDefault()}var d=0;f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.each(["bind","one"],function(a,c){f.fn[c]=function(a,d,e){var g;if(typeof a=="object"){for(var h in a)this[c](h,d,a[h],e);return this}if(arguments.length===2||d===!1)e=d,d=b;c==="one"?(g=function(a){f(this).unbind(a,g);return e.apply(this,arguments)},g.guid=e.guid||f.guid++):g=e;if(a==="unload"&&c!=="one")this.one(a,d,e);else for(var i=0,j=this.length;i<j;i++)f.event.add(this[i],a,g,d);return this}}),f.fn.extend({unbind:function(a,b){if(typeof a=="object"&&!a.preventDefault)for(var c in a)this.unbind(c,a[c]);else for(var d=0,e=this.length;d<e;d++)f.event.remove(this[d],a,b);return this},delegate:function(a,b,c,d){return this.live(b,c,d,a)},undelegate:function(a,b,c){return arguments.length===0?this.unbind("live"):this.die(b,null,c,a)},trigger:function(a,b){return this.each(function(){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)}});var L={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};f.each(["live","die"],function(a,c){f.fn[c]=function(a,d,e,g){var h,i=0,j,k,l,m=g||this.selector,n=g?this:f(this.context);if(typeof a=="object"&&!a.preventDefault){for(var o in a)n[c](o,d,a[o],m);return this}if(c==="die"&&!a&&g&&g.charAt(0)==="."){n.unbind(g);return this}if(d===!1||f.isFunction(d))e=d||D,d=b;a=(a||"").split(" ");while((h=a[i++])!=null){j=x.exec(h),k="",j&&(k=j[0],h=h.replace(x,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,L[h]?(a.push(L[h]+k),h=h+k):h=(L[h]||h)+k;if(c==="live")for(var p=0,q=n.length;p<q;p++)f.event.add(n[p],"live."+N(h,m),{data:d,selector:m,handler:e,origType:h,origHandler:e,preType:l});else n.unbind("live."+N(h,m),e)}return this}}),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".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0)}),function(){function u(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}if(i.nodeType===1){f||(i.sizcache=c,i.sizset=g);if(typeof b!="string"){if(i===b){j=!0;break}}else if(k.filter(b,[i]).length>0){j=i;break}}i=i[a]}d[g]=j}}}function t(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}i.nodeType===1&&!f&&(i.sizcache=c,i.sizset=g);if(i.nodeName.toLowerCase()===b){j=i;break}i=i[a]}d[g]=j}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d=0,e=Object.prototype.toString,g=!1,h=!0,i=/\\/g,j=/\W/;[0,0].sort(function(){h=!1;return 0});var k=function(b,d,f,g){f=f||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return f;var i,j,n,o,q,r,s,t,u=!0,w=k.isXML(d),x=[],y=b;do{a.exec(""),i=a.exec(y);if(i){y=i[3],x.push(i[1]);if(i[2]){o=i[3];break}}}while(i);if(x.length>1&&m.exec(b))if(x.length===2&&l.relative[x[0]])j=v(x[0]+x[1],d);else{j=l.relative[x[0]]?[d]:k(x.shift(),d);while(x.length)b=x.shift(),l.relative[b]&&(b+=x.shift()),j=v(b,j)}else{!g&&x.length>1&&d.nodeType===9&&!w&&l.match.ID.test(x[0])&&!l.match.ID.test(x[x.length-1])&&(q=k.find(x.shift(),d,w),d=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]);if(d){q=g?{expr:x.pop(),set:p(g)}:k.find(x.pop(),x.length===1&&(x[0]==="~"||x[0]==="+")&&d.parentNode?d.parentNode:d,w),j=q.expr?k.filter(q.expr,q.set):q.set,x.length>0?n=p(j):u=!1;while(x.length)r=x.pop(),s=r,l.relative[r]?s=x.pop():r="",s==null&&(s=d),l.relative[r](n,s,w)}else n=x=[]}n||(n=j),n||k.error(r||b);if(e.call(n)==="[object Array]")if(!u)f.push.apply(f,n);else if(d&&d.nodeType===1)for(t=0;n[t]!=null;t++)n[t]&&(n[t]===!0||n[t].nodeType===1&&k.contains(d,n[t]))&&f.push(j[t]);else for(t=0;n[t]!=null;t++)n[t]&&n[t].nodeType===1&&f.push(j[t]);else p(n,f);o&&(k(o,h,f,g),k.uniqueSort(f));return f};k.uniqueSort=function(a){if(r){g=h,a.sort(r);if(g)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},k.matches=function(a,b){return k(a,null,null,b)},k.matchesSelector=function(a,b){return k(b,null,null,[a]).length>0},k.find=function(a,b,c){var d;if(!a)return[];for(var e=0,f=l.order.length;e<f;e++){var g,h=l.order[e];if(g=l.leftMatch[h].exec(a)){var j=g[1];g.splice(1,1);if(j.substr(j.length-1)!=="\\"){g[1]=(g[1]||"").replace(i,""),d=l.find[h](g,b,c);if(d!=null){a=a.replace(l.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},k.filter=function(a,c,d,e){var f,g,h=a,i=[],j=c,m=c&&c[0]&&k.isXML(c[0]);while(a&&c.length){for(var n in l.filter)if((f=l.leftMatch[n].exec(a))!=null&&f[2]){var o,p,q=l.filter[n],r=f[1];g=!1,f.splice(1,1);if(r.substr(r.length-1)==="\\")continue;j===i&&(i=[]);if(l.preFilter[n]){f=l.preFilter[n](f,j,d,i,e,m);if(!f)g=o=!0;else if(f===!0)continue}if(f)for(var s=0;(p=j[s])!=null;s++)if(p){o=q(p,f,s,j);var t=e^!!o;d&&o!=null?t?g=!0:j[s]=!1:t&&(i.push(p),g=!0)}if(o!==b){d||(j=i),a=a.replace(l.match[n],"");if(!g)return[];break}}if(a===h)if(g==null)k.error(a);else break;h=a}return j},k.error=function(a){throw"Syntax error, unrecognized expression: "+a};var l=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!j.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&k.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!j.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&k.filter(b,a,!0)}},"":function(a,b,c){var e,f=d++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),e=b,g=t),g("parentNode",b,f,a,e,c)},"~":function(a,b,c){var e,f=d++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),e=b,g=t),g("previousSibling",b,f,a,e,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(i,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(i,"")},TAG:function(a,b){return a[1].replace(i,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||k.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&k.error(a[0]);a[0]=d++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(i,"");!f&&l.attrMap[g]&&(a[1]=l.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(i,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=k(b[3],null,null,c);else{var g=k.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(l.match.POS.test(b[0])||l.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!k(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){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=l.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||k.getText([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}k.error(e)},CHILD:function(a,b){var c=b[1],d=a;switch(c){case"only":case"first":while(d=d.previousSibling)if(d.nodeType===1)return!1;if(c==="first")return!0;d=a;case"last":while(d=d.nextSibling)if(d.nodeType===1)return!1;return!0;case"nth":var e=b[2],f=b[3];if(e===1&&f===0)return!0;var g=b[0],h=a.parentNode;if(h&&(h.sizcache!==g||!a.nodeIndex)){var i=0;for(d=h.firstChild;d;d=d.nextSibling)d.nodeType===1&&(d.nodeIndex=++i);h.sizcache=g}var j=a.nodeIndex-f;return e===0?j===0:j%e===0&&j/e>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=l.attrHandle[c]?l.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=l.setFilters[e];if(f)return f(a,c,b,d)}}},m=l.match.POS,n=function(a,b){return"\\"+(b-0+1)};for(var o in l.match)l.match[o]=new RegExp(l.match[o].source+/(?![^\[]*\])(?![^\(]*\))/.source),l.leftMatch[o]=new RegExp(/(^(?:.|\r|\n)*?)/.source+l.match[o].source.replace(/\\(\d+)/g,n));var p=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(q){p=function(a,b){var c=0,d=b||[];if(e.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var f=a.length;c<f;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var r,s;c.documentElement.compareDocumentPosition?r=function(a,b){if(a===b){g=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(r=function(a,b){if(a===b){g=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;if(h===i)return s(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return s(e[k],f[k]);return k===c?s(a,f[k],-1):s(e[k],b,1)},s=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),k.getText=function(a){var b="",c;for(var d=0;a[d];d++)c=a[d],c.nodeType===3||c.nodeType===4?b+=c.nodeValue:c.nodeType!==8&&(b+=k.getText(c.childNodes));return b},function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(l.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},l.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(l.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(l.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=k,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){k=function(b,e,f,g){e=e||c;if(!g&&!k.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return p(e.getElementsByTagName(b),f);if(h[2]&&l.find.CLASS&&e.getElementsByClassName)return p(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return p([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return p([],f);if(i.id===h[3])return p([i],f)}try{return p(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var m=e,n=e.getAttribute("id"),o=n||d,q=e.parentNode,r=/^\s*[+~]/.test(b);n?o=o.replace(/'/g,"\\$&"):e.setAttribute("id",o),r&&q&&(e=e.parentNode);try{if(!r||q)return p(e.querySelectorAll("[id='"+o+"'] "+b),f)}catch(s){}finally{n||m.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)k[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}k.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(a))try{if(e||!l.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 k(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;l.order.splice(1,0,"CLASS"),l.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?k.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?k.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:k.contains=function(){return!1},k.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var v=function(a,b){var c,d=[],e="",f=b.nodeType?[b]:b;while(c=l.match.PSEUDO.exec(a))e+=c[0],a=a.replace(l.match.PSEUDO,"");a=l.relative[a]?a+"*":a;for(var g=0,h=f.length;g<h;g++)k(a,f[g],d);return k.filter(e,d)};f.find=k,f.expr=k.selectors,f.expr[":"]=f.expr.filters,f.unique=k.uniqueSort,f.text=k.getText,f.isXMLDoc=k.isXML,f.contains=k.contains}();var O=/Until$/,P=/^(?:parents|prevUntil|prevAll)/,Q=/,/,R=/^.[^:#\[\.,]*$/,S=Array.prototype.slice,T=f.expr.match.POS,U={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(W(this,a,!1),"not",a)},filter:function(a){return this.pushStack(W(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?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,i,j={},k=1;if(g&&a.length){for(d=0,e=a.length;d<e;d++)i=a[d],j[i]||(j[i]=T.test(i)?f(i,b||this.context):i);while(g&&g.ownerDocument&&g!==b){for(i in j)h=j[i],(h.jquery?h.index(g)>-1:f(g).is(h))&&c.push({selector:i,elem:g,level:k});g=g.parentNode,k++}}return c}var l=T.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(l?l.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||typeof a=="string")return f.inArray(this[0],a?f(a):this.parent().children());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(V(c[0])||V(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),g=S.call(arguments);O.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!U[a]?f.unique(e):e,(this.length>1||Q.test(d))&&P.test(a)&&(e=e.reverse());return this.pushStack(e,a,g.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 X=/ jQuery\d+="(?:\d+|null)"/g,Y=/^\s+/,Z=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,$=/<([\w:]+)/,_=/<tbody/i,ba=/<|&#?\w+;/,bb=/<(?:script|object|embed|option|style)/i,bc=/checked\s*(?:[^=]|=\s*.checked.)/i,bd=/\/(java|ecma)script/i,be=/^\s*<!(?:\[CDATA\[|\-\-)/,bf={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,"",""]};bf.optgroup=bf.option,bf.tbody=bf.tfoot=bf.colgroup=bf.caption=bf.thead,bf.th=bf.td,f.support.htmlSerialize||(bf._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){return this.each(function(){f(this).wrapAll(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(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f(arguments[0]).toArray());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(X,""):null;if(typeof a=="string"&&!bb.test(a)&&(f.support.leadingWhitespace||!Y.test(a))&&!bf[($.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Z,"<$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"&&bc.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?bg(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bm)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i;b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof a[0]=="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!bb.test(a[0])&&(f.support.checkClone||!bc.test(a[0]))&&(g=!0,h=f.fragments[a[0]],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[a[0]]=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=a.cloneNode(!0),e,g,h;if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bi(a,d),e=bj(a),g=bj(d);for(h=0;e[h];++h)bi(e[h],g[h])}if(b){bh(a,d);if(c){e=bj(a),g=bj(d);for(h=0;e[h];++h)bh(e[h],g[h])}}e=g=null;return d},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(!ba.test(k))k=b.createTextNode(k);else{k=k.replace(Z,"<$1></$2>");var l=($.exec(k)||["",""])[1].toLowerCase(),m=bf[l]||bf._default,n=m[0],o=b.createElement("div");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&&Y.test(k)&&o.insertBefore(b.createTextNode(Y.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++)bl(k[i]);else bl(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||bd.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.expando,g=f.event.special,h=f.support.deleteExpando;for(var i=0,j;(j=a[i])!=null;i++){if(j.nodeName&&f.noData[j.nodeName.toLowerCase()])continue;c=j[f.expando];if(c){b=d[c]&&d[c][e];if(b&&b.events){for(var k in b.events)g[k]?f.event.remove(j,k):f.removeEvent(j,k,b.handle);b.handle&&(b.handle.elem=null)}h?delete j[f.expando]:j.removeAttribute&&j.removeAttribute(f.expando),delete d[c]}}}});var bn=/alpha\([^)]*\)/i,bo=/opacity=([^)]*)/,bp=/([A-Z]|^ms)/g,bq=/^-?\d+(?:px)?$/i,br=/^-?\d/,bs=/^[+\-]=/,bt=/[^+\-\.\de]+/g,bu={position:"absolute",visibility:"hidden",display:"block"},bv=["Left","Right"],bw=["Top","Bottom"],bx,by,bz;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=bx(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;if(h==="number"&&isNaN(d)||d==null)return;h==="string"&&bs.test(d)&&(d=+d.replace(bt,"")+parseFloat(f.css(a,c)),h="number"),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(bx)return bx(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 bA(a,b,d);f.swap(a,bu,function(){e=bA(a,b,d)});return e}},set:function(a,b){if(!bq.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bo.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;c.zoom=1;var e=f.isNaN(b)?"":"alpha(opacity="+b*100+")",g=d&&d.filter||c.filter||"";c.filter=bn.test(g)?g.replace(bn,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=bx(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(by=function(a,c){var d,e,g;c=c.replace(bp,"-$1").toLowerCase();if(!(e=a.ownerDocument.defaultView))return b;if(g=e.getComputedStyle(a,null))d=g.getPropertyValue(c),d===""&&!f.contains(a.ownerDocument.documentElement,a)&&(d=f.style(a,c));return d}),c.documentElement.currentStyle&&(bz=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bq.test(d)&&br.test(d)&&(c=f.left,e&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":d||0,d=f.pixelLeft+"px",f.left=c,e&&(a.runtimeStyle.left=e));return d===""?"auto":d}),bx=by||bz,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.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bB=/%20/g,bC=/\[\]$/,bD=/\r?\n/g,bE=/#.*$/,bF=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bG=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bH=/^(?:about|app|app\-storage|.+\-extension|file|widget):$/,bI=/^(?:GET|HEAD)$/,bJ=/^\/\//,bK=/\?/,bL=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bM=/^(?:select|textarea)/i,bN=/\s+/,bO=/([?&])_=[^&]*/,bP=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bQ=f.fn.load,bR={},bS={},bT,bU;try{bT=e.href}catch(bV){bT=c.createElement("a"),bT.href="",bT=bT.href}bU=bP.exec(bT.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bQ)return bQ.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(bL,"")).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||bM.test(this.nodeName)||bG.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(bD,"\r\n")}}):{name:b.name,value:c.replace(bD,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.bind(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?f.extend(!0,a,f.ajaxSettings,b):(b=a,a=f.extend(!0,f.ajaxSettings,b));for(var c in{context:1,url:1})c in b?a[c]=b[c]:c in f.ajaxSettings&&(a[c]=f.ajaxSettings[c]);return a},ajaxSettings:{url:bT,isLocal:bH.test(bU[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":"*/*"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML}},ajaxPrefilter:bW(bR),ajaxTransport:bW(bS),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?4:0;var o,r,u,w=l?bZ(d,v,l):b,x,y;if(a>=200&&a<300||a===304){if(d.ifModified){if(x=v.getResponseHeader("Last-Modified"))f.lastModified[k]=x;if(y=v.getResponseHeader("Etag"))f.etag[k]=y}if(a===304)c="notmodified",o=!0;else try{r=b$(d,w),c="success",o=!0}catch(z){c="parsererror",u=z}}else{u=c;if(!c||a)c="error",a<0&&(a=0)}v.status=a,v.statusText=c,o?h.resolveWith(e,[r,c,v]):h.rejectWith(e,[v,c,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.resolveWith(e,[v,c]),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._Deferred(),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=bF.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.done,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(bE,"").replace(bJ,bU[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bN),d.crossDomain==null&&(r=bP.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bU[1]&&r[2]==bU[2]&&(r[3]||(r[1]==="http:"?80:443))==(bU[3]||(bU[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bX(bR,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bI.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bK.test(d.url)?"&":"?")+d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bO,"$1_="+x);d.url=y+(y===d.url?(bK.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]!=="*"?", */*; 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=bX(bS,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){status<2?w(-1,z):f.error(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)bY(g,a[g],c,e);return d.join("&").replace(bB,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var b_=f.now(),ca=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+b_++}}),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&&(ca.test(b.url)||e&&ca.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(ca,l),b.url===j&&(e&&(k=k.replace(ca,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 cb=a.ActiveXObject?function(){for(var a in cd)cd[a](0,1)}:!1,cc=0,cd;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ce()||cf()}:ce,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,cb&&delete cd[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=++cc,cb&&(cd||(cd={},f(a).unload(cb)),cd[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cg={},ch,ci,cj=/^(?:toggle|show|hide)$/,ck=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cl,cm=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cn,co=a.webkitRequestAnimationFrame||a.mozRequestAnimationFrame||a.oRequestAnimationFrame;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cr("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",cs(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(cr("hide",3),a,b,c);for(var d=0,e=this.length;d<e;d++)if(this[d].style){var g=f.css(this[d],"display");g!=="none"&&!f._data(this[d],"olddisplay")&&f._data(this[d],"olddisplay",g)}for(d=0;d<e;d++)this[d].style&&(this[d].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(cr("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){var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return this[e.queue===!1?"each":"queue"](function(){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?(j=cs(this.nodeName),j==="inline"?this.style.display="inline-block":(this.style.display="inline",this.style.zoom=1)):this.style.display="inline-block"))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)k=new f.fx(this,b,i),h=a[i],cj.test(h)?k[h==="toggle"?d?"show":"hide":h]():(l=ck.exec(h),m=k.cur(),l?(n=parseFloat(l[2]),o=l[3]||(f.cssNumber[i]?"":"px"),o!=="px"&&(f.style(this,i,(n||1)+o),m=(n||1)/k.cur()*m,f.style(this,i,m+o)),l[1]&&(n=(l[1]==="-="?-1:1)*n+m),k.custom(m,n,o)):k.custom(m,h,""));return!0})},stop:function(a,b){a&&this.queue([]),this.each(function(){var a=f.timers,c=a.length;b||f._unmark(!0,this);while(c--)a[c].elem===this&&(b&&a[c](!0),a.splice(c,1))}),b||this.dequeue();return this}}),f.each({slideDown:cr("show",1),slideUp:cr("hide",1),slideToggle:cr("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,d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue!==!1?f.dequeue(this):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,b,c){function h(a){return d.step(a)}var d=this,e=f.fx,g;this.startTime=cn||cp(),this.start=a,this.end=b,this.unit=c||this.unit||(f.cssNumber[this.prop]?"":"px"),this.now=this.start,this.pos=this.state=0,h.elem=this.elem,h()&&f.timers.push(h)&&!cl&&(co?(cl=!0,g=function(){cl&&(co(g),e.tick())},co(g)):cl=setInterval(e.tick,e.interval))},show:function(){this.options.orig[this.prop]=f.style(this.elem,this.prop),this.options.show=!0,this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b=cn||cp(),c=!0,d=this.elem,e=this.options,g,h;if(a||b>=e.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),e.animatedProperties[this.prop]=!0;for(g in e.animatedProperties)e.animatedProperties[g]!==!0&&(c=!1);if(c){e.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){d.style["overflow"+b]=e.overflow[a]}),e.hide&&f(d).hide();if(e.hide||e.show)for(var i in e.animatedProperties)f.style(d,i,e.orig[i]);e.complete.call(d)}return!1}e.duration==Infinity?this.now=b:(h=b-this.startTime,this.state=h/e.duration,this.pos=f.easing[e.animatedProperties[this.prop]](this.state,h,0,1,e.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){for(var a=f.timers,b=0;b<a.length;++b)a[b]()||a.splice(b--,1);a.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cl),cl=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.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit:a.elem[a.prop]=a.now}}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var ct=/^t(?:able|d|h)$/i,cu=/^(?: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=cv(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);f.offset.initialize();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.offset.supportsFixedPosition&&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.offset.doesNotAddBorder&&(!f.offset.doesAddBorderForTableAndCells||!ct.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.offset.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.offset.supportsFixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={initialize:function(){var a=c.body,b=c.createElement("div"),d,e,g,h,i=parseFloat(f.css(a,"marginTop"))||0,j="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";f.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"}),b.innerHTML=j,a.insertBefore(b,a.firstChild),d=b.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,this.doesNotAddBorder=e.offsetTop!==5,this.doesAddBorderForTableAndCells=h.offsetTop===5,e.style.position="fixed",e.style.top="20px",this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i,a.removeChild(b),f.offset.initialize=f.noop},bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.offset.initialize(),f.offset.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=cu.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&&!cu.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=cv(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=cv(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")):null},f.fn["outer"+c]=function(a){var b=this[0];return b&&b.style?parseFloat(f.css(b,d,a?"margin":"border")):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];return e.document.compatMode==="CSS1Compat"&&g||e.document.body["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 h=f.css(e,d),i=parseFloat(h);return f.isNaN(i)?h:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f})(window);
src/react/js/app/main.js
lopezhansel/OctoDex
import React from 'react'; import Router from 'react-router'; import ReactDOM from 'react-dom'; import createBrowserHistory from 'history/lib/createBrowserHistory'; let history = createBrowserHistory();
client/src/components/header.js
vitalyorlov/spreadsheet-core
import React from 'react'; import LocalSwitcher from './locale-switcher'; import {Link} from 'react-router'; import counterpart from 'counterpart'; import Translate from 'react-translate-component'; import LocalizationService from './../infrastructure/localization-service'; import dispatcher from './../infrastructure/dispatcher'; counterpart.registerTranslations('en', { dropdownMenu: { profile: 'Profile', statistic: 'Statistic', logout: 'Logout', search: 'Search...' } }); counterpart.registerTranslations('ru', { dropdownMenu: { profile: 'Профиль', statistic: 'Статистика', logout: 'Выход', seacrh: 'Поиск' } }); const additionalConstants = { en: { search: "Search..." }, ru: { search: "Поиск..." } }; export default class Header extends React.Component { constructor() { super(); this.state = {}; this.state.localizationService = new LocalizationService(additionalConstants); } logout() { dispatcher.dispatch({action: 'user.logout'}); } render() { return ( <header className="top-head container-fluid"> <button type="button" className="navbar-toggle pull-left"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <form role="search" className="navbar-left app-search pull-left hidden-xs"> <input type="text" placeholder={this.state.localizationService.translate("search")} className="form-control"/> <a href=""><i className="fa fa-search"></i></a> </form> <nav className=" navbar-default" role="navigation"> <ul className="nav navbar-nav hidden-xs"> <LocalSwitcher user={this.props.user} /> </ul> <ul className="nav navbar-nav navbar-right top-menu top-right-menu"> <li className="dropdown"> <a data-toggle="dropdown" className="dropdown-toggle" href="#"> <i className="fa fa-bell-o"></i> <span className="badge badge-sm up bg-pink count">3</span> </a> </li> <li className="dropdown text-center"> <a data-toggle="dropdown" className="dropdown-toggle" href="#"> <img alt="" src="" className="img-circle profile-img thumb-sm"/> <span className="username">{this.props.user.firstName + " " + this.props.user.lastName}</span> <span className="caret"></span> </a> <ul className="dropdown-menu pro-menu fadeInUp animated" tabIndex="5003"> <li> <Link to="/profile" > <i className="fa fa-briefcase"></i> <Translate content="dropdownMenu.profile" /> </Link> </li> <li> <a href="#"> <i className="fa fa-cog"></i> <Translate content="dropdownMenu.statistic" /> </a> </li> <li> <a href="#" onClick={this.logout.bind(this)}> <i className="fa fa-sign-out"></i> <Translate content="dropdownMenu.logout" /> </a> </li> </ul> </li> </ul> </nav> </header> ); } }
ajax/libs/react-instantsearch/4.1.3/Core.min.js
seogi1004/cdnjs
/*! ReactInstantSearch 4.1.3 | © Algolia, inc. | https://community.algolia.com/react-instantsearch/ */ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("react")):"function"==typeof define&&define.amd?define(["react"],e):"object"==typeof exports?exports.Core=e(require("react")):(t.ReactInstantSearch=t.ReactInstantSearch||{},t.ReactInstantSearch.Core=e(t.React))}(this,function(t){return function(t){function e(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,e),o.l=!0,o.exports}var r={};return e.m=t,e.c=r,e.d=function(t,r,n){e.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:n})},e.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(r,"a",r),r},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=352)}([function(t,e,r){t.exports=r(159)()},function(t,e){var r=Array.isArray;t.exports=r},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function i(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function c(t){if(!t.displayName)throw new Error("`createConnector` requires you to provide a `displayName` property.");var e=(0,p.default)(t,"refine"),r=(0,p.default)(t,"searchForFacetValues"),n=(0,p.default)(t,"getSearchParameters"),c=(0,p.default)(t,"getMetadata"),u=(0,p.default)(t,"transitionState"),f=(0,p.default)(t,"cleanUp"),v=n||c||u;return function(p){var g,x,j;return x=g=function(y){function d(t,e){o(this,d);var r=a(this,(d.__proto__||Object.getPrototypeOf(d)).call(this,t,e));j.call(r);var n=e.ais,i=n.store,c=n.widgetsManager,u=!1;r.state={props:r.getProvidedProps(l({},t,{canRender:u})),canRender:u},r.unsubscribe=i.subscribe(function(){r.state.canRender&&r.setState({props:r.getProvidedProps(l({},r.props,{canRender:r.state.canRender}))})}),v&&(r.unregisterWidget=c.registerWidget(r));return r}return i(d,y),h(d,[{key:"getMetadata",value:function(e){return c?t.getMetadata.call(this,this.props,e):{}}},{key:"getSearchParameters",value:function(e){return n?t.getSearchParameters.call(this,e,this.props,this.context.ais.store.getState().widgets):null}},{key:"transitionState",value:function(e,r){return u?t.transitionState.call(this,this.props,e,r):r}},{key:"componentDidMount",value:function(){this.setState({canRender:!0})}},{key:"componentWillMount",value:function(){t.getSearchParameters&&this.context.ais.onSearchParameters(t.getSearchParameters,this.context,this.props)}},{key:"componentWillReceiveProps",value:function(e){(0,s.default)(this.props,e)||(this.setState({props:this.getProvidedProps(e)}),v&&(this.context.ais.widgetsManager.update(),t.transitionState&&this.context.ais.onSearchStateChange(t.transitionState.call(this,e,this.context.ais.store.getState().widgets,this.context.ais.store.getState().widgets))))}},{key:"componentWillUnmount",value:function(){if(this.unsubscribe(),v&&(this.unregisterWidget(),f)){var e=t.cleanUp.call(this,this.props,this.context.ais.store.getState().widgets);this.context.ais.store.setState(l({},this.context.ais.store.getState(),{widgets:e})),this.context.ais.onSearchStateChange((0,_.removeEmptyKey)(e))}}},{key:"shouldComponentUpdate",value:function(t,e){var r=(0,_.shallowEqual)(this.props,t);return null===this.state.props||null===e.props?this.state.props!==e.props||!r:!r||!(0,_.shallowEqual)(this.state.props,e.props)}},{key:"render",value:function(){var t=this;if(null===this.state.props)return null;var n=e?{refine:this.refine,createURL:this.createURL}:{},o=r?{searchForItems:this.searchForFacetValues,searchForFacetValues:function(e,r){t.searchForFacetValues(e,r)}}:{};return b.default.createElement(p,l({},this.props,this.state.props,n,o))}}]),d}(d.Component),g.displayName=t.displayName+"("+(0,_.getDisplayName)(p)+")",g.defaultClassNames=p.defaultClassNames,g.propTypes=t.propTypes,g.defaultProps=t.defaultProps,g.contextTypes={ais:y.default.object.isRequired,multiIndexContext:y.default.object},j=function(){var e=this;this.getProvidedProps=function(r){var n=e.context.ais.store,o=n.getState(),a=o.results,i=o.searching,c=o.error,u=o.widgets,s=o.metadata,f=o.resultsFacetValues,p=o.searchingForFacetValues,l={results:a,searching:i,error:c,searchingForFacetValues:p};return t.getProvidedProps.call(e,r,u,l,s,f)},this.refine=function(){for(var r,n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];e.context.ais.onInternalStateUpdate((r=t.refine).call.apply(r,[e,e.props,e.context.ais.store.getState().widgets].concat(o)))},this.searchForFacetValues=function(){for(var r=arguments.length,n=Array(r),o=0;o<r;o++)n[o]=arguments[o];e.context.ais.onSearchForFacetValues(t.searchForFacetValues.apply(t,[e.props,e.context.ais.store.getState().widgets].concat(n)))},this.createURL=function(){for(var r,n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];return e.context.ais.createHrefForState((r=t.refine).call.apply(r,[e,e.props,e.context.ais.store.getState().widgets].concat(o)))},this.cleanUp=function(){for(var r,n=arguments.length,o=Array(n),a=0;a<n;a++)o[a]=arguments[a];return(r=t.cleanUp).call.apply(r,[e].concat(o))}},x}}Object.defineProperty(e,"__esModule",{value:!0});var u=r(81),s=n(u),f=r(58),p=n(f),l=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t},h=function(){function t(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(e,r,n){return r&&t(e.prototype,r),n&&t(e,n),e}}();e.default=c;var v=r(0),y=n(v),d=r(4),b=n(d),_=r(44)},function(t,e,r){var n=r(76),o="object"==typeof self&&self&&self.Object===Object&&self,a=n||o||Function("return this")();t.exports=a},function(e,r){e.exports=t},,function(t,e){function r(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}t.exports=r},function(t,e){function r(t){return null!=t&&"object"==typeof t}t.exports=r},function(t,e,r){function n(t){return null==t?void 0===t?u:c:s&&s in Object(t)?a(t):i(t)}var o=r(16),a=r(124),i=r(125),c="[object Null]",u="[object Undefined]",s=o?o.toStringTag:void 0;t.exports=n},function(t,e,r){function n(t){return i(t)?o(t):a(t)}var o=r(89),a=r(79),i=r(11);t.exports=n},function(t,e,r){function n(t,e){var r=a(t,e);return o(r)?r:void 0}var o=r(123),a=r(128);t.exports=n},function(t,e,r){function n(t){return null!=t&&a(t.length)&&!o(t)}var o=r(19),a=r(42);t.exports=n},function(t,e){function r(t,e){for(var r=-1,n=null==t?0:t.length,o=Array(n);++r<n;)o[r]=e(t[r],r,t);return o}t.exports=r},,,function(t,e,r){function n(t){if(null==t)return!0;if(u(t)&&(c(t)||"string"==typeof t||"function"==typeof t.splice||s(t)||p(t)||i(t)))return!t.length;var e=a(t);if(e==l||e==h)return!t.size;if(f(t))return!o(t).length;for(var r in t)if(y.call(t,r))return!1;return!0}var o=r(79),a=r(57),i=r(20),c=r(1),u=r(11),s=r(21),f=r(38),p=r(34),l="[object Map]",h="[object Set]",v=Object.prototype,y=v.hasOwnProperty;t.exports=n},function(t,e,r){var n=r(3),o=n.Symbol;t.exports=o},,function(t,e){function r(t,e){return t===e||t!==t&&e!==e}t.exports=r},function(t,e,r){function n(t){if(!a(t))return!1;var e=o(t);return e==c||e==u||e==i||e==s}var o=r(8),a=r(6),i="[object AsyncFunction]",c="[object Function]",u="[object GeneratorFunction]",s="[object Proxy]";t.exports=n},function(t,e,r){var n=r(147),o=r(7),a=Object.prototype,i=a.hasOwnProperty,c=a.propertyIsEnumerable,u=n(function(){return arguments}())?n:function(t){return o(t)&&i.call(t,"callee")&&!c.call(t,"callee")};t.exports=u},function(t,e,r){(function(t){var n=r(3),o=r(148),a="object"==typeof e&&e&&!e.nodeType&&e,i=a&&"object"==typeof t&&t&&!t.nodeType&&t,c=i&&i.exports===a,u=c?n.Buffer:void 0,s=u?u.isBuffer:void 0,f=s||o;t.exports=f}).call(e,r(56)(t))},function(t,e,r){function n(t,e){return o(t)?t:a(t,e)?[t]:i(c(t))}var o=r(1),a=r(64),i=r(156),c=r(65);t.exports=n},function(t,e,r){function n(t){return"symbol"==typeof t||a(t)&&o(t)==i}var o=r(8),a=r(7),i="[object Symbol]";t.exports=n},function(t,e,r){function n(t){if("string"==typeof t||o(t))return t;var e=t+"";return"0"==e&&1/t==-a?"-0":e}var o=r(23),a=1/0;t.exports=n},,,,function(t,e,r){function n(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}var o=r(113),a=r(114),i=r(115),c=r(116),u=r(117);n.prototype.clear=o,n.prototype.delete=a,n.prototype.get=i,n.prototype.has=c,n.prototype.set=u,t.exports=n},function(t,e,r){function n(t,e){for(var r=t.length;r--;)if(o(t[r][0],e))return r;return-1}var o=r(18);t.exports=n},function(t,e,r){var n=r(10),o=n(Object,"create");t.exports=o},function(t,e,r){function n(t,e){var r=t.__data__;return o(e)?r["string"==typeof e?"string":"hash"]:r.map}var o=r(137);t.exports=n},function(t,e){function r(t,e){return e=null==e?n:e,!!e&&("number"==typeof t||o.test(t))&&t>-1&&t%1==0&&t<e}var n=9007199254740991,o=/^(?:0|[1-9]\d*)$/;t.exports=r},,function(t,e,r){var n=r(149),o=r(43),a=r(150),i=a&&a.isTypedArray,c=i?o(i):n;t.exports=c},,,,function(t,e){function r(t){var e=t&&t.constructor,r="function"==typeof e&&e.prototype||n;return t===r}var n=Object.prototype;t.exports=r},function(t,e,r){function n(t){var e=this.__data__=new o(t);this.size=e.size}var o=r(28),a=r(118),i=r(119),c=r(120),u=r(121),s=r(122);n.prototype.clear=a,n.prototype.delete=i,n.prototype.get=c,n.prototype.has=u,n.prototype.set=s,t.exports=n},function(t,e,r){var n=r(10),o=r(3),a=n(o,"Map");t.exports=a},function(t,e,r){function n(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}var o=r(129),a=r(136),i=r(138),c=r(139),u=r(140);n.prototype.clear=o,n.prototype.delete=a,n.prototype.get=i,n.prototype.has=c,n.prototype.set=u,t.exports=n},function(t,e){function r(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=n}var n=9007199254740991;t.exports=r},function(t,e){function r(t){return function(e){return t(e)}}t.exports=r},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(t===e)return!0;var r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(var o=Object.prototype.hasOwnProperty,a=0;a<r.length;a++)if(!o.call(e,r[a])||t[r[a]]!==e[r[a]])return!1;return!0}function a(t){var e=1===t.button;return Boolean(e||t.altKey||t.ctrlKey||t.metaKey||t.shiftKey)}function i(t){return 0===t.length?"":""+t[0].toUpperCase()+t.slice(1)}function c(t,e,r){var n=t.isConjunctiveFacet(r)||t.isDisjunctiveFacet(r),o=Boolean(e.getFacetByName(r));e.nbHits>0&&n&&!o&&console.warn('A component requested values for facet "'+r+'", but no facet values were retrieved from the API. This means that you should add '+('the attribute "'+r+'" to the list of attributes for faceting in ')+"your index settings.")}function u(t){return t.displayName||t.name||"UnknownComponent"}function s(t){return Object.keys(t).forEach(function(e){var r=t[e];(0,h.default)(r)&&(0,p.default)(r)?delete t[e]:(0,p.default)(r)&&s(r)}),t}Object.defineProperty(e,"__esModule",{value:!0}),e.defer=void 0;var f=r(45),p=n(f),l=r(15),h=n(l);e.shallowEqual=o,e.isSpecialClick=a,e.capitalize=i,e.assertFacetDefined=c,e.getDisplayName=u,e.removeEmptyKey=s;var v=Promise.resolve();e.defer=function(t){v.then(t)}},function(t,e,r){function n(t){if(!i(t)||o(t)!=c)return!1;var e=a(t);if(null===e)return!0;var r=p.call(e,"constructor")&&e.constructor;return"function"==typeof r&&r instanceof r&&f.call(r)==l}var o=r(8),a=r(67),i=r(7),c="[object Object]",u=Function.prototype,s=Object.prototype,f=u.toString,p=s.hasOwnProperty,l=f.call(Object);t.exports=n},,,,,,,,,,function(t,e){var r;r=function(){return this}();try{r=r||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(r=window)}t.exports=r},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e,r){var n=r(152),o=r(40),a=r(153),i=r(154),c=r(90),u=r(8),s=r(77),f="[object Map]",p="[object Object]",l="[object Promise]",h="[object Set]",v="[object WeakMap]",y="[object DataView]",d=s(n),b=s(o),_=s(a),g=s(i),x=s(c),j=u;(n&&j(new n(new ArrayBuffer(1)))!=y||o&&j(new o)!=f||a&&j(a.resolve())!=l||i&&j(new i)!=h||c&&j(new c)!=v)&&(j=function(t){var e=u(t),r=e==p?t.constructor:void 0,n=r?s(r):"";if(n)switch(n){case d:return y;case b:return f;case _:return l;case g:return h;case x:return v}return e}),t.exports=j},function(t,e,r){function n(t,e){return null!=t&&a(t,e,o)}var o=r(155),a=r(91);t.exports=n},function(t,e,r){function n(t,e,r,i,c){return t===e||(null==t||null==e||!a(t)&&!a(e)?t!==t&&e!==e:o(t,e,r,i,n,c))}var o=r(112),a=r(7);t.exports=n},function(t,e,r){function n(t){var e=-1,r=null==t?0:t.length;for(this.__data__=new o;++e<r;)this.add(t[e])}var o=r(41),a=r(141),i=r(142);n.prototype.add=n.prototype.push=a,n.prototype.has=i,t.exports=n},function(t,e){function r(t,e){return t.has(e)}t.exports=r},function(t,e){function r(t,e){for(var r=-1,n=e.length,o=t.length;++r<n;)t[o+r]=e[r];return t}t.exports=r},function(t,e,r){var n=r(87),o=r(88),a=Object.prototype,i=a.propertyIsEnumerable,c=Object.getOwnPropertySymbols,u=c?function(t){return null==t?[]:(t=Object(t),n(c(t),function(e){return i.call(t,e)}))}:o;t.exports=u},function(t,e,r){function n(t,e){if(o(t))return!1;var r=typeof t;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=t&&!a(t))||(c.test(t)||!i.test(t)||null!=e&&t in Object(e))}var o=r(1),a=r(23),i=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,c=/^\w*$/;t.exports=n},function(t,e,r){function n(t){return null==t?"":o(t)}var o=r(66);t.exports=n},function(t,e,r){function n(t){if("string"==typeof t)return t;if(i(t))return a(t,n)+"";if(c(t))return f?f.call(t):"";var e=t+"";return"0"==e&&1/t==-u?"-0":e}var o=r(16),a=r(12),i=r(1),c=r(23),u=1/0,s=o?o.prototype:void 0,f=s?s.toString:void 0;t.exports=n},function(t,e,r){var n=r(80),o=n(Object.getPrototypeOf,Object);t.exports=o},,,,,,,,,function(t,e,r){(function(e){var r="object"==typeof e&&e&&e.Object===Object&&e;t.exports=r}).call(e,r(55))},function(t,e){function r(t){if(null!=t){try{return o.call(t)}catch(t){}try{return t+""}catch(t){}}return""}var n=Function.prototype,o=n.toString;t.exports=r},function(t,e,r){function n(t,e,r,n,s,f){var p=r&c,l=t.length,h=e.length;if(l!=h&&!(p&&h>l))return!1;var v=f.get(t);if(v&&f.get(e))return v==e;var y=-1,d=!0,b=r&u?new o:void 0;for(f.set(t,e),f.set(e,t);++y<l;){var _=t[y],g=e[y];if(n)var x=p?n(g,_,y,e,t,f):n(_,g,y,t,e,f);if(void 0!==x){if(x)continue;d=!1;break}if(b){if(!a(e,function(t,e){if(!i(b,e)&&(_===t||s(_,t,r,n,f)))return b.push(e)})){d=!1;break}}else if(_!==g&&!s(_,g,r,n,f)){d=!1;break}}return f.delete(t),f.delete(e),d}var o=r(60),a=r(143),i=r(61),c=1,u=2;t.exports=n},function(t,e,r){function n(t){if(!o(t))return a(t);var e=[];for(var r in Object(t))c.call(t,r)&&"constructor"!=r&&e.push(r);return e}var o=r(38),a=r(151),i=Object.prototype,c=i.hasOwnProperty;t.exports=n},function(t,e){function r(t,e){return function(r){return t(e(r))}}t.exports=r},function(t,e,r){function n(t,e){return o(t,e)}var o=r(59);t.exports=n},function(t,e,r){var n=r(3),o=n.Uint8Array;t.exports=o},function(t,e){function r(t){var e=-1,r=Array(t.size);return t.forEach(function(t,n){r[++e]=[n,t]}),r}t.exports=r},function(t,e){function r(t){var e=-1,r=Array(t.size);return t.forEach(function(t){r[++e]=t}),r}t.exports=r},function(t,e,r){function n(t){return o(t,i,a)}var o=r(86),a=r(63),i=r(9);t.exports=n},function(t,e,r){function n(t,e,r){var n=e(t);return a(t)?n:o(n,r(t))}var o=r(62),a=r(1);t.exports=n},function(t,e){function r(t,e){for(var r=-1,n=null==t?0:t.length,o=0,a=[];++r<n;){var i=t[r];e(i,r,t)&&(a[o++]=i)}return a}t.exports=r},function(t,e){function r(){return[]}t.exports=r},function(t,e,r){function n(t,e){var r=i(t),n=!r&&a(t),f=!r&&!n&&c(t),l=!r&&!n&&!f&&s(t),h=r||n||f||l,v=h?o(t.length,String):[],y=v.length;for(var d in t)!e&&!p.call(t,d)||h&&("length"==d||f&&("offset"==d||"parent"==d)||l&&("buffer"==d||"byteLength"==d||"byteOffset"==d)||u(d,y))||v.push(d);return v}var o=r(146),a=r(20),i=r(1),c=r(21),u=r(32),s=r(34),f=Object.prototype,p=f.hasOwnProperty;t.exports=n},function(t,e,r){var n=r(10),o=r(3),a=n(o,"WeakMap");t.exports=a},function(t,e,r){function n(t,e,r){e=o(e,t);for(var n=-1,f=e.length,p=!1;++n<f;){var l=s(e[n]);if(!(p=null!=t&&r(t,l)))break;t=t[l]}return p||++n!=f?p:(f=null==t?0:t.length,!!f&&u(f)&&c(l,f)&&(i(t)||a(t)))}var o=r(22),a=r(20),i=r(1),c=r(32),u=r(42),s=r(24);t.exports=n},,,,,,,,,,,,,,,,,,,,,function(t,e,r){function n(t,e,r,n,d,_){var g=s(t),x=s(e),j=g?v:u(t),m=x?v:u(e);j=j==h?y:j,m=m==h?y:m;var O=j==y,w=m==y,P=j==m;if(P&&f(t)){if(!f(e))return!1;g=!0,O=!1}if(P&&!O)return _||(_=new o),g||p(t)?a(t,e,r,n,d,_):i(t,e,j,r,n,d,_);if(!(r&l)){var S=O&&b.call(t,"__wrapped__"),F=w&&b.call(e,"__wrapped__");if(S||F){var A=S?t.value():t,k=F?e.value():e;return _||(_=new o),d(A,k,r,n,_)}}return!!P&&(_||(_=new o),c(t,e,r,n,d,_))}var o=r(39),a=r(78),i=r(144),c=r(145),u=r(57),s=r(1),f=r(21),p=r(34),l=1,h="[object Arguments]",v="[object Array]",y="[object Object]",d=Object.prototype,b=d.hasOwnProperty;t.exports=n},function(t,e){function r(){this.__data__=[],this.size=0}t.exports=r},function(t,e,r){function n(t){var e=this.__data__,r=o(e,t);if(r<0)return!1;var n=e.length-1;return r==n?e.pop():i.call(e,r,1),--this.size,!0}var o=r(29),a=Array.prototype,i=a.splice;t.exports=n},function(t,e,r){function n(t){var e=this.__data__,r=o(e,t);return r<0?void 0:e[r][1]}var o=r(29);t.exports=n},function(t,e,r){function n(t){return o(this.__data__,t)>-1}var o=r(29);t.exports=n},function(t,e,r){function n(t,e){var r=this.__data__,n=o(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}var o=r(29);t.exports=n},function(t,e,r){function n(){this.__data__=new o,this.size=0}var o=r(28);t.exports=n},function(t,e){function r(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}t.exports=r},function(t,e){function r(t){return this.__data__.get(t)}t.exports=r},function(t,e){function r(t){return this.__data__.has(t)}t.exports=r},function(t,e,r){function n(t,e){var r=this.__data__;if(r instanceof o){var n=r.__data__;if(!a||n.length<c-1)return n.push([t,e]),this.size=++r.size,this;r=this.__data__=new i(n)}return r.set(t,e),this.size=r.size,this}var o=r(28),a=r(40),i=r(41),c=200;t.exports=n},function(t,e,r){function n(t){if(!i(t)||a(t))return!1;var e=o(t)?v:s;return e.test(c(t))}var o=r(19),a=r(126),i=r(6),c=r(77),u=/[\\^$.*+?()[\]{}|]/g,s=/^\[object .+?Constructor\]$/,f=Function.prototype,p=Object.prototype,l=f.toString,h=p.hasOwnProperty,v=RegExp("^"+l.call(h).replace(u,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=n},function(t,e,r){function n(t){var e=i.call(t,u),r=t[u];try{t[u]=void 0;var n=!0}catch(t){}var o=c.call(t);return n&&(e?t[u]=r:delete t[u]),o}var o=r(16),a=Object.prototype,i=a.hasOwnProperty,c=a.toString,u=o?o.toStringTag:void 0;t.exports=n},function(t,e){function r(t){return o.call(t)}var n=Object.prototype,o=n.toString;t.exports=r},function(t,e,r){function n(t){return!!a&&a in t}var o=r(127),a=function(){var t=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();t.exports=n},function(t,e,r){var n=r(3),o=n["__core-js_shared__"];t.exports=o},function(t,e){function r(t,e){return null==t?void 0:t[e]}t.exports=r},function(t,e,r){function n(){this.size=0,this.__data__={hash:new o,map:new(i||a),string:new o}}var o=r(130),a=r(28),i=r(40);t.exports=n},function(t,e,r){function n(t){var e=-1,r=null==t?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}var o=r(131),a=r(132),i=r(133),c=r(134),u=r(135);n.prototype.clear=o,n.prototype.delete=a,n.prototype.get=i,n.prototype.has=c,n.prototype.set=u,t.exports=n},function(t,e,r){function n(){this.__data__=o?o(null):{},this.size=0}var o=r(30);t.exports=n},function(t,e){function r(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}t.exports=r},function(t,e,r){function n(t){var e=this.__data__;if(o){var r=e[t];return r===a?void 0:r}return c.call(e,t)?e[t]:void 0}var o=r(30),a="__lodash_hash_undefined__",i=Object.prototype,c=i.hasOwnProperty;t.exports=n},function(t,e,r){function n(t){var e=this.__data__;return o?void 0!==e[t]:i.call(e,t)}var o=r(30),a=Object.prototype,i=a.hasOwnProperty;t.exports=n},function(t,e,r){function n(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=o&&void 0===e?a:e,this}var o=r(30),a="__lodash_hash_undefined__";t.exports=n},function(t,e,r){function n(t){var e=o(this,t).delete(t);return this.size-=e?1:0,e}var o=r(31);t.exports=n},function(t,e){function r(t){var e=typeof t;return"string"==e||"number"==e||"symbol"==e||"boolean"==e?"__proto__"!==t:null===t}t.exports=r},function(t,e,r){function n(t){return o(this,t).get(t)}var o=r(31);t.exports=n},function(t,e,r){function n(t){return o(this,t).has(t)}var o=r(31);t.exports=n},function(t,e,r){function n(t,e){var r=o(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this}var o=r(31);t.exports=n},function(t,e){function r(t){return this.__data__.set(t,n),this}var n="__lodash_hash_undefined__";t.exports=r},function(t,e){function r(t){return this.__data__.has(t)}t.exports=r},function(t,e){function r(t,e){for(var r=-1,n=null==t?0:t.length;++r<n;)if(e(t[r],r,t))return!0;return!1}t.exports=r},function(t,e,r){function n(t,e,r,n,o,O,P){switch(r){case m:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case j:return!(t.byteLength!=e.byteLength||!O(new a(t),new a(e)));case l:case h:case d:return i(+t,+e);case v:return t.name==e.name&&t.message==e.message;case b:case g:return t==e+"";case y:var S=u;case _:var F=n&f;if(S||(S=s),t.size!=e.size&&!F)return!1;var A=P.get(t);if(A)return A==e;n|=p,P.set(t,e);var k=c(S(t),S(e),n,o,O,P);return P.delete(t),k;case x:if(w)return w.call(t)==w.call(e)}return!1}var o=r(16),a=r(82),i=r(18),c=r(78),u=r(83),s=r(84),f=1,p=2,l="[object Boolean]",h="[object Date]",v="[object Error]",y="[object Map]",d="[object Number]",b="[object RegExp]",_="[object Set]",g="[object String]",x="[object Symbol]",j="[object ArrayBuffer]",m="[object DataView]",O=o?o.prototype:void 0,w=O?O.valueOf:void 0;t.exports=n},function(t,e,r){function n(t,e,r,n,i,u){var s=r&a,f=o(t),p=f.length,l=o(e),h=l.length;if(p!=h&&!s)return!1;for(var v=p;v--;){var y=f[v];if(!(s?y in e:c.call(e,y)))return!1}var d=u.get(t);if(d&&u.get(e))return d==e;var b=!0;u.set(t,e),u.set(e,t);for(var _=s;++v<p;){y=f[v];var g=t[y],x=e[y];if(n)var j=s?n(x,g,y,e,t,u):n(g,x,y,t,e,u);if(!(void 0===j?g===x||i(g,x,r,n,u):j)){b=!1;break}_||(_="constructor"==y)}if(b&&!_){var m=t.constructor,O=e.constructor;m!=O&&"constructor"in t&&"constructor"in e&&!("function"==typeof m&&m instanceof m&&"function"==typeof O&&O instanceof O)&&(b=!1)}return u.delete(t),u.delete(e),b}var o=r(85),a=1,i=Object.prototype,c=i.hasOwnProperty;t.exports=n},function(t,e){function r(t,e){for(var r=-1,n=Array(t);++r<t;)n[r]=e(r);return n}t.exports=r},function(t,e,r){function n(t){return a(t)&&o(t)==i}var o=r(8),a=r(7),i="[object Arguments]";t.exports=n},function(t,e){function r(){return!1}t.exports=r},function(t,e,r){function n(t){return i(t)&&a(t.length)&&!!E[o(t)]}var o=r(8),a=r(42),i=r(7),c="[object Arguments]",u="[object Array]",s="[object Boolean]",f="[object Date]",p="[object Error]",l="[object Function]",h="[object Map]",v="[object Number]",y="[object Object]",d="[object RegExp]",b="[object Set]",_="[object String]",g="[object WeakMap]",x="[object ArrayBuffer]",j="[object DataView]",m="[object Float32Array]",O="[object Float64Array]",w="[object Int8Array]",P="[object Int16Array]",S="[object Int32Array]",F="[object Uint8Array]",A="[object Uint8ClampedArray]",k="[object Uint16Array]",R="[object Uint32Array]",E={};E[m]=E[O]=E[w]=E[P]=E[S]=E[F]=E[A]=E[k]=E[R]=!0,E[c]=E[u]=E[x]=E[s]=E[j]=E[f]=E[p]=E[l]=E[h]=E[v]=E[y]=E[d]=E[b]=E[_]=E[g]=!1,t.exports=n},function(t,e,r){(function(t){var n=r(76),o="object"==typeof e&&e&&!e.nodeType&&e,a=o&&"object"==typeof t&&t&&!t.nodeType&&t,i=a&&a.exports===o,c=i&&n.process,u=function(){try{return c&&c.binding&&c.binding("util")}catch(t){}}();t.exports=u}).call(e,r(56)(t))},function(t,e,r){var n=r(80),o=n(Object.keys,Object);t.exports=o},function(t,e,r){var n=r(10),o=r(3),a=n(o,"DataView");t.exports=a},function(t,e,r){var n=r(10),o=r(3),a=n(o,"Promise");t.exports=a},function(t,e,r){var n=r(10),o=r(3),a=n(o,"Set");t.exports=a},function(t,e){function r(t,e){return null!=t&&o.call(t,e)}var n=Object.prototype,o=n.hasOwnProperty;t.exports=r},function(t,e,r){var n=r(157),o=/^\./,a=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,i=/\\(\\)?/g,c=n(function(t){var e=[];return o.test(t)&&e.push(""),t.replace(a,function(t,r,n,o){e.push(n?o.replace(i,"$1"):r||t)}),e});t.exports=c},function(t,e,r){function n(t){var e=o(t,function(t){return r.size===a&&r.clear(),t}),r=e.cache;return e}var o=r(158),a=500;t.exports=n},function(t,e,r){function n(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new TypeError(a);var r=function(){var n=arguments,o=e?e.apply(this,n):n[0],a=r.cache;if(a.has(o))return a.get(o);var i=t.apply(this,n);return r.cache=a.set(o,i)||a,i};return r.cache=new(n.Cache||o),r}var o=r(41),a="Expected a function";n.Cache=o,t.exports=n},function(t,e,r){"use strict";var n=r(160),o=r(161),a=r(162);t.exports=function(){function t(t,e,r,n,i,c){c!==a&&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 e(){return t}t.isRequired=t;var r={array:t,bool:t,func:t,number:t,object:t,string:t,symbol:t,any:t,arrayOf:e,element:t,instanceOf:e,node:t,objectOf:e,oneOf:e,oneOfType:e,shape:e,exact:e};return r.checkPropTypes=n,r.PropTypes=r,r}},function(t,e,r){"use strict";function n(t){return function(){return t}}var o=function(){};o.thatReturns=n,o.thatReturnsFalse=n(!1),o.thatReturnsTrue=n(!0),o.thatReturnsNull=n(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(t){return t},t.exports=o},function(t,e,r){"use strict";function n(t,e,r,n,a,i,c,u){if(o(e),!t){var s;if(void 0===e)s=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var f=[r,n,a,i,c,u],p=0;s=new Error(e.replace(/%s/g,function(){return f[p++]})),s.name="Invariant Violation"}throw s.framesToPop=1,s}}var o=function(t){};t.exports=n},function(t,e,r){"use strict";var n="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";t.exports=n},,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var o=r(2);Object.defineProperty(e,"createConnector",{enumerable:!0,get:function(){return n(o).default}})}])}); //# sourceMappingURL=Core.min.js.map
src/addons/Portal/Portal.js
Semantic-Org/Semantic-UI-React
import EventStack from '@semantic-ui-react/event-stack' import { handleRef, Ref } from '@fluentui/react-component-ref' import keyboardKey from 'keyboard-key' import _ from 'lodash' import PropTypes from 'prop-types' import React from 'react' import { ModernAutoControlledComponent as Component, customPropTypes, doesNodeContainClick, makeDebugger, } from '../../lib' import validateTrigger from './utils/validateTrigger' import PortalInner from './PortalInner' const debug = makeDebugger('portal') /** * A component that allows you to render children outside their parent. * @see Modal * @see Popup * @see Dimmer * @see Confirm */ class Portal extends Component { contentRef = React.createRef() triggerRef = React.createRef() latestDocumentMouseDownEvent = null componentWillUnmount() { // Clean up timers clearTimeout(this.mouseEnterTimer) clearTimeout(this.mouseLeaveTimer) } // ---------------------------------------- // Document Event Handlers // ---------------------------------------- handleDocumentMouseDown = (e) => { this.latestDocumentMouseDownEvent = e } handleDocumentClick = (e) => { const { closeOnDocumentClick } = this.props const currentMouseDownEvent = this.latestDocumentMouseDownEvent this.latestDocumentMouseDownEvent = null if ( !this.contentRef.current || // no portal doesNodeContainClick(this.triggerRef.current, e) || // event happened in trigger (delegate to trigger handlers) (currentMouseDownEvent && doesNodeContainClick(this.contentRef.current, currentMouseDownEvent)) || // event originated in the portal but was ended outside doesNodeContainClick(this.contentRef.current, e) // event happened in the portal ) { return } // ignore the click if (closeOnDocumentClick) { debug('handleDocumentClick()') this.close(e) } } handleEscape = (e) => { if (!this.props.closeOnEscape) return if (keyboardKey.getCode(e) !== keyboardKey.Escape) return debug('handleEscape()') this.close(e) } // ---------------------------------------- // Component Event Handlers // ---------------------------------------- handlePortalMouseLeave = (e) => { const { closeOnPortalMouseLeave, mouseLeaveDelay } = this.props if (!closeOnPortalMouseLeave) return // Do not close the portal when 'mouseleave' is triggered by children if (e.target !== this.contentRef.current) return debug('handlePortalMouseLeave()') this.mouseLeaveTimer = this.closeWithTimeout(e, mouseLeaveDelay) } handlePortalMouseEnter = () => { // In order to enable mousing from the trigger to the portal, we need to // clear the mouseleave timer that was set when leaving the trigger. const { closeOnPortalMouseLeave } = this.props if (!closeOnPortalMouseLeave) return debug('handlePortalMouseEnter()') clearTimeout(this.mouseLeaveTimer) } handleTriggerBlur = (e, ...rest) => { const { trigger, closeOnTriggerBlur } = this.props // Call original event handler _.invoke(trigger, 'props.onBlur', e, ...rest) // IE 11 doesn't work with relatedTarget in blur events const target = e.relatedTarget || document.activeElement // do not close if focus is given to the portal const didFocusPortal = _.invoke(this.contentRef.current, 'contains', target) if (!closeOnTriggerBlur || didFocusPortal) return debug('handleTriggerBlur()') this.close(e) } handleTriggerClick = (e, ...rest) => { const { trigger, closeOnTriggerClick, openOnTriggerClick } = this.props const { open } = this.state // Call original event handler _.invoke(trigger, 'props.onClick', e, ...rest) if (open && closeOnTriggerClick) { debug('handleTriggerClick() - close') this.close(e) } else if (!open && openOnTriggerClick) { debug('handleTriggerClick() - open') this.open(e) } } handleTriggerFocus = (e, ...rest) => { const { trigger, openOnTriggerFocus } = this.props // Call original event handler _.invoke(trigger, 'props.onFocus', e, ...rest) if (!openOnTriggerFocus) return debug('handleTriggerFocus()') this.open(e) } handleTriggerMouseLeave = (e, ...rest) => { clearTimeout(this.mouseEnterTimer) const { trigger, closeOnTriggerMouseLeave, mouseLeaveDelay } = this.props // Call original event handler _.invoke(trigger, 'props.onMouseLeave', e, ...rest) if (!closeOnTriggerMouseLeave) return debug('handleTriggerMouseLeave()') this.mouseLeaveTimer = this.closeWithTimeout(e, mouseLeaveDelay) } handleTriggerMouseEnter = (e, ...rest) => { clearTimeout(this.mouseLeaveTimer) const { trigger, mouseEnterDelay, openOnTriggerMouseEnter } = this.props // Call original event handler _.invoke(trigger, 'props.onMouseEnter', e, ...rest) if (!openOnTriggerMouseEnter) return debug('handleTriggerMouseEnter()') this.mouseEnterTimer = this.openWithTimeout(e, mouseEnterDelay) } // ---------------------------------------- // Behavior // ---------------------------------------- open = (e) => { debug('open()') _.invoke(this.props, 'onOpen', e, { ...this.props, open: true }) this.setState({ open: true }) } openWithTimeout = (e, delay) => { debug('openWithTimeout()', delay) // React wipes the entire event object and suggests using e.persist() if // you need the event for async access. However, even with e.persist // certain required props (e.g. currentTarget) are null so we're forced to clone. const eventClone = { ...e } return setTimeout(() => this.open(eventClone), delay || 0) } close = (e) => { debug('close()') this.setState({ open: false }) _.invoke(this.props, 'onClose', e, { ...this.props, open: false }) } closeWithTimeout = (e, delay) => { debug('closeWithTimeout()', delay) // React wipes the entire event object and suggests using e.persist() if // you need the event for async access. However, even with e.persist // certain required props (e.g. currentTarget) are null so we're forced to clone. const eventClone = { ...e } return setTimeout(() => this.close(eventClone), delay || 0) } handleMount = () => { debug('handleMount()') _.invoke(this.props, 'onMount', null, this.props) } handleUnmount = () => { debug('handleUnmount()') _.invoke(this.props, 'onUnmount', null, this.props) } handleTriggerRef = (c) => { debug('handleTriggerRef()') this.triggerRef.current = c handleRef(this.props.triggerRef, c) } render() { const { children, eventPool, mountNode, trigger } = this.props const { open } = this.state /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { validateTrigger(trigger) } return ( <> {open && ( <> <PortalInner innerRef={this.contentRef} mountNode={mountNode} onMount={this.handleMount} onUnmount={this.handleUnmount} > {children} </PortalInner> <EventStack name='mouseleave' on={this.handlePortalMouseLeave} pool={eventPool} target={this.contentRef} /> <EventStack name='mouseenter' on={this.handlePortalMouseEnter} pool={eventPool} target={this.contentRef} /> <EventStack name='mousedown' on={this.handleDocumentMouseDown} pool={eventPool} /> <EventStack name='click' on={this.handleDocumentClick} pool={eventPool} /> <EventStack name='keydown' on={this.handleEscape} pool={eventPool} /> </> )} {trigger && ( <Ref innerRef={this.handleTriggerRef}> {React.cloneElement(trigger, { onBlur: this.handleTriggerBlur, onClick: this.handleTriggerClick, onFocus: this.handleTriggerFocus, onMouseLeave: this.handleTriggerMouseLeave, onMouseEnter: this.handleTriggerMouseEnter, })} </Ref> )} </> ) } } Portal.propTypes = { /** Primary content. */ children: PropTypes.node.isRequired, /** Controls whether or not the portal should close when the document is clicked. */ closeOnDocumentClick: PropTypes.bool, /** Controls whether or not the portal should close when escape is pressed is displayed. */ closeOnEscape: PropTypes.bool, /** * Controls whether or not the portal should close when mousing out of the portal. * NOTE: This will prevent `closeOnTriggerMouseLeave` when mousing over the * gap from the trigger to the portal. */ closeOnPortalMouseLeave: PropTypes.bool, /** Controls whether or not the portal should close on blur of the trigger. */ closeOnTriggerBlur: PropTypes.bool, /** Controls whether or not the portal should close on click of the trigger. */ closeOnTriggerClick: PropTypes.bool, /** Controls whether or not the portal should close when mousing out of the trigger. */ closeOnTriggerMouseLeave: PropTypes.bool, /** Initial value of open. */ defaultOpen: PropTypes.bool, /** Event pool namespace that is used to handle component events */ eventPool: PropTypes.string, /** The node where the portal should mount. */ mountNode: PropTypes.any, /** Milliseconds to wait before opening on mouse over */ mouseEnterDelay: PropTypes.number, /** Milliseconds to wait before closing on mouse leave */ mouseLeaveDelay: PropTypes.number, /** * Called when a close event happens * * @param {SyntheticEvent} event - React's original SyntheticEvent. * @param {object} data - All props. */ onClose: PropTypes.func, /** * Called when the portal is mounted on the DOM. * * @param {null} * @param {object} data - All props. */ onMount: PropTypes.func, /** * Called when an open event happens * * @param {SyntheticEvent} event - React's original SyntheticEvent. * @param {object} data - All props. */ onOpen: PropTypes.func, /** * Called when the portal is unmounted from the DOM. * * @param {null} * @param {object} data - All props. */ onUnmount: PropTypes.func, /** Controls whether or not the portal is displayed. */ open: PropTypes.bool, /** Controls whether or not the portal should open when the trigger is clicked. */ openOnTriggerClick: PropTypes.bool, /** Controls whether or not the portal should open on focus of the trigger. */ openOnTriggerFocus: PropTypes.bool, /** Controls whether or not the portal should open when mousing over the trigger. */ openOnTriggerMouseEnter: PropTypes.bool, /** Element to be rendered in-place where the portal is defined. */ trigger: PropTypes.node, /** Called with a ref to the trigger node. */ triggerRef: customPropTypes.ref, } Portal.defaultProps = { closeOnDocumentClick: true, closeOnEscape: true, eventPool: 'default', openOnTriggerClick: true, } Portal.autoControlledProps = ['open'] Portal.Inner = PortalInner export default Portal
frontend/components/FeedbackModal.js
ryanhugh/searchneu
/* * This file is part of Search NEU and licensed under AGPL3. * See the license file in the root folder for details. */ import React from 'react'; import PropTypes from 'prop-types'; import { Transition } from 'react-transition-group'; import { Button, Icon, Modal, Header, TextArea, Input, Form, Message, } from 'semantic-ui-react'; import macros from './macros'; import request from './request'; // This file manages the two popups that asks for user information // 1. the feedback popup that shows up if you click the feedback button on the bottom of the page // 2. At one point, instead of the typeform, we had a similar popup appear asking if user's were interested // These popups display a messge and have a a text box for users to enter data, and then they sent this data to the backend class FeedbackModal extends React.Component { // The bool of whether the feedback form should be open or not // needs to be tracked in home.js // because it is set to true when clicking the buttons to open this Modal in Home.js // and is set to false through actions in this component. static propTypes = { closeForm: PropTypes.func.isRequired, feedbackModalOpen: PropTypes.bool.isRequired, isFeedback: PropTypes.bool, isHelpOut: PropTypes.bool, }; static defaultProps = { isFeedback: false, isHelpOut: false, }; constructor(props) { super(props); this.state = { // The value of the message box. messageValue: '', // The value of the contact box. contactValue: '', // Whether the message is visible or not. messageVisible: false, }; if (!props.isHelpOut && !props.isFeedback) { macros.error('popup has to either be ishelp out or isFeedback'); } this.onTextAreaChange = this.onTextAreaChange.bind(this); this.onContactChange = this.onContactChange.bind(this); this.hideMessage = this.hideMessage.bind(this); this.onSubmit = this.onSubmit.bind(this); } async onSubmit() { // Send an event to amplitude too, just for redundancy. macros.logAmplitudeEvent('Feedback', { text: this.state.messageValue, contact: this.state.contactValue }); const response = await request.post({ url: '/submitFeedback', body: { message: this.state.messageValue, contact: this.state.contactValue, }, }); if (response.error) { macros.error('Unable to submit feedback', response.error, this.state.messageValue, this.state.contactValue); } this.setState({ messageVisible: true, messageValue: '', contactValue: '', }); // Hide the message after 2 seconds setTimeout(() => { this.setState({ messageVisible: false, }); }, 2000); this.props.closeForm(); } onTextAreaChange(event) { this.setState({ messageValue: event.target.value, }); } onContactChange(event) { this.setState({ contactValue: event.target.value, }); } hideMessage() { this.setState({ messageVisible: false, }); } render() { const transitionStyles = { entering: { opacity: 0 }, entered: { opacity: 1 }, exited: { display: 'none', opacity: 0 }, }; let firstText; let secondBody; let header = null; if (this.props.isFeedback) { firstText = 'Find a bug in Search NEU? Find a query that dosen\'t come up with the results you were looking for? Have an idea for an improvement or just want to say hi? Drop a line below! Feel free to write whatever you want to and someone on the team will read it.'; secondBody = [ <p key='0'> By default this form is anonymous. Leave your name and/or email if you want us to be able to contact you. </p>, <Input name='contact' form='feedbackForm' className='formModalInput' onChange={ this.onContactChange } key='1' />, ]; header = 'Search NEU Feedback'; } else { header = 'Get Involved with Search NEU!'; firstText = 'Thanks for your interest! We\'d love to have more people help out with the project. We are looking for people for both introductory level roles and leadership roles. There\'s a lot of CS stuff (new features, etc) and non-CS stuff (posters, marketing, outreach, etc) that we could work on, so it is no problem at all if you don\'t have a lot of experience in CS! Everything is flexible, and we could help you learn some programming along the way if you want to work on the site 🙂. Leave your name and some way we can get in contact (Facebook URL, email, Fortnite username, etc) and someone will reach out!'; } return ( <div className='feedback-container'> <Transition in={ this.state.messageVisible } timeout={ 500 }> {(state) => { return ( <Message success className='alertMessage' header='Your submission was successful.' style={{ ...transitionStyles[state] }} onDismiss={ this.hideMessage } /> ); }} </Transition> <Modal open={ this.props.feedbackModalOpen } onClose={ this.props.closeForm } size='small' className='feedback-modal-container'> <Header icon='mail' content={ header } /> <Modal.Content className='formModalContent'> <Form> <div className='feedbackParagraph'> {firstText} </div> <TextArea name='response' form='feedbackForm' className='feedbackTextbox' onChange={ this.onTextAreaChange } /> {secondBody} </Form> </Modal.Content> <Modal.Actions> <Button basic color='red' onClick={ this.props.closeForm }> <Icon name='remove' /> Cancel </Button> <Button type='submit' color='green' form='feedbackForm' onClick={ this.onSubmit }> <Icon name='checkmark' /> Submit </Button> </Modal.Actions> </Modal> </div> ); } } export default FeedbackModal;
client/src/pages/dashboard/FeedItem.js
ccwukong/lfcommerce-react
import React from 'react'; import PropTypes from 'prop-types'; import { Card, CardTitle, } from 'reactstrap'; const FeedItem = props => { const { backgroundColor, fontColor, title, content, datetime } = props; return ( <Card body style={{ marginTop: 10, background: backgroundColor || '#fff' }}> <CardTitle style={{ color: fontColor || '#000', fontWeight: 200 }}> {title} </CardTitle> <div className="text-muted">{datetime}</div> <div className="text-muted">{content}</div> </Card> ); }; FeedItem.propTypes = { backgroundColor: PropTypes.string.isRequired, title: PropTypes.string.isRequired, fontColor: PropTypes.string.isRequired, content: PropTypes.string.isRequired, datetime: PropTypes.string.isRequired, }; export default FeedItem;
web/src/js/__tests__/components/ContentView/DownloadContentButtonSpec.js
StevenVanAcker/mitmproxy
import React from 'react' import renderer from 'react-test-renderer' import DownloadContentButton from '../../../components/ContentView/DownloadContentButton' import { TFlow } from '../../ducks/tutils' let tflow = new TFlow() describe('DownloadContentButton Component', () => { it('should render correctly', () => { let downloadContentButton = renderer.create( <DownloadContentButton flow={tflow} message={tflow.response}/> ), tree = downloadContentButton.toJSON() expect(tree).toMatchSnapshot() }) })
src/svg-icons/image/flash-off.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFlashOff = (props) => ( <SvgIcon {...props}> <path d="M3.27 3L2 4.27l5 5V13h3v9l3.58-6.14L17.73 20 19 18.73 3.27 3zM17 10h-4l4-8H7v2.18l8.46 8.46L17 10z"/> </SvgIcon> ); ImageFlashOff = pure(ImageFlashOff); ImageFlashOff.displayName = 'ImageFlashOff'; ImageFlashOff.muiName = 'SvgIcon'; export default ImageFlashOff;
packages/lore-tutorial/templates/es6/step16/src/components/CreateButton.js
lore/lore
import React from 'react'; export default class CreateButton extends React.Component { getStyles() { return { createButton: { position: 'absolute', top: '25px', right: '15px', zIndex: 1000, borderRadius: '100px', outline: 'none' } } } onClick() { function createTweet(params) { console.log(params); } lore.dialog.show(function() { return lore.dialogs.tweet.create({ onSubmit: createTweet }); }) } render() { const styles = this.getStyles(); return ( <button type="button" className="btn btn-primary btn-lg" style={styles.createButton} onClick={this.onClick}> + </button> ); } }
admin/client/App/shared/Popout/index.js
matthewstyers/keystone
/** * A Popout component. * One can also add a Header (Popout/Header), a Footer * (Popout/Footer), a Body (Popout/Body) and a Pan (Popout/Pane). */ import React from 'react'; import Portal from '../Portal'; import Transition from 'react-addons-css-transition-group'; const SIZES = { arrowHeight: 12, arrowWidth: 16, horizontalMargin: 20, }; var Popout = React.createClass({ displayName: 'Popout', propTypes: { isOpen: React.PropTypes.bool, onCancel: React.PropTypes.func, onSubmit: React.PropTypes.func, relativeToID: React.PropTypes.string.isRequired, width: React.PropTypes.number, }, getDefaultProps () { return { width: 320, }; }, getInitialState () { return {}; }, componentWillReceiveProps (nextProps) { if (!this.props.isOpen && nextProps.isOpen) { window.addEventListener('resize', this.calculatePosition); this.calculatePosition(nextProps.isOpen); } else if (this.props.isOpen && !nextProps.isOpen) { window.removeEventListener('resize', this.calculatePosition); } }, getPortalDOMNode () { return this.refs.portal.getPortalDOMNode(); }, calculatePosition (isOpen) { if (!isOpen) return; let posNode = document.getElementById(this.props.relativeToID); const pos = { top: 0, left: 0, width: posNode.offsetWidth, height: posNode.offsetHeight, }; while (posNode.offsetParent) { pos.top += posNode.offsetTop; pos.left += posNode.offsetLeft; posNode = posNode.offsetParent; } let leftOffset = Math.max(pos.left + (pos.width / 2) - (this.props.width / 2), SIZES.horizontalMargin); let topOffset = pos.top + pos.height + SIZES.arrowHeight; var spaceOnRight = window.innerWidth - (leftOffset + this.props.width + SIZES.horizontalMargin); if (spaceOnRight < 0) { leftOffset = leftOffset + spaceOnRight; } const arrowLeftOffset = leftOffset === SIZES.horizontalMargin ? pos.left + (pos.width / 2) - (SIZES.arrowWidth / 2) - SIZES.horizontalMargin : null; const newStateAvaliable = this.state.leftOffset !== leftOffset || this.state.topOffset !== topOffset || this.state.arrowLeftOffset !== arrowLeftOffset; if (newStateAvaliable) { this.setState({ leftOffset: leftOffset, topOffset: topOffset, arrowLeftOffset: arrowLeftOffset, }); } }, renderPopout () { if (!this.props.isOpen) return; const { arrowLeftOffset, leftOffset, topOffset } = this.state; const arrowStyles = arrowLeftOffset ? { left: 0, marginLeft: arrowLeftOffset } : null; return ( <div className="Popout" style={{ left: leftOffset, top: topOffset, width: this.props.width, }} > <span className="Popout__arrow" style={arrowStyles} /> <div className="Popout__inner"> {this.props.children} </div> </div> ); }, renderBlockout () { if (!this.props.isOpen) return; return <div className="blockout" onClick={this.props.onCancel} />; }, render () { return ( <Portal className="Popout-wrapper" ref="portal"> <Transition className="Popout-animation" transitionEnterTimeout={190} transitionLeaveTimeout={190} transitionName="Popout" component="div" > {this.renderPopout()} </Transition> {this.renderBlockout()} </Portal> ); }, }); module.exports = Popout; // expose the child to the top level export module.exports.Header = require('./PopoutHeader'); module.exports.Body = require('./PopoutBody'); module.exports.Footer = require('./PopoutFooter'); module.exports.Pane = require('./PopoutPane');
ajax/libs/webshim/1.14.3/dev/shims/moxie/js/moxie.js
codevinsky/cdnjs
/** * mOxie - multi-runtime File API & XMLHttpRequest L2 Polyfill * v1.2.1 * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing * * Date: 2014-05-14 */ /** * Compiled inline version. (Library mode) */ /*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ /*globals $code */ (function(exports, undefined) { "use strict"; var modules = {}; function require(ids, callback) { var module, defs = []; for (var i = 0; i < ids.length; ++i) { module = modules[ids[i]] || resolve(ids[i]); if (!module) { throw 'module definition dependecy not found: ' + ids[i]; } defs.push(module); } callback.apply(null, defs); } function define(id, dependencies, definition) { if (typeof id !== 'string') { throw 'invalid module definition, module id must be defined and be a string'; } if (dependencies === undefined) { throw 'invalid module definition, dependencies must be specified'; } if (definition === undefined) { throw 'invalid module definition, definition function must be specified'; } require(dependencies, function() { modules[id] = definition.apply(null, arguments); }); } function defined(id) { return !!modules[id]; } function resolve(id) { var target = exports; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length; ++fi) { if (!target[fragments[fi]]) { return; } target = target[fragments[fi]]; } return target; } function expose(ids) { for (var i = 0; i < ids.length; i++) { var target = exports; var id = ids[i]; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length - 1; ++fi) { if (target[fragments[fi]] === undefined) { target[fragments[fi]] = {}; } target = target[fragments[fi]]; } target[fragments[fragments.length - 1]] = modules[id]; } } // Included from: src/javascript/core/utils/Basic.js /** * Basic.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Basic', [], function() { /** Gets the true type of the built-in object (better version of typeof). @author Angus Croll (http://javascriptweblog.wordpress.com/) @method typeOf @for Utils @static @param {Object} o Object to check. @return {String} Object [[Class]] */ var typeOf = function(o) { var undef; if (o === undef) { return 'undefined'; } else if (o === null) { return 'null'; } else if (o.nodeType) { return 'node'; } // the snippet below is awesome, however it fails to detect null, undefined and arguments types in IE lte 8 return ({}).toString.call(o).match(/\s([a-z|A-Z]+)/)[1].toLowerCase(); }; /** Extends the specified object with another object. @method extend @static @param {Object} target Object to extend. @param {Object} [obj]* Multiple objects to extend with. @return {Object} Same as target, the extended object. */ var extend = function(target) { var undef; each(arguments, function(arg, i) { if (i > 0) { each(arg, function(value, key) { if (value !== undef) { if (typeOf(target[key]) === typeOf(value) && !!~inArray(typeOf(value), ['array', 'object'])) { extend(target[key], value); } else { target[key] = value; } } }); } }); return target; }; /** Executes the callback function for each item in array/object. If you return false in the callback it will break the loop. @method each @static @param {Object} obj Object to iterate. @param {function} callback Callback function to execute for each item. */ var each = function(obj, callback) { var length, key, i, undef; if (obj) { try { length = obj.length; } catch(ex) { length = undef; } if (length === undef) { // Loop object items for (key in obj) { if (obj.hasOwnProperty(key)) { if (callback(obj[key], key) === false) { return; } } } } else { // Loop array items for (i = 0; i < length; i++) { if (callback(obj[i], i) === false) { return; } } } } }; /** Checks if object is empty. @method isEmptyObj @static @param {Object} o Object to check. @return {Boolean} */ var isEmptyObj = function(obj) { var prop; if (!obj || typeOf(obj) !== 'object') { return true; } for (prop in obj) { return false; } return true; }; /** Recieve an array of functions (usually async) to call in sequence, each function receives a callback as first argument that it should call, when it completes. Finally, after everything is complete, main callback is called. Passing truthy value to the callback as a first argument will interrupt the sequence and invoke main callback immediately. @method inSeries @static @param {Array} queue Array of functions to call in sequence @param {Function} cb Main callback that is called in the end, or in case of error */ var inSeries = function(queue, cb) { var i = 0, length = queue.length; if (typeOf(cb) !== 'function') { cb = function() {}; } if (!queue || !queue.length) { cb(); } function callNext(i) { if (typeOf(queue[i]) === 'function') { queue[i](function(error) { /*jshint expr:true */ ++i < length && !error ? callNext(i) : cb(error); }); } } callNext(i); }; /** Recieve an array of functions (usually async) to call in parallel, each function receives a callback as first argument that it should call, when it completes. After everything is complete, main callback is called. Passing truthy value to the callback as a first argument will interrupt the process and invoke main callback immediately. @method inParallel @static @param {Array} queue Array of functions to call in sequence @param {Function} cb Main callback that is called in the end, or in case of erro */ var inParallel = function(queue, cb) { var count = 0, num = queue.length, cbArgs = new Array(num); each(queue, function(fn, i) { fn(function(error) { if (error) { return cb(error); } var args = [].slice.call(arguments); args.shift(); // strip error - undefined or not cbArgs[i] = args; count++; if (count === num) { cbArgs.unshift(null); cb.apply(this, cbArgs); } }); }); }; /** Find an element in array and return it's index if present, otherwise return -1. @method inArray @static @param {Mixed} needle Element to find @param {Array} array @return {Int} Index of the element, or -1 if not found */ var inArray = function(needle, array) { if (array) { if (Array.prototype.indexOf) { return Array.prototype.indexOf.call(array, needle); } for (var i = 0, length = array.length; i < length; i++) { if (array[i] === needle) { return i; } } } return -1; }; /** Returns elements of first array if they are not present in second. And false - otherwise. @private @method arrayDiff @param {Array} needles @param {Array} array @return {Array|Boolean} */ var arrayDiff = function(needles, array) { var diff = []; if (typeOf(needles) !== 'array') { needles = [needles]; } if (typeOf(array) !== 'array') { array = [array]; } for (var i in needles) { if (inArray(needles[i], array) === -1) { diff.push(needles[i]); } } return diff.length ? diff : false; }; /** Find intersection of two arrays. @private @method arrayIntersect @param {Array} array1 @param {Array} array2 @return {Array} Intersection of two arrays or null if there is none */ var arrayIntersect = function(array1, array2) { var result = []; each(array1, function(item) { if (inArray(item, array2) !== -1) { result.push(item); } }); return result.length ? result : null; }; /** Forces anything into an array. @method toArray @static @param {Object} obj Object with length field. @return {Array} Array object containing all items. */ var toArray = function(obj) { var i, arr = []; for (i = 0; i < obj.length; i++) { arr[i] = obj[i]; } return arr; }; /** Generates an unique ID. This is 99.99% unique since it takes the current time and 5 random numbers. The only way a user would be able to get the same ID is if the two persons at the same exact milisecond manages to get 5 the same random numbers between 0-65535 it also uses a counter so each call will be guaranteed to be page unique. It's more probable for the earth to be hit with an ansteriod. Y @method guid @static @param {String} prefix to prepend (by default 'o' will be prepended). @method guid @return {String} Virtually unique id. */ var guid = (function() { var counter = 0; return function(prefix) { var guid = new Date().getTime().toString(32), i; for (i = 0; i < 5; i++) { guid += Math.floor(Math.random() * 65535).toString(32); } return (prefix || 'o_') + guid + (counter++).toString(32); }; }()); /** Trims white spaces around the string @method trim @static @param {String} str @return {String} */ var trim = function(str) { if (!str) { return str; } return String.prototype.trim ? String.prototype.trim.call(str) : str.toString().replace(/^\s*/, '').replace(/\s*$/, ''); }; /** Parses the specified size string into a byte value. For example 10kb becomes 10240. @method parseSizeStr @static @param {String/Number} size String to parse or number to just pass through. @return {Number} Size in bytes. */ var parseSizeStr = function(size) { if (typeof(size) !== 'string') { return size; } var muls = { t: 1099511627776, g: 1073741824, m: 1048576, k: 1024 }, mul; size = /^([0-9]+)([mgk]?)$/.exec(size.toLowerCase().replace(/[^0-9mkg]/g, '')); mul = size[2]; size = +size[1]; if (muls.hasOwnProperty(mul)) { size *= muls[mul]; } return size; }; return { guid: guid, typeOf: typeOf, extend: extend, each: each, isEmptyObj: isEmptyObj, inSeries: inSeries, inParallel: inParallel, inArray: inArray, arrayDiff: arrayDiff, arrayIntersect: arrayIntersect, toArray: toArray, trim: trim, parseSizeStr: parseSizeStr }; }); // Included from: src/javascript/core/I18n.js /** * I18n.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/I18n", [ "moxie/core/utils/Basic" ], function(Basic) { var i18n = {}; return { /** * Extends the language pack object with new items. * * @param {Object} pack Language pack items to add. * @return {Object} Extended language pack object. */ addI18n: function(pack) { return Basic.extend(i18n, pack); }, /** * Translates the specified string by checking for the english string in the language pack lookup. * * @param {String} str String to look for. * @return {String} Translated string or the input string if it wasn't found. */ translate: function(str) { return i18n[str] || str; }, /** * Shortcut for translate function * * @param {String} str String to look for. * @return {String} Translated string or the input string if it wasn't found. */ _: function(str) { return this.translate(str); }, /** * Pseudo sprintf implementation - simple way to replace tokens with specified values. * * @param {String} str String with tokens * @return {String} String with replaced tokens */ sprintf: function(str) { var args = [].slice.call(arguments, 1); return str.replace(/%[a-z]/g, function() { var value = args.shift(); return Basic.typeOf(value) !== 'undefined' ? value : ''; }); } }; }); // Included from: src/javascript/core/utils/Mime.js /** * Mime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/utils/Mime", [ "moxie/core/utils/Basic", "moxie/core/I18n" ], function(Basic, I18n) { var mimeData = "" + "application/msword,doc dot," + "application/pdf,pdf," + "application/pgp-signature,pgp," + "application/postscript,ps ai eps," + "application/rtf,rtf," + "application/vnd.ms-excel,xls xlb," + "application/vnd.ms-powerpoint,ppt pps pot," + "application/zip,zip," + "application/x-shockwave-flash,swf swfl," + "application/vnd.openxmlformats-officedocument.wordprocessingml.document,docx," + "application/vnd.openxmlformats-officedocument.wordprocessingml.template,dotx," + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,xlsx," + "application/vnd.openxmlformats-officedocument.presentationml.presentation,pptx," + "application/vnd.openxmlformats-officedocument.presentationml.template,potx," + "application/vnd.openxmlformats-officedocument.presentationml.slideshow,ppsx," + "application/x-javascript,js," + "application/json,json," + "audio/mpeg,mp3 mpga mpega mp2," + "audio/x-wav,wav," + "audio/x-m4a,m4a," + "audio/ogg,oga ogg," + "audio/aiff,aiff aif," + "audio/flac,flac," + "audio/aac,aac," + "audio/ac3,ac3," + "audio/x-ms-wma,wma," + "image/bmp,bmp," + "image/gif,gif," + "image/jpeg,jpg jpeg jpe," + "image/photoshop,psd," + "image/png,png," + "image/svg+xml,svg svgz," + "image/tiff,tiff tif," + "text/plain,asc txt text diff log," + "text/html,htm html xhtml," + "text/css,css," + "text/csv,csv," + "text/rtf,rtf," + "video/mpeg,mpeg mpg mpe m2v," + "video/quicktime,qt mov," + "video/mp4,mp4," + "video/x-m4v,m4v," + "video/x-flv,flv," + "video/x-ms-wmv,wmv," + "video/avi,avi," + "video/webm,webm," + "video/3gpp,3gpp 3gp," + "video/3gpp2,3g2," + "video/vnd.rn-realvideo,rv," + "video/ogg,ogv," + "video/x-matroska,mkv," + "application/vnd.oasis.opendocument.formula-template,otf," + "application/octet-stream,exe"; var Mime = { mimes: {}, extensions: {}, // Parses the default mime types string into a mimes and extensions lookup maps addMimeType: function (mimeData) { var items = mimeData.split(/,/), i, ii, ext; for (i = 0; i < items.length; i += 2) { ext = items[i + 1].split(/ /); // extension to mime lookup for (ii = 0; ii < ext.length; ii++) { this.mimes[ext[ii]] = items[i]; } // mime to extension lookup this.extensions[items[i]] = ext; } }, extList2mimes: function (filters, addMissingExtensions) { var self = this, ext, i, ii, type, mimes = []; // convert extensions to mime types list for (i = 0; i < filters.length; i++) { ext = filters[i].extensions.split(/\s*,\s*/); for (ii = 0; ii < ext.length; ii++) { // if there's an asterisk in the list, then accept attribute is not required if (ext[ii] === '*') { return []; } type = self.mimes[ext[ii]]; if (!type) { if (addMissingExtensions && /^\w+$/.test(ext[ii])) { mimes.push('.' + ext[ii]); } else { return []; // accept all } } else if (Basic.inArray(type, mimes) === -1) { mimes.push(type); } } } return mimes; }, mimes2exts: function(mimes) { var self = this, exts = []; Basic.each(mimes, function(mime) { if (mime === '*') { exts = []; return false; } // check if this thing looks like mime type var m = mime.match(/^(\w+)\/(\*|\w+)$/); if (m) { if (m[2] === '*') { // wildcard mime type detected Basic.each(self.extensions, function(arr, mime) { if ((new RegExp('^' + m[1] + '/')).test(mime)) { [].push.apply(exts, self.extensions[mime]); } }); } else if (self.extensions[mime]) { [].push.apply(exts, self.extensions[mime]); } } }); return exts; }, mimes2extList: function(mimes) { var accept = [], exts = []; if (Basic.typeOf(mimes) === 'string') { mimes = Basic.trim(mimes).split(/\s*,\s*/); } exts = this.mimes2exts(mimes); accept.push({ title: I18n.translate('Files'), extensions: exts.length ? exts.join(',') : '*' }); // save original mimes string accept.mimes = mimes; return accept; }, getFileExtension: function(fileName) { var matches = fileName && fileName.match(/\.([^.]+)$/); if (matches) { return matches[1].toLowerCase(); } return ''; }, getFileMime: function(fileName) { return this.mimes[this.getFileExtension(fileName)] || ''; } }; Mime.addMimeType(mimeData); return Mime; }); // Included from: src/javascript/core/utils/Env.js /** * Env.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/utils/Env", [ "moxie/core/utils/Basic" ], function(Basic) { // UAParser.js v0.6.2 // Lightweight JavaScript-based User-Agent string parser // https://github.com/faisalman/ua-parser-js // // Copyright © 2012-2013 Faisalman <fyzlman@gmail.com> // Dual licensed under GPLv2 & MIT var UAParser = (function (undefined) { ////////////// // Constants ///////////// var EMPTY = '', UNKNOWN = '?', FUNC_TYPE = 'function', UNDEF_TYPE = 'undefined', OBJ_TYPE = 'object', MAJOR = 'major', MODEL = 'model', NAME = 'name', TYPE = 'type', VENDOR = 'vendor', VERSION = 'version', ARCHITECTURE= 'architecture', CONSOLE = 'console', MOBILE = 'mobile', TABLET = 'tablet'; /////////// // Helper ////////// var util = { has : function (str1, str2) { return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1; }, lowerize : function (str) { return str.toLowerCase(); } }; /////////////// // Map helper ////////////// var mapper = { rgx : function () { // loop through all regexes maps for (var result, i = 0, j, k, p, q, matches, match, args = arguments; i < args.length; i += 2) { var regex = args[i], // even sequence (0,2,4,..) props = args[i + 1]; // odd sequence (1,3,5,..) // construct object barebones if (typeof(result) === UNDEF_TYPE) { result = {}; for (p in props) { q = props[p]; if (typeof(q) === OBJ_TYPE) { result[q[0]] = undefined; } else { result[q] = undefined; } } } // try matching uastring with regexes for (j = k = 0; j < regex.length; j++) { matches = regex[j].exec(this.getUA()); if (!!matches) { for (p = 0; p < props.length; p++) { match = matches[++k]; q = props[p]; // check if given property is actually array if (typeof(q) === OBJ_TYPE && q.length > 0) { if (q.length == 2) { if (typeof(q[1]) == FUNC_TYPE) { // assign modified match result[q[0]] = q[1].call(this, match); } else { // assign given value, ignore regex match result[q[0]] = q[1]; } } else if (q.length == 3) { // check whether function or regex if (typeof(q[1]) === FUNC_TYPE && !(q[1].exec && q[1].test)) { // call function (usually string mapper) result[q[0]] = match ? q[1].call(this, match, q[2]) : undefined; } else { // sanitize match using given regex result[q[0]] = match ? match.replace(q[1], q[2]) : undefined; } } else if (q.length == 4) { result[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined; } } else { result[q] = match ? match : undefined; } } break; } } if(!!matches) break; // break the loop immediately if match found } return result; }, str : function (str, map) { for (var i in map) { // check if array if (typeof(map[i]) === OBJ_TYPE && map[i].length > 0) { for (var j = 0; j < map[i].length; j++) { if (util.has(map[i][j], str)) { return (i === UNKNOWN) ? undefined : i; } } } else if (util.has(map[i], str)) { return (i === UNKNOWN) ? undefined : i; } } return str; } }; /////////////// // String map ////////////// var maps = { browser : { oldsafari : { major : { '1' : ['/8', '/1', '/3'], '2' : '/4', '?' : '/' }, version : { '1.0' : '/8', '1.2' : '/1', '1.3' : '/3', '2.0' : '/412', '2.0.2' : '/416', '2.0.3' : '/417', '2.0.4' : '/419', '?' : '/' } } }, device : { sprint : { model : { 'Evo Shift 4G' : '7373KT' }, vendor : { 'HTC' : 'APA', 'Sprint' : 'Sprint' } } }, os : { windows : { version : { 'ME' : '4.90', 'NT 3.11' : 'NT3.51', 'NT 4.0' : 'NT4.0', '2000' : 'NT 5.0', 'XP' : ['NT 5.1', 'NT 5.2'], 'Vista' : 'NT 6.0', '7' : 'NT 6.1', '8' : 'NT 6.2', '8.1' : 'NT 6.3', 'RT' : 'ARM' } } } }; ////////////// // Regex map ///////////// var regexes = { browser : [[ // Presto based /(opera\smini)\/((\d+)?[\w\.-]+)/i, // Opera Mini /(opera\s[mobiletab]+).+version\/((\d+)?[\w\.-]+)/i, // Opera Mobi/Tablet /(opera).+version\/((\d+)?[\w\.]+)/i, // Opera > 9.80 /(opera)[\/\s]+((\d+)?[\w\.]+)/i // Opera < 9.80 ], [NAME, VERSION, MAJOR], [ /\s(opr)\/((\d+)?[\w\.]+)/i // Opera Webkit ], [[NAME, 'Opera'], VERSION, MAJOR], [ // Mixed /(kindle)\/((\d+)?[\w\.]+)/i, // Kindle /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?((\d+)?[\w\.]+)*/i, // Lunascape/Maxthon/Netfront/Jasmine/Blazer // Trident based /(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?((\d+)?[\w\.]*)/i, // Avant/IEMobile/SlimBrowser/Baidu /(?:ms|\()(ie)\s((\d+)?[\w\.]+)/i, // Internet Explorer // Webkit/KHTML based /(rekonq)((?:\/)[\w\.]+)*/i, // Rekonq /(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron)\/((\d+)?[\w\.-]+)/i // Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron ], [NAME, VERSION, MAJOR], [ /(trident).+rv[:\s]((\d+)?[\w\.]+).+like\sgecko/i // IE11 ], [[NAME, 'IE'], VERSION, MAJOR], [ /(yabrowser)\/((\d+)?[\w\.]+)/i // Yandex ], [[NAME, 'Yandex'], VERSION, MAJOR], [ /(comodo_dragon)\/((\d+)?[\w\.]+)/i // Comodo Dragon ], [[NAME, /_/g, ' '], VERSION, MAJOR], [ /(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?((\d+)?[\w\.]+)/i // Chrome/OmniWeb/Arora/Tizen/Nokia ], [NAME, VERSION, MAJOR], [ /(dolfin)\/((\d+)?[\w\.]+)/i // Dolphin ], [[NAME, 'Dolphin'], VERSION, MAJOR], [ /((?:android.+)crmo|crios)\/((\d+)?[\w\.]+)/i // Chrome for Android/iOS ], [[NAME, 'Chrome'], VERSION, MAJOR], [ /((?:android.+))version\/((\d+)?[\w\.]+)\smobile\ssafari/i // Android Browser ], [[NAME, 'Android Browser'], VERSION, MAJOR], [ /version\/((\d+)?[\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari ], [VERSION, MAJOR, [NAME, 'Mobile Safari']], [ /version\/((\d+)?[\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile ], [VERSION, MAJOR, NAME], [ /webkit.+?(mobile\s?safari|safari)((\/[\w\.]+))/i // Safari < 3.0 ], [NAME, [MAJOR, mapper.str, maps.browser.oldsafari.major], [VERSION, mapper.str, maps.browser.oldsafari.version]], [ /(konqueror)\/((\d+)?[\w\.]+)/i, // Konqueror /(webkit|khtml)\/((\d+)?[\w\.]+)/i ], [NAME, VERSION, MAJOR], [ // Gecko based /(navigator|netscape)\/((\d+)?[\w\.-]+)/i // Netscape ], [[NAME, 'Netscape'], VERSION, MAJOR], [ /(swiftfox)/i, // Swiftfox /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?((\d+)?[\w\.\+]+)/i, // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/((\d+)?[\w\.-]+)/i, // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix /(mozilla)\/((\d+)?[\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla // Other /(uc\s?browser|polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|qqbrowser)[\/\s]?((\d+)?[\w\.]+)/i, // UCBrowser/Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/QQBrowser /(links)\s\(((\d+)?[\w\.]+)/i, // Links /(gobrowser)\/?((\d+)?[\w\.]+)*/i, // GoBrowser /(ice\s?browser)\/v?((\d+)?[\w\._]+)/i, // ICE Browser /(mosaic)[\/\s]((\d+)?[\w\.]+)/i // Mosaic ], [NAME, VERSION, MAJOR] ], engine : [[ /(presto)\/([\w\.]+)/i, // Presto /(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links /(icab)[\/\s]([23]\.[\d\.]+)/i // iCab ], [NAME, VERSION], [ /rv\:([\w\.]+).*(gecko)/i // Gecko ], [VERSION, NAME] ], os : [[ // Windows based /(windows)\snt\s6\.2;\s(arm)/i, // Windows RT /(windows\sphone(?:\sos)*|windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i ], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [ /(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i ], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [ // Mobile/Embedded OS /\((bb)(10);/i // BlackBerry 10 ], [[NAME, 'BlackBerry'], VERSION], [ /(blackberry)\w*\/?([\w\.]+)*/i, // Blackberry /(tizen)\/([\w\.]+)/i, // Tizen /(android|webos|palm\os|qnx|bada|rim\stablet\sos|meego)[\/\s-]?([\w\.]+)*/i // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo ], [NAME, VERSION], [ /(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i // Symbian ], [[NAME, 'Symbian'], VERSION],[ /mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS ], [[NAME, 'Firefox OS'], VERSION], [ // Console /(nintendo|playstation)\s([wids3portablevu]+)/i, // Nintendo/Playstation // GNU/Linux based /(mint)[\/\s\(]?(\w+)*/i, // Mint /(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk)[\/\s-]?([\w\.-]+)*/i, // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk /(hurd|linux)\s?([\w\.]+)*/i, // Hurd/Linux /(gnu)\s?([\w\.]+)*/i // GNU ], [NAME, VERSION], [ /(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS ], [[NAME, 'Chromium OS'], VERSION],[ // Solaris /(sunos)\s?([\w\.]+\d)*/i // Solaris ], [[NAME, 'Solaris'], VERSION], [ // BSD based /\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly ], [NAME, VERSION],[ /(ip[honead]+)(?:.*os\s*([\w]+)*\slike\smac|;\sopera)/i // iOS ], [[NAME, 'iOS'], [VERSION, /_/g, '.']], [ /(mac\sos\sx)\s?([\w\s\.]+\w)*/i // Mac OS ], [NAME, [VERSION, /_/g, '.']], [ // Other /(haiku)\s(\w+)/i, // Haiku /(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i, // AIX /(macintosh|mac(?=_powerpc)|plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos)/i, // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS /(unix)\s?([\w\.]+)*/i // UNIX ], [NAME, VERSION] ] }; ///////////////// // Constructor //////////////// var UAParser = function (uastring) { var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY); this.getBrowser = function () { return mapper.rgx.apply(this, regexes.browser); }; this.getEngine = function () { return mapper.rgx.apply(this, regexes.engine); }; this.getOS = function () { return mapper.rgx.apply(this, regexes.os); }; this.getResult = function() { return { ua : this.getUA(), browser : this.getBrowser(), engine : this.getEngine(), os : this.getOS() }; }; this.getUA = function () { return ua; }; this.setUA = function (uastring) { ua = uastring; return this; }; this.setUA(ua); }; return new UAParser().getResult(); })(); function version_compare(v1, v2, operator) { // From: http://phpjs.org/functions // + original by: Philippe Jausions (http://pear.php.net/user/jausions) // + original by: Aidan Lister (http://aidanlister.com/) // + reimplemented by: Kankrelune (http://www.webfaktory.info/) // + improved by: Brett Zamir (http://brett-zamir.me) // + improved by: Scott Baker // + improved by: Theriault // * example 1: version_compare('8.2.5rc', '8.2.5a'); // * returns 1: 1 // * example 2: version_compare('8.2.50', '8.2.52', '<'); // * returns 2: true // * example 3: version_compare('5.3.0-dev', '5.3.0'); // * returns 3: -1 // * example 4: version_compare('4.1.0.52','4.01.0.51'); // * returns 4: 1 // Important: compare must be initialized at 0. var i = 0, x = 0, compare = 0, // vm maps textual PHP versions to negatives so they're less than 0. // PHP currently defines these as CASE-SENSITIVE. It is important to // leave these as negatives so that they can come before numerical versions // and as if no letters were there to begin with. // (1alpha is < 1 and < 1.1 but > 1dev1) // If a non-numerical value can't be mapped to this table, it receives // -7 as its value. vm = { 'dev': -6, 'alpha': -5, 'a': -5, 'beta': -4, 'b': -4, 'RC': -3, 'rc': -3, '#': -2, 'p': 1, 'pl': 1 }, // This function will be called to prepare each version argument. // It replaces every _, -, and + with a dot. // It surrounds any nonsequence of numbers/dots with dots. // It replaces sequences of dots with a single dot. // version_compare('4..0', '4.0') == 0 // Important: A string of 0 length needs to be converted into a value // even less than an unexisting value in vm (-7), hence [-8]. // It's also important to not strip spaces because of this. // version_compare('', ' ') == 1 prepVersion = function (v) { v = ('' + v).replace(/[_\-+]/g, '.'); v = v.replace(/([^.\d]+)/g, '.$1.').replace(/\.{2,}/g, '.'); return (!v.length ? [-8] : v.split('.')); }, // This converts a version component to a number. // Empty component becomes 0. // Non-numerical component becomes a negative number. // Numerical component becomes itself as an integer. numVersion = function (v) { return !v ? 0 : (isNaN(v) ? vm[v] || -7 : parseInt(v, 10)); }; v1 = prepVersion(v1); v2 = prepVersion(v2); x = Math.max(v1.length, v2.length); for (i = 0; i < x; i++) { if (v1[i] == v2[i]) { continue; } v1[i] = numVersion(v1[i]); v2[i] = numVersion(v2[i]); if (v1[i] < v2[i]) { compare = -1; break; } else if (v1[i] > v2[i]) { compare = 1; break; } } if (!operator) { return compare; } // Important: operator is CASE-SENSITIVE. // "No operator" seems to be treated as "<." // Any other values seem to make the function return null. switch (operator) { case '>': case 'gt': return (compare > 0); case '>=': case 'ge': return (compare >= 0); case '<=': case 'le': return (compare <= 0); case '==': case '=': case 'eq': return (compare === 0); case '<>': case '!=': case 'ne': return (compare !== 0); case '': case '<': case 'lt': return (compare < 0); default: return null; } } var can = (function() { var caps = { define_property: (function() { /* // currently too much extra code required, not exactly worth it try { // as of IE8, getters/setters are supported only on DOM elements var obj = {}; if (Object.defineProperty) { Object.defineProperty(obj, 'prop', { enumerable: true, configurable: true }); return true; } } catch(ex) {} if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) { return true; }*/ return false; }()), create_canvas: (function() { // On the S60 and BB Storm, getContext exists, but always returns undefined // so we actually have to call getContext() to verify // github.com/Modernizr/Modernizr/issues/issue/97/ var el = document.createElement('canvas'); return !!(el.getContext && el.getContext('2d')); }()), return_response_type: function(responseType) { try { if (Basic.inArray(responseType, ['', 'text', 'document']) !== -1) { return true; } else if (window.XMLHttpRequest) { var xhr = new XMLHttpRequest(); xhr.open('get', '/'); // otherwise Gecko throws an exception if ('responseType' in xhr) { xhr.responseType = responseType; // as of 23.0.1271.64, Chrome switched from throwing exception to merely logging it to the console (why? o why?) if (xhr.responseType !== responseType) { return false; } return true; } } } catch (ex) {} return false; }, // ideas for this heavily come from Modernizr (http://modernizr.com/) use_data_uri: (function() { var du = new Image(); du.onload = function() { caps.use_data_uri = (du.width === 1 && du.height === 1); }; setTimeout(function() { du.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP8AAAAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="; }, 1); return false; }()), use_data_uri_over32kb: function() { // IE8 return caps.use_data_uri && (Env.browser !== 'IE' || Env.version >= 9); }, use_data_uri_of: function(bytes) { return (caps.use_data_uri && bytes < 33000 || caps.use_data_uri_over32kb()); }, use_fileinput: function() { var el = document.createElement('input'); el.setAttribute('type', 'file'); return !el.disabled; } }; return function(cap) { var args = [].slice.call(arguments); args.shift(); // shift of cap return Basic.typeOf(caps[cap]) === 'function' ? caps[cap].apply(this, args) : !!caps[cap]; }; }()); var Env = { can: can, browser: UAParser.browser.name, version: parseFloat(UAParser.browser.major), os: UAParser.os.name, // everybody intuitively types it in a lowercase for some reason osVersion: UAParser.os.version, verComp: version_compare, swf_url: "../flash/Moxie.swf", xap_url: "../silverlight/Moxie.xap", global_event_dispatcher: "moxie.core.EventTarget.instance.dispatchEvent" }; // for backward compatibility // @deprecated Use `Env.os` instead Env.OS = Env.os; return Env; }); // Included from: src/javascript/core/utils/Dom.js /** * Dom.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Dom', ['moxie/core/utils/Env'], function(Env) { /** Get DOM Element by it's id. @method get @for Utils @param {String} id Identifier of the DOM Element @return {DOMElement} */ var get = function(id) { if (typeof id !== 'string') { return id; } return document.getElementById(id); }; /** Checks if specified DOM element has specified class. @method hasClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var hasClass = function(obj, name) { if (!obj.className) { return false; } var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)"); return regExp.test(obj.className); }; /** Adds specified className to specified DOM element. @method addClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var addClass = function(obj, name) { if (!hasClass(obj, name)) { obj.className = !obj.className ? name : obj.className.replace(/\s+$/, '') + ' ' + name; } }; /** Removes specified className from specified DOM element. @method removeClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var removeClass = function(obj, name) { if (obj.className) { var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)"); obj.className = obj.className.replace(regExp, function($0, $1, $2) { return $1 === ' ' && $2 === ' ' ? ' ' : ''; }); } }; /** Returns a given computed style of a DOM element. @method getStyle @static @param {Object} obj DOM element like object. @param {String} name Style you want to get from the DOM element */ var getStyle = function(obj, name) { if (obj.currentStyle) { return obj.currentStyle[name]; } else if (window.getComputedStyle) { return window.getComputedStyle(obj, null)[name]; } }; /** Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields. @method getPos @static @param {Element} node HTML element or element id to get x, y position from. @param {Element} root Optional root element to stop calculations at. @return {object} Absolute position of the specified element object with x, y fields. */ var getPos = function(node, root) { var x = 0, y = 0, parent, doc = document, nodeRect, rootRect; node = node; root = root || doc.body; // Returns the x, y cordinate for an element on IE 6 and IE 7 function getIEPos(node) { var bodyElm, rect, x = 0, y = 0; if (node) { rect = node.getBoundingClientRect(); bodyElm = doc.compatMode === "CSS1Compat" ? doc.documentElement : doc.body; x = rect.left + bodyElm.scrollLeft; y = rect.top + bodyElm.scrollTop; } return { x : x, y : y }; } // Use getBoundingClientRect on IE 6 and IE 7 but not on IE 8 in standards mode if (node && node.getBoundingClientRect && Env.browser === 'IE' && (!doc.documentMode || doc.documentMode < 8)) { nodeRect = getIEPos(node); rootRect = getIEPos(root); return { x : nodeRect.x - rootRect.x, y : nodeRect.y - rootRect.y }; } parent = node; while (parent && parent != root && parent.nodeType) { x += parent.offsetLeft || 0; y += parent.offsetTop || 0; parent = parent.offsetParent; } parent = node.parentNode; while (parent && parent != root && parent.nodeType) { x -= parent.scrollLeft || 0; y -= parent.scrollTop || 0; parent = parent.parentNode; } return { x : x, y : y }; }; /** Returns the size of the specified node in pixels. @method getSize @static @param {Node} node Node to get the size of. @return {Object} Object with a w and h property. */ var getSize = function(node) { return { w : node.offsetWidth || node.clientWidth, h : node.offsetHeight || node.clientHeight }; }; return { get: get, hasClass: hasClass, addClass: addClass, removeClass: removeClass, getStyle: getStyle, getPos: getPos, getSize: getSize }; }); // Included from: src/javascript/core/Exceptions.js /** * Exceptions.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/Exceptions', [ 'moxie/core/utils/Basic' ], function(Basic) { function _findKey(obj, value) { var key; for (key in obj) { if (obj[key] === value) { return key; } } return null; } return { RuntimeError: (function() { var namecodes = { NOT_INIT_ERR: 1, NOT_SUPPORTED_ERR: 9, JS_ERR: 4 }; function RuntimeError(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": RuntimeError " + this.code; } Basic.extend(RuntimeError, namecodes); RuntimeError.prototype = Error.prototype; return RuntimeError; }()), OperationNotAllowedException: (function() { function OperationNotAllowedException(code) { this.code = code; this.name = 'OperationNotAllowedException'; } Basic.extend(OperationNotAllowedException, { NOT_ALLOWED_ERR: 1 }); OperationNotAllowedException.prototype = Error.prototype; return OperationNotAllowedException; }()), ImageError: (function() { var namecodes = { WRONG_FORMAT: 1, MAX_RESOLUTION_ERR: 2 }; function ImageError(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": ImageError " + this.code; } Basic.extend(ImageError, namecodes); ImageError.prototype = Error.prototype; return ImageError; }()), FileException: (function() { var namecodes = { NOT_FOUND_ERR: 1, SECURITY_ERR: 2, ABORT_ERR: 3, NOT_READABLE_ERR: 4, ENCODING_ERR: 5, NO_MODIFICATION_ALLOWED_ERR: 6, INVALID_STATE_ERR: 7, SYNTAX_ERR: 8 }; function FileException(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": FileException " + this.code; } Basic.extend(FileException, namecodes); FileException.prototype = Error.prototype; return FileException; }()), DOMException: (function() { var namecodes = { INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, INVALID_CHARACTER_ERR: 5, NO_DATA_ALLOWED_ERR: 6, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INUSE_ATTRIBUTE_ERR: 10, INVALID_STATE_ERR: 11, SYNTAX_ERR: 12, INVALID_MODIFICATION_ERR: 13, NAMESPACE_ERR: 14, INVALID_ACCESS_ERR: 15, VALIDATION_ERR: 16, TYPE_MISMATCH_ERR: 17, SECURITY_ERR: 18, NETWORK_ERR: 19, ABORT_ERR: 20, URL_MISMATCH_ERR: 21, QUOTA_EXCEEDED_ERR: 22, TIMEOUT_ERR: 23, INVALID_NODE_TYPE_ERR: 24, DATA_CLONE_ERR: 25 }; function DOMException(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": DOMException " + this.code; } Basic.extend(DOMException, namecodes); DOMException.prototype = Error.prototype; return DOMException; }()), EventException: (function() { function EventException(code) { this.code = code; this.name = 'EventException'; } Basic.extend(EventException, { UNSPECIFIED_EVENT_TYPE_ERR: 0 }); EventException.prototype = Error.prototype; return EventException; }()) }; }); // Included from: src/javascript/core/EventTarget.js /** * EventTarget.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/EventTarget', [ 'moxie/core/Exceptions', 'moxie/core/utils/Basic' ], function(x, Basic) { /** Parent object for all event dispatching components and objects @class EventTarget @constructor EventTarget */ function EventTarget() { // hash of event listeners by object uid var eventpool = {}; Basic.extend(this, { /** Unique id of the event dispatcher, usually overriden by children @property uid @type String */ uid: null, /** Can be called from within a child in order to acquire uniqie id in automated manner @method init */ init: function() { if (!this.uid) { this.uid = Basic.guid('uid_'); } }, /** Register a handler to a specific event dispatched by the object @method addEventListener @param {String} type Type or basically a name of the event to subscribe to @param {Function} fn Callback function that will be called when event happens @param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first @param {Object} [scope=this] A scope to invoke event handler in */ addEventListener: function(type, fn, priority, scope) { var self = this, list; type = Basic.trim(type); if (/\s/.test(type)) { // multiple event types were passed for one handler Basic.each(type.split(/\s+/), function(type) { self.addEventListener(type, fn, priority, scope); }); return; } type = type.toLowerCase(); priority = parseInt(priority, 10) || 0; list = eventpool[this.uid] && eventpool[this.uid][type] || []; list.push({fn : fn, priority : priority, scope : scope || this}); if (!eventpool[this.uid]) { eventpool[this.uid] = {}; } eventpool[this.uid][type] = list; }, /** Check if any handlers were registered to the specified event @method hasEventListener @param {String} type Type or basically a name of the event to check @return {Mixed} Returns a handler if it was found and false, if - not */ hasEventListener: function(type) { return type ? !!(eventpool[this.uid] && eventpool[this.uid][type]) : !!eventpool[this.uid]; }, /** Unregister the handler from the event, or if former was not specified - unregister all handlers @method removeEventListener @param {String} type Type or basically a name of the event @param {Function} [fn] Handler to unregister */ removeEventListener: function(type, fn) { type = type.toLowerCase(); var list = eventpool[this.uid] && eventpool[this.uid][type], i; if (list) { if (fn) { for (i = list.length - 1; i >= 0; i--) { if (list[i].fn === fn) { list.splice(i, 1); break; } } } else { list = []; } // delete event list if it has become empty if (!list.length) { delete eventpool[this.uid][type]; // and object specific entry in a hash if it has no more listeners attached if (Basic.isEmptyObj(eventpool[this.uid])) { delete eventpool[this.uid]; } } } }, /** Remove all event handlers from the object @method removeAllEventListeners */ removeAllEventListeners: function() { if (eventpool[this.uid]) { delete eventpool[this.uid]; } }, /** Dispatch the event @method dispatchEvent @param {String/Object} Type of event or event object to dispatch @param {Mixed} [...] Variable number of arguments to be passed to a handlers @return {Boolean} true by default and false if any handler returned false */ dispatchEvent: function(type) { var uid, list, args, tmpEvt, evt = {}, result = true, undef; if (Basic.typeOf(type) !== 'string') { // we can't use original object directly (because of Silverlight) tmpEvt = type; if (Basic.typeOf(tmpEvt.type) === 'string') { type = tmpEvt.type; if (tmpEvt.total !== undef && tmpEvt.loaded !== undef) { // progress event evt.total = tmpEvt.total; evt.loaded = tmpEvt.loaded; } evt.async = tmpEvt.async || false; } else { throw new x.EventException(x.EventException.UNSPECIFIED_EVENT_TYPE_ERR); } } // check if event is meant to be dispatched on an object having specific uid if (type.indexOf('::') !== -1) { (function(arr) { uid = arr[0]; type = arr[1]; }(type.split('::'))); } else { uid = this.uid; } type = type.toLowerCase(); list = eventpool[uid] && eventpool[uid][type]; if (list) { // sort event list by prority list.sort(function(a, b) { return b.priority - a.priority; }); args = [].slice.call(arguments); // first argument will be pseudo-event object args.shift(); evt.type = type; args.unshift(evt); // Dispatch event to all listeners var queue = []; Basic.each(list, function(handler) { // explicitly set the target, otherwise events fired from shims do not get it args[0].target = handler.scope; // if event is marked as async, detach the handler if (evt.async) { queue.push(function(cb) { setTimeout(function() { cb(handler.fn.apply(handler.scope, args) === false); }, 1); }); } else { queue.push(function(cb) { cb(handler.fn.apply(handler.scope, args) === false); // if handler returns false stop propagation }); } }); if (queue.length) { Basic.inSeries(queue, function(err) { result = !err; }); } } return result; }, /** Alias for addEventListener @method bind @protected */ bind: function() { this.addEventListener.apply(this, arguments); }, /** Alias for removeEventListener @method unbind @protected */ unbind: function() { this.removeEventListener.apply(this, arguments); }, /** Alias for removeAllEventListeners @method unbindAll @protected */ unbindAll: function() { this.removeAllEventListeners.apply(this, arguments); }, /** Alias for dispatchEvent @method trigger @protected */ trigger: function() { return this.dispatchEvent.apply(this, arguments); }, /** Converts properties of on[event] type to corresponding event handlers, is used to avoid extra hassle around the process of calling them back @method convertEventPropsToHandlers @private */ convertEventPropsToHandlers: function(handlers) { var h; if (Basic.typeOf(handlers) !== 'array') { handlers = [handlers]; } for (var i = 0; i < handlers.length; i++) { h = 'on' + handlers[i]; if (Basic.typeOf(this[h]) === 'function') { this.addEventListener(handlers[i], this[h]); } else if (Basic.typeOf(this[h]) === 'undefined') { this[h] = null; // object must have defined event properties, even if it doesn't make use of them } } } }); } EventTarget.instance = new EventTarget(); return EventTarget; }); // Included from: src/javascript/core/utils/Encode.js /** * Encode.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Encode', [], function() { /** Encode string with UTF-8 @method utf8_encode @for Utils @static @param {String} str String to encode @return {String} UTF-8 encoded string */ var utf8_encode = function(str) { return unescape(encodeURIComponent(str)); }; /** Decode UTF-8 encoded string @method utf8_decode @static @param {String} str String to decode @return {String} Decoded string */ var utf8_decode = function(str_data) { return decodeURIComponent(escape(str_data)); }; /** Decode Base64 encoded string (uses browser's default method if available), from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_decode.js @method atob @static @param {String} data String to decode @return {String} Decoded string */ var atob = function(data, utf8) { if (typeof(window.atob) === 'function') { return utf8 ? utf8_decode(window.atob(data)) : window.atob(data); } // http://kevin.vanzonneveld.net // + original by: Tyler Akins (http://rumkin.com) // + improved by: Thunder.m // + input by: Aman Gupta // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + bugfixed by: Pellentesque Malesuada // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA=='); // * returns 1: 'Kevin van Zonneveld' // mozilla has this native // - but breaks in 2.0.0.12! //if (typeof this.window.atob == 'function') { // return atob(data); //} var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = []; if (!data) { return data; } data += ''; do { // unpack four hexets into three octets using index points in b64 h1 = b64.indexOf(data.charAt(i++)); h2 = b64.indexOf(data.charAt(i++)); h3 = b64.indexOf(data.charAt(i++)); h4 = b64.indexOf(data.charAt(i++)); bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; o1 = bits >> 16 & 0xff; o2 = bits >> 8 & 0xff; o3 = bits & 0xff; if (h3 == 64) { tmp_arr[ac++] = String.fromCharCode(o1); } else if (h4 == 64) { tmp_arr[ac++] = String.fromCharCode(o1, o2); } else { tmp_arr[ac++] = String.fromCharCode(o1, o2, o3); } } while (i < data.length); dec = tmp_arr.join(''); return utf8 ? utf8_decode(dec) : dec; }; /** Base64 encode string (uses browser's default method if available), from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_encode.js @method btoa @static @param {String} data String to encode @return {String} Base64 encoded string */ var btoa = function(data, utf8) { if (utf8) { utf8_encode(data); } if (typeof(window.btoa) === 'function') { return window.btoa(data); } // http://kevin.vanzonneveld.net // + original by: Tyler Akins (http://rumkin.com) // + improved by: Bayron Guevara // + improved by: Thunder.m // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Pellentesque Malesuada // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Rafał Kukawski (http://kukawski.pl) // * example 1: base64_encode('Kevin van Zonneveld'); // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA==' // mozilla has this native // - but breaks in 2.0.0.12! var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc = "", tmp_arr = []; if (!data) { return data; } do { // pack three octets into four hexets o1 = data.charCodeAt(i++); o2 = data.charCodeAt(i++); o3 = data.charCodeAt(i++); bits = o1 << 16 | o2 << 8 | o3; h1 = bits >> 18 & 0x3f; h2 = bits >> 12 & 0x3f; h3 = bits >> 6 & 0x3f; h4 = bits & 0x3f; // use hexets to index into b64, and append result to encoded string tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); } while (i < data.length); enc = tmp_arr.join(''); var r = data.length % 3; return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3); }; return { utf8_encode: utf8_encode, utf8_decode: utf8_decode, atob: atob, btoa: btoa }; }); // Included from: src/javascript/runtime/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/Runtime', [ "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/EventTarget" ], function(Basic, Dom, EventTarget) { var runtimeConstructors = {}, runtimes = {}; /** Common set of methods and properties for every runtime instance @class Runtime @param {Object} options @param {String} type Sanitized name of the runtime @param {Object} [caps] Set of capabilities that differentiate specified runtime @param {Object} [modeCaps] Set of capabilities that do require specific operational mode @param {String} [preferredMode='browser'] Preferred operational mode to choose if no required capabilities were requested */ function Runtime(options, type, caps, modeCaps, preferredMode) { /** Dispatched when runtime is initialized and ready. Results in RuntimeInit on a connected component. @event Init */ /** Dispatched when runtime fails to initialize. Results in RuntimeError on a connected component. @event Error */ var self = this , _shim , _uid = Basic.guid(type + '_') , defaultMode = preferredMode || 'browser' ; options = options || {}; // register runtime in private hash runtimes[_uid] = this; /** Default set of capabilities, which can be redifined later by specific runtime @private @property caps @type Object */ caps = Basic.extend({ // Runtime can: // provide access to raw binary data of the file access_binary: false, // provide access to raw binary data of the image (image extension is optional) access_image_binary: false, // display binary data as thumbs for example display_media: false, // make cross-domain requests do_cors: false, // accept files dragged and dropped from the desktop drag_and_drop: false, // filter files in selection dialog by their extensions filter_by_extension: true, // resize image (and manipulate it raw data of any file in general) resize_image: false, // periodically report how many bytes of total in the file were uploaded (loaded) report_upload_progress: false, // provide access to the headers of http response return_response_headers: false, // support response of specific type, which should be passed as an argument // e.g. runtime.can('return_response_type', 'blob') return_response_type: false, // return http status code of the response return_status_code: true, // send custom http header with the request send_custom_headers: false, // pick up the files from a dialog select_file: false, // select whole folder in file browse dialog select_folder: false, // select multiple files at once in file browse dialog select_multiple: true, // send raw binary data, that is generated after image resizing or manipulation of other kind send_binary_string: false, // send cookies with http request and therefore retain session send_browser_cookies: true, // send data formatted as multipart/form-data send_multipart: true, // slice the file or blob to smaller parts slice_blob: false, // upload file without preloading it to memory, stream it out directly from disk stream_upload: false, // programmatically trigger file browse dialog summon_file_dialog: false, // upload file of specific size, size should be passed as argument // e.g. runtime.can('upload_filesize', '500mb') upload_filesize: true, // initiate http request with specific http method, method should be passed as argument // e.g. runtime.can('use_http_method', 'put') use_http_method: true }, caps); // default to the mode that is compatible with preferred caps if (options.preferred_caps) { defaultMode = Runtime.getMode(modeCaps, options.preferred_caps, defaultMode); } // small extension factory here (is meant to be extended with actual extensions constructors) _shim = (function() { var objpool = {}; return { exec: function(uid, comp, fn, args) { if (_shim[comp]) { if (!objpool[uid]) { objpool[uid] = { context: this, instance: new _shim[comp]() }; } if (objpool[uid].instance[fn]) { return objpool[uid].instance[fn].apply(this, args); } } }, removeInstance: function(uid) { delete objpool[uid]; }, removeAllInstances: function() { var self = this; Basic.each(objpool, function(obj, uid) { if (Basic.typeOf(obj.instance.destroy) === 'function') { obj.instance.destroy.call(obj.context); } self.removeInstance(uid); }); } }; }()); // public methods Basic.extend(this, { /** Specifies whether runtime instance was initialized or not @property initialized @type {Boolean} @default false */ initialized: false, // shims require this flag to stop initialization retries /** Unique ID of the runtime @property uid @type {String} */ uid: _uid, /** Runtime type (e.g. flash, html5, etc) @property type @type {String} */ type: type, /** Runtime (not native one) may operate in browser or client mode. @property mode @private @type {String|Boolean} current mode or false, if none possible */ mode: Runtime.getMode(modeCaps, (options.required_caps), defaultMode), /** id of the DOM container for the runtime (if available) @property shimid @type {String} */ shimid: _uid + '_container', /** Number of connected clients. If equal to zero, runtime can be destroyed @property clients @type {Number} */ clients: 0, /** Runtime initialization options @property options @type {Object} */ options: options, /** Checks if the runtime has specific capability @method can @param {String} cap Name of capability to check @param {Mixed} [value] If passed, capability should somehow correlate to the value @param {Object} [refCaps] Set of capabilities to check the specified cap against (defaults to internal set) @return {Boolean} true if runtime has such capability and false, if - not */ can: function(cap, value) { var refCaps = arguments[2] || caps; // if cap var is a comma-separated list of caps, convert it to object (key/value) if (Basic.typeOf(cap) === 'string' && Basic.typeOf(value) === 'undefined') { cap = Runtime.parseCaps(cap); } if (Basic.typeOf(cap) === 'object') { for (var key in cap) { if (!this.can(key, cap[key], refCaps)) { return false; } } return true; } // check the individual cap if (Basic.typeOf(refCaps[cap]) === 'function') { return refCaps[cap].call(this, value); } else { return (value === refCaps[cap]); } }, /** Returns container for the runtime as DOM element @method getShimContainer @return {DOMElement} */ getShimContainer: function() { var container, shimContainer = Dom.get(this.shimid); // if no container for shim, create one if (!shimContainer) { container = this.options.container ? Dom.get(this.options.container) : document.body; // create shim container and insert it at an absolute position into the outer container shimContainer = document.createElement('div'); shimContainer.id = this.shimid; shimContainer.className = 'moxie-shim moxie-shim-' + this.type; Basic.extend(shimContainer.style, { position: 'absolute', top: '0px', left: '0px', width: '1px', height: '1px', overflow: 'hidden' }); container.appendChild(shimContainer); container = null; } return shimContainer; }, /** Returns runtime as DOM element (if appropriate) @method getShim @return {DOMElement} */ getShim: function() { return _shim; }, /** Invokes a method within the runtime itself (might differ across the runtimes) @method shimExec @param {Mixed} [] @protected @return {Mixed} Depends on the action and component */ shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return self.getShim().exec.call(this, this.uid, component, action, args); }, /** Operaional interface that is used by components to invoke specific actions on the runtime (is invoked in the scope of component) @method exec @param {Mixed} []* @protected @return {Mixed} Depends on the action and component */ exec: function(component, action) { // this is called in the context of component, not runtime var args = [].slice.call(arguments, 2); if (self[component] && self[component][action]) { return self[component][action].apply(this, args); } return self.shimExec.apply(this, arguments); }, /** Destroys the runtime (removes all events and deletes DOM structures) @method destroy */ destroy: function() { if (!self) { return; // obviously already destroyed } var shimContainer = Dom.get(this.shimid); if (shimContainer) { shimContainer.parentNode.removeChild(shimContainer); } if (_shim) { _shim.removeAllInstances(); } this.unbindAll(); delete runtimes[this.uid]; this.uid = null; // mark this runtime as destroyed _uid = self = _shim = shimContainer = null; } }); // once we got the mode, test against all caps if (this.mode && options.required_caps && !this.can(options.required_caps)) { this.mode = false; } } /** Default order to try different runtime types @property order @type String @static */ Runtime.order = 'html5,flash,silverlight,html4'; /** Retrieves runtime from private hash by it's uid @method getRuntime @private @static @param {String} uid Unique identifier of the runtime @return {Runtime|Boolean} Returns runtime, if it exists and false, if - not */ Runtime.getRuntime = function(uid) { return runtimes[uid] ? runtimes[uid] : false; }; /** Register constructor for the Runtime of new (or perhaps modified) type @method addConstructor @static @param {String} type Runtime type (e.g. flash, html5, etc) @param {Function} construct Constructor for the Runtime type */ Runtime.addConstructor = function(type, constructor) { constructor.prototype = EventTarget.instance; runtimeConstructors[type] = constructor; }; /** Get the constructor for the specified type. method getConstructor @static @param {String} type Runtime type (e.g. flash, html5, etc) @return {Function} Constructor for the Runtime type */ Runtime.getConstructor = function(type) { return runtimeConstructors[type] || null; }; /** Get info about the runtime (uid, type, capabilities) @method getInfo @static @param {String} uid Unique identifier of the runtime @return {Mixed} Info object or null if runtime doesn't exist */ Runtime.getInfo = function(uid) { var runtime = Runtime.getRuntime(uid); if (runtime) { return { uid: runtime.uid, type: runtime.type, mode: runtime.mode, can: function() { return runtime.can.apply(runtime, arguments); } }; } return null; }; /** Convert caps represented by a comma-separated string to the object representation. @method parseCaps @static @param {String} capStr Comma-separated list of capabilities @return {Object} */ Runtime.parseCaps = function(capStr) { var capObj = {}; if (Basic.typeOf(capStr) !== 'string') { return capStr || {}; } Basic.each(capStr.split(','), function(key) { capObj[key] = true; // we assume it to be - true }); return capObj; }; /** Test the specified runtime for specific capabilities. @method can @static @param {String} type Runtime type (e.g. flash, html5, etc) @param {String|Object} caps Set of capabilities to check @return {Boolean} Result of the test */ Runtime.can = function(type, caps) { var runtime , constructor = Runtime.getConstructor(type) , mode ; if (constructor) { runtime = new constructor({ required_caps: caps }); mode = runtime.mode; runtime.destroy(); return !!mode; } return false; }; /** Figure out a runtime that supports specified capabilities. @method thatCan @static @param {String|Object} caps Set of capabilities to check @param {String} [runtimeOrder] Comma-separated list of runtimes to check against @return {String} Usable runtime identifier or null */ Runtime.thatCan = function(caps, runtimeOrder) { var types = (runtimeOrder || Runtime.order).split(/\s*,\s*/); for (var i in types) { if (Runtime.can(types[i], caps)) { return types[i]; } } return null; }; /** Figure out an operational mode for the specified set of capabilities. @method getMode @static @param {Object} modeCaps Set of capabilities that depend on particular runtime mode @param {Object} [requiredCaps] Supplied set of capabilities to find operational mode for @param {String|Boolean} [defaultMode='browser'] Default mode to use @return {String|Boolean} Compatible operational mode */ Runtime.getMode = function(modeCaps, requiredCaps, defaultMode) { var mode = null; if (Basic.typeOf(defaultMode) === 'undefined') { // only if not specified defaultMode = 'browser'; } if (requiredCaps && !Basic.isEmptyObj(modeCaps)) { // loop over required caps and check if they do require the same mode Basic.each(requiredCaps, function(value, cap) { if (modeCaps.hasOwnProperty(cap)) { var capMode = modeCaps[cap](value); // make sure we always have an array if (typeof(capMode) === 'string') { capMode = [capMode]; } if (!mode) { mode = capMode; } else if (!(mode = Basic.arrayIntersect(mode, capMode))) { // if cap requires conflicting mode - runtime cannot fulfill required caps return (mode = false); } } }); if (mode) { return Basic.inArray(defaultMode, mode) !== -1 ? defaultMode : mode[0]; } else if (mode === false) { return false; } } return defaultMode; }; /** Capability check that always returns true @private @static @return {True} */ Runtime.capTrue = function() { return true; }; /** Capability check that always returns false @private @static @return {False} */ Runtime.capFalse = function() { return false; }; /** Evaluate the expression to boolean value and create a function that always returns it. @private @static @param {Mixed} expr Expression to evaluate @return {Function} Function returning the result of evaluation */ Runtime.capTest = function(expr) { return function() { return !!expr; }; }; return Runtime; }); // Included from: src/javascript/runtime/RuntimeClient.js /** * RuntimeClient.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/RuntimeClient', [ 'moxie/core/Exceptions', 'moxie/core/utils/Basic', 'moxie/runtime/Runtime' ], function(x, Basic, Runtime) { /** Set of methods and properties, required by a component to acquire ability to connect to a runtime @class RuntimeClient */ return function RuntimeClient() { var runtime; Basic.extend(this, { /** Connects to the runtime specified by the options. Will either connect to existing runtime or create a new one. Increments number of clients connected to the specified runtime. @method connectRuntime @param {Mixed} options Can be a runtme uid or a set of key-value pairs defining requirements and pre-requisites */ connectRuntime: function(options) { var comp = this, ruid; function initialize(items) { var type, constructor; // if we ran out of runtimes if (!items.length) { comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); runtime = null; return; } type = items.shift(); constructor = Runtime.getConstructor(type); if (!constructor) { initialize(items); return; } // try initializing the runtime runtime = new constructor(options); runtime.bind('Init', function() { // mark runtime as initialized runtime.initialized = true; // jailbreak ... setTimeout(function() { runtime.clients++; // this will be triggered on component comp.trigger('RuntimeInit', runtime); }, 1); }); runtime.bind('Error', function() { runtime.destroy(); // runtime cannot destroy itself from inside at a right moment, thus we do it here initialize(items); }); /*runtime.bind('Exception', function() { });*/ // check if runtime managed to pick-up operational mode if (!runtime.mode) { runtime.trigger('Error'); return; } runtime.init(); } // check if a particular runtime was requested if (Basic.typeOf(options) === 'string') { ruid = options; } else if (Basic.typeOf(options.ruid) === 'string') { ruid = options.ruid; } if (ruid) { runtime = Runtime.getRuntime(ruid); if (runtime) { runtime.clients++; return runtime; } else { // there should be a runtime and there's none - weird case throw new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR); } } // initialize a fresh one, that fits runtime list and required features best initialize((options.runtime_order || Runtime.order).split(/\s*,\s*/)); }, /** Returns the runtime to which the client is currently connected. @method getRuntime @return {Runtime} Runtime or null if client is not connected */ getRuntime: function() { if (runtime && runtime.uid) { return runtime; } runtime = null; // make sure we do not leave zombies rambling around return null; }, /** Disconnects from the runtime. Decrements number of clients connected to the specified runtime. @method disconnectRuntime */ disconnectRuntime: function() { if (runtime && --runtime.clients <= 0) { runtime.destroy(); runtime = null; } } }); }; }); // Included from: src/javascript/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/Blob', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Encode', 'moxie/runtime/RuntimeClient' ], function(Basic, Encode, RuntimeClient) { var blobpool = {}; /** @class Blob @constructor @param {String} ruid Unique id of the runtime, to which this blob belongs to @param {Object} blob Object "Native" blob object, as it is represented in the runtime */ function Blob(ruid, blob) { function _sliceDetached(start, end, type) { var blob, data = blobpool[this.uid]; if (Basic.typeOf(data) !== 'string' || !data.length) { return null; // or throw exception } blob = new Blob(null, { type: type, size: end - start }); blob.detach(data.substr(start, blob.size)); return blob; } RuntimeClient.call(this); if (ruid) { this.connectRuntime(ruid); } if (!blob) { blob = {}; } else if (Basic.typeOf(blob) === 'string') { // dataUrl or binary string blob = { data: blob }; } Basic.extend(this, { /** Unique id of the component @property uid @type {String} */ uid: blob.uid || Basic.guid('uid_'), /** Unique id of the connected runtime, if falsy, then runtime will have to be initialized before this Blob can be used, modified or sent @property ruid @type {String} */ ruid: ruid, /** Size of blob @property size @type {Number} @default 0 */ size: blob.size || 0, /** Mime type of blob @property type @type {String} @default '' */ type: blob.type || '', /** @method slice @param {Number} [start=0] */ slice: function(start, end, type) { if (this.isDetached()) { return _sliceDetached.apply(this, arguments); } return this.getRuntime().exec.call(this, 'Blob', 'slice', this.getSource(), start, end, type); }, /** Returns "native" blob object (as it is represented in connected runtime) or null if not found @method getSource @return {Blob} Returns "native" blob object or null if not found */ getSource: function() { if (!blobpool[this.uid]) { return null; } return blobpool[this.uid]; }, /** Detaches blob from any runtime that it depends on and initialize with standalone value @method detach @protected @param {DOMString} [data=''] Standalone value */ detach: function(data) { if (this.ruid) { this.getRuntime().exec.call(this, 'Blob', 'destroy'); this.disconnectRuntime(); this.ruid = null; } data = data || ''; // if dataUrl, convert to binary string var matches = data.match(/^data:([^;]*);base64,/); if (matches) { this.type = matches[1]; data = Encode.atob(data.substring(data.indexOf('base64,') + 7)); } this.size = data.length; blobpool[this.uid] = data; }, /** Checks if blob is standalone (detached of any runtime) @method isDetached @protected @return {Boolean} */ isDetached: function() { return !this.ruid && Basic.typeOf(blobpool[this.uid]) === 'string'; }, /** Destroy Blob and free any resources it was using @method destroy */ destroy: function() { this.detach(); delete blobpool[this.uid]; } }); if (blob.data) { this.detach(blob.data); // auto-detach if payload has been passed } else { blobpool[this.uid] = blob; } } return Blob; }); // Included from: src/javascript/file/File.js /** * File.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/File', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Mime', 'moxie/file/Blob' ], function(Basic, Mime, Blob) { /** @class File @extends Blob @constructor @param {String} ruid Unique id of the runtime, to which this blob belongs to @param {Object} file Object "Native" file object, as it is represented in the runtime */ function File(ruid, file) { var name, type; if (!file) { // avoid extra errors in case we overlooked something file = {}; } // figure out the type if (file.type && file.type !== '') { type = file.type; } else { type = Mime.getFileMime(file.name); } // sanitize file name or generate new one if (file.name) { name = file.name.replace(/\\/g, '/'); name = name.substr(name.lastIndexOf('/') + 1); } else { var prefix = type.split('/')[0]; name = Basic.guid((prefix !== '' ? prefix : 'file') + '_'); if (Mime.extensions[type]) { name += '.' + Mime.extensions[type][0]; // append proper extension if possible } } Blob.apply(this, arguments); Basic.extend(this, { /** File mime type @property type @type {String} @default '' */ type: type || '', /** File name @property name @type {String} @default UID */ name: name || Basic.guid('file_'), /** Relative path to the file inside a directory @property relativePath @type {String} @default '' */ relativePath: '', /** Date of last modification @property lastModifiedDate @type {String} @default now */ lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString() // Thu Aug 23 2012 19:40:00 GMT+0400 (GET) }); } File.prototype = Blob.prototype; return File; }); // Included from: src/javascript/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileInput', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Mime', 'moxie/core/utils/Dom', 'moxie/core/Exceptions', 'moxie/core/EventTarget', 'moxie/core/I18n', 'moxie/file/File', 'moxie/runtime/Runtime', 'moxie/runtime/RuntimeClient' ], function(Basic, Mime, Dom, x, EventTarget, I18n, File, Runtime, RuntimeClient) { /** Provides a convenient way to create cross-browser file-picker. Generates file selection dialog on click, converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory with _FileReader_ or uploaded to a server through _XMLHttpRequest_. @class FileInput @constructor @extends EventTarget @uses RuntimeClient @param {Object|String|DOMElement} options If options is string or node, argument is considered as _browse\_button_. @param {String|DOMElement} options.browse_button DOM Element to turn into file picker. @param {Array} [options.accept] Array of mime types to accept. By default accepts all. @param {String} [options.file='file'] Name of the file field (not the filename). @param {Boolean} [options.multiple=false] Enable selection of multiple files. @param {Boolean} [options.directory=false] Turn file input into the folder input (cannot be both at the same time). @param {String|DOMElement} [options.container] DOM Element to use as a container for file-picker. Defaults to parentNode for _browse\_button_. @param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support. @example <div id="container"> <a id="file-picker" href="javascript:;">Browse...</a> </div> <script> var fileInput = new mOxie.FileInput({ browse_button: 'file-picker', // or document.getElementById('file-picker') container: 'container', accept: [ {title: "Image files", extensions: "jpg,gif,png"} // accept only images ], multiple: true // allow multiple file selection }); fileInput.onchange = function(e) { // do something to files array console.info(e.target.files); // or this.files or fileInput.files }; fileInput.init(); // initialize </script> */ var dispatches = [ /** Dispatched when runtime is connected and file-picker is ready to be used. @event ready @param {Object} event */ 'ready', /** Dispatched right after [ready](#event_ready) event, and whenever [refresh()](#method_refresh) is invoked. Check [corresponding documentation entry](#method_refresh) for more info. @event refresh @param {Object} event */ /** Dispatched when selection of files in the dialog is complete. @event change @param {Object} event */ 'change', 'cancel', // TODO: might be useful /** Dispatched when mouse cursor enters file-picker area. Can be used to style element accordingly. @event mouseenter @param {Object} event */ 'mouseenter', /** Dispatched when mouse cursor leaves file-picker area. Can be used to style element accordingly. @event mouseleave @param {Object} event */ 'mouseleave', /** Dispatched when functional mouse button is pressed on top of file-picker area. @event mousedown @param {Object} event */ 'mousedown', /** Dispatched when functional mouse button is released on top of file-picker area. @event mouseup @param {Object} event */ 'mouseup' ]; function FileInput(options) { var self = this, container, browseButton, defaults; // if flat argument passed it should be browse_button id if (Basic.inArray(Basic.typeOf(options), ['string', 'node']) !== -1) { options = { browse_button : options }; } // this will help us to find proper default container browseButton = Dom.get(options.browse_button); if (!browseButton) { // browse button is required throw new x.DOMException(x.DOMException.NOT_FOUND_ERR); } // figure out the options defaults = { accept: [{ title: I18n.translate('All Files'), extensions: '*' }], name: 'file', multiple: false, required_caps: false, container: browseButton.parentNode || document.body }; options = Basic.extend({}, defaults, options); // convert to object representation if (typeof(options.required_caps) === 'string') { options.required_caps = Runtime.parseCaps(options.required_caps); } // normalize accept option (could be list of mime types or array of title/extensions pairs) if (typeof(options.accept) === 'string') { options.accept = Mime.mimes2extList(options.accept); } container = Dom.get(options.container); // make sure we have container if (!container) { container = document.body; } // make container relative, if it's not if (Dom.getStyle(container, 'position') === 'static') { container.style.position = 'relative'; } container = browseButton = null; // IE RuntimeClient.call(self); Basic.extend(self, { /** Unique id of the component @property uid @protected @readOnly @type {String} @default UID */ uid: Basic.guid('uid_'), /** Unique id of the connected runtime, if any. @property ruid @protected @type {String} */ ruid: null, /** Unique id of the runtime container. Useful to get hold of it for various manipulations. @property shimid @protected @type {String} */ shimid: null, /** Array of selected mOxie.File objects @property files @type {Array} @default null */ files: null, /** Initializes the file-picker, connects it to runtime and dispatches event ready when done. @method init */ init: function() { self.convertEventPropsToHandlers(dispatches); self.bind('RuntimeInit', function(e, runtime) { self.ruid = runtime.uid; self.shimid = runtime.shimid; self.bind("Ready", function() { self.trigger("Refresh"); }, 999); self.bind("Change", function() { var files = runtime.exec.call(self, 'FileInput', 'getFiles'); self.files = []; Basic.each(files, function(file) { // ignore empty files (IE10 for example hangs if you try to send them via XHR) if (file.size === 0) { return true; } self.files.push(new File(self.ruid, file)); }); }, 999); // re-position and resize shim container self.bind('Refresh', function() { var pos, size, browseButton, shimContainer; browseButton = Dom.get(options.browse_button); shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist if (browseButton) { pos = Dom.getPos(browseButton, Dom.get(options.container)); size = Dom.getSize(browseButton); if (shimContainer) { Basic.extend(shimContainer.style, { top : pos.y + 'px', left : pos.x + 'px', width : size.w + 'px', height : size.h + 'px' }); } } shimContainer = browseButton = null; }); runtime.exec.call(self, 'FileInput', 'init', options); }); // runtime needs: options.required_features, options.runtime_order and options.container self.connectRuntime(Basic.extend({}, options, { required_caps: { select_file: true } })); }, /** Disables file-picker element, so that it doesn't react to mouse clicks. @method disable @param {Boolean} [state=true] Disable component if - true, enable if - false */ disable: function(state) { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'disable', Basic.typeOf(state) === 'undefined' ? true : state); } }, /** Reposition and resize dialog trigger to match the position and size of browse_button element. @method refresh */ refresh: function() { self.trigger("Refresh"); }, /** Destroy component. @method destroy */ destroy: function() { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'destroy'); this.disconnectRuntime(); } if (Basic.typeOf(this.files) === 'array') { // no sense in leaving associated files behind Basic.each(this.files, function(file) { file.destroy(); }); } this.files = null; } }); } FileInput.prototype = EventTarget.instance; return FileInput; }); // Included from: src/javascript/runtime/RuntimeTarget.js /** * RuntimeTarget.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/RuntimeTarget', [ 'moxie/core/utils/Basic', 'moxie/runtime/RuntimeClient', "moxie/core/EventTarget" ], function(Basic, RuntimeClient, EventTarget) { /** Instance of this class can be used as a target for the events dispatched by shims, when allowing them onto components is for either reason inappropriate @class RuntimeTarget @constructor @protected @extends EventTarget */ function RuntimeTarget() { this.uid = Basic.guid('uid_'); RuntimeClient.call(this); this.destroy = function() { this.disconnectRuntime(); this.unbindAll(); }; } RuntimeTarget.prototype = EventTarget.instance; return RuntimeTarget; }); // Included from: src/javascript/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileReader', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Encode', 'moxie/core/Exceptions', 'moxie/core/EventTarget', 'moxie/file/Blob', 'moxie/file/File', 'moxie/runtime/RuntimeTarget' ], function(Basic, Encode, x, EventTarget, Blob, File, RuntimeTarget) { /** Utility for preloading o.Blob/o.File objects in memory. By design closely follows [W3C FileReader](http://www.w3.org/TR/FileAPI/#dfn-filereader) interface. Where possible uses native FileReader, where - not falls back to shims. @class FileReader @constructor FileReader @extends EventTarget @uses RuntimeClient */ var dispatches = [ /** Dispatched when the read starts. @event loadstart @param {Object} event */ 'loadstart', /** Dispatched while reading (and decoding) blob, and reporting partial Blob data (progess.loaded/progress.total). @event progress @param {Object} event */ 'progress', /** Dispatched when the read has successfully completed. @event load @param {Object} event */ 'load', /** Dispatched when the read has been aborted. For instance, by invoking the abort() method. @event abort @param {Object} event */ 'abort', /** Dispatched when the read has failed. @event error @param {Object} event */ 'error', /** Dispatched when the request has completed (either in success or failure). @event loadend @param {Object} event */ 'loadend' ]; function FileReader() { var self = this, _fr; Basic.extend(this, { /** UID of the component instance. @property uid @type {String} */ uid: Basic.guid('uid_'), /** Contains current state of FileReader object. Can take values of FileReader.EMPTY, FileReader.LOADING and FileReader.DONE. @property readyState @type {Number} @default FileReader.EMPTY */ readyState: FileReader.EMPTY, /** Result of the successful read operation. @property result @type {String} */ result: null, /** Stores the error of failed asynchronous read operation. @property error @type {DOMError} */ error: null, /** Initiates reading of File/Blob object contents to binary string. @method readAsBinaryString @param {Blob|File} blob Object to preload */ readAsBinaryString: function(blob) { _read.call(this, 'readAsBinaryString', blob); }, /** Initiates reading of File/Blob object contents to dataURL string. @method readAsDataURL @param {Blob|File} blob Object to preload */ readAsDataURL: function(blob) { _read.call(this, 'readAsDataURL', blob); }, /** Initiates reading of File/Blob object contents to string. @method readAsText @param {Blob|File} blob Object to preload */ readAsText: function(blob) { _read.call(this, 'readAsText', blob); }, /** Aborts preloading process. @method abort */ abort: function() { this.result = null; if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) { return; } else if (this.readyState === FileReader.LOADING) { this.readyState = FileReader.DONE; } if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'abort'); } this.trigger('abort'); this.trigger('loadend'); }, /** Destroy component and release resources. @method destroy */ destroy: function() { this.abort(); if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'destroy'); _fr.disconnectRuntime(); } self = _fr = null; } }); function _read(op, blob) { _fr = new RuntimeTarget(); function error(err) { self.readyState = FileReader.DONE; self.error = err; self.trigger('error'); loadEnd(); } function loadEnd() { _fr.destroy(); _fr = null; self.trigger('loadend'); } function exec(runtime) { _fr.bind('Error', function(e, err) { error(err); }); _fr.bind('Progress', function(e) { self.result = runtime.exec.call(_fr, 'FileReader', 'getResult'); self.trigger(e); }); _fr.bind('Load', function(e) { self.readyState = FileReader.DONE; self.result = runtime.exec.call(_fr, 'FileReader', 'getResult'); self.trigger(e); loadEnd(); }); runtime.exec.call(_fr, 'FileReader', 'read', op, blob); } this.convertEventPropsToHandlers(dispatches); if (this.readyState === FileReader.LOADING) { return error(new x.DOMException(x.DOMException.INVALID_STATE_ERR)); } this.readyState = FileReader.LOADING; this.trigger('loadstart'); // if source is o.Blob/o.File if (blob instanceof Blob) { if (blob.isDetached()) { var src = blob.getSource(); switch (op) { case 'readAsText': case 'readAsBinaryString': this.result = src; break; case 'readAsDataURL': this.result = 'data:' + blob.type + ';base64,' + Encode.btoa(src); break; } this.readyState = FileReader.DONE; this.trigger('load'); loadEnd(); } else { exec(_fr.connectRuntime(blob.ruid)); } } else { error(new x.DOMException(x.DOMException.NOT_FOUND_ERR)); } } } /** Initial FileReader state @property EMPTY @type {Number} @final @static @default 0 */ FileReader.EMPTY = 0; /** FileReader switches to this state when it is preloading the source @property LOADING @type {Number} @final @static @default 1 */ FileReader.LOADING = 1; /** Preloading is complete, this is a final state @property DONE @type {Number} @final @static @default 2 */ FileReader.DONE = 2; FileReader.prototype = EventTarget.instance; return FileReader; }); // Included from: src/javascript/core/utils/Url.js /** * Url.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Url', [], function() { /** Parse url into separate components and fill in absent parts with parts from current url, based on https://raw.github.com/kvz/phpjs/master/functions/url/parse_url.js @method parseUrl @for Utils @static @param {String} url Url to parse (defaults to empty string if undefined) @return {Object} Hash containing extracted uri components */ var parseUrl = function(url, currentUrl) { var key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'fragment'] , i = key.length , ports = { http: 80, https: 443 } , uri = {} , regex = /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/ , m = regex.exec(url || '') ; while (i--) { if (m[i]) { uri[key[i]] = m[i]; } } // when url is relative, we set the origin and the path ourselves if (!uri.scheme) { // come up with defaults if (!currentUrl || typeof(currentUrl) === 'string') { currentUrl = parseUrl(currentUrl || document.location.href); } uri.scheme = currentUrl.scheme; uri.host = currentUrl.host; uri.port = currentUrl.port; var path = ''; // for urls without trailing slash we need to figure out the path if (/^[^\/]/.test(uri.path)) { path = currentUrl.path; // if path ends with a filename, strip it if (!/(\/|\/[^\.]+)$/.test(path)) { path = path.replace(/\/[^\/]+$/, '/'); } else { path += '/'; } } uri.path = path + (uri.path || ''); // site may reside at domain.com or domain.com/subdir } if (!uri.port) { uri.port = ports[uri.scheme] || 80; } uri.port = parseInt(uri.port, 10); if (!uri.path) { uri.path = "/"; } delete uri.source; return uri; }; /** Resolve url - among other things will turn relative url to absolute @method resolveUrl @static @param {String} url Either absolute or relative @return {String} Resolved, absolute url */ var resolveUrl = function(url) { var ports = { // we ignore default ports http: 80, https: 443 } , urlp = parseUrl(url) ; return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : ''); }; /** Check if specified url has the same origin as the current document @method hasSameOrigin @param {String|Object} url @return {Boolean} */ var hasSameOrigin = function(url) { function origin(url) { return [url.scheme, url.host, url.port].join('/'); } if (typeof url === 'string') { url = parseUrl(url); } return origin(parseUrl()) === origin(url); }; return { parseUrl: parseUrl, resolveUrl: resolveUrl, hasSameOrigin: hasSameOrigin }; }); // Included from: src/javascript/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileReaderSync', [ 'moxie/core/utils/Basic', 'moxie/runtime/RuntimeClient', 'moxie/core/utils/Encode' ], function(Basic, RuntimeClient, Encode) { /** Synchronous FileReader implementation. Something like this is available in WebWorkers environment, here it can be used to read only preloaded blobs/files and only below certain size (not yet sure what that'd be, but probably < 1mb). Not meant to be used directly by user. @class FileReaderSync @private @constructor */ return function() { RuntimeClient.call(this); Basic.extend(this, { uid: Basic.guid('uid_'), readAsBinaryString: function(blob) { return _read.call(this, 'readAsBinaryString', blob); }, readAsDataURL: function(blob) { return _read.call(this, 'readAsDataURL', blob); }, /*readAsArrayBuffer: function(blob) { return _read.call(this, 'readAsArrayBuffer', blob); },*/ readAsText: function(blob) { return _read.call(this, 'readAsText', blob); } }); function _read(op, blob) { if (blob.isDetached()) { var src = blob.getSource(); switch (op) { case 'readAsBinaryString': return src; case 'readAsDataURL': return 'data:' + blob.type + ';base64,' + Encode.btoa(src); case 'readAsText': var txt = ''; for (var i = 0, length = src.length; i < length; i++) { txt += String.fromCharCode(src[i]); } return txt; } } else { var result = this.connectRuntime(blob.ruid).exec.call(this, 'FileReaderSync', 'read', op, blob); this.disconnectRuntime(); return result; } } }; }); // Included from: src/javascript/xhr/FormData.js /** * FormData.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/xhr/FormData", [ "moxie/core/Exceptions", "moxie/core/utils/Basic", "moxie/file/Blob" ], function(x, Basic, Blob) { /** FormData @class FormData @constructor */ function FormData() { var _blob, _fields = []; Basic.extend(this, { /** Append another key-value pair to the FormData object @method append @param {String} name Name for the new field @param {String|Blob|Array|Object} value Value for the field */ append: function(name, value) { var self = this, valueType = Basic.typeOf(value); // according to specs value might be either Blob or String if (value instanceof Blob) { _blob = { name: name, value: value // unfortunately we can only send single Blob in one FormData }; } else if ('array' === valueType) { name += '[]'; Basic.each(value, function(value) { self.append(name, value); }); } else if ('object' === valueType) { Basic.each(value, function(value, key) { self.append(name + '[' + key + ']', value); }); } else if ('null' === valueType || 'undefined' === valueType || 'number' === valueType && isNaN(value)) { self.append(name, "false"); } else { _fields.push({ name: name, value: value.toString() }); } }, /** Checks if FormData contains Blob. @method hasBlob @return {Boolean} */ hasBlob: function() { return !!this.getBlob(); }, /** Retrieves blob. @method getBlob @return {Object} Either Blob if found or null */ getBlob: function() { return _blob && _blob.value || null; }, /** Retrieves blob field name. @method getBlobName @return {String} Either Blob field name or null */ getBlobName: function() { return _blob && _blob.name || null; }, /** Loop over the fields in FormData and invoke the callback for each of them. @method each @param {Function} cb Callback to call for each field */ each: function(cb) { Basic.each(_fields, function(field) { cb(field.value, field.name); }); if (_blob) { cb(_blob.value, _blob.name); } }, destroy: function() { _blob = null; _fields = []; } }); } return FormData; }); // Included from: src/javascript/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/xhr/XMLHttpRequest", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/core/EventTarget", "moxie/core/utils/Encode", "moxie/core/utils/Url", "moxie/runtime/Runtime", "moxie/runtime/RuntimeTarget", "moxie/file/Blob", "moxie/file/FileReaderSync", "moxie/xhr/FormData", "moxie/core/utils/Env", "moxie/core/utils/Mime" ], function(Basic, x, EventTarget, Encode, Url, Runtime, RuntimeTarget, Blob, FileReaderSync, FormData, Env, Mime) { var httpCode = { 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 207: 'Multi-Status', 226: 'IM Used', 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 306: 'Reserved', 307: 'Temporary Redirect', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request-URI Too Long', 415: 'Unsupported Media Type', 416: 'Requested Range Not Satisfiable', 417: 'Expectation Failed', 422: 'Unprocessable Entity', 423: 'Locked', 424: 'Failed Dependency', 426: 'Upgrade Required', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported', 506: 'Variant Also Negotiates', 507: 'Insufficient Storage', 510: 'Not Extended' }; function XMLHttpRequestUpload() { this.uid = Basic.guid('uid_'); } XMLHttpRequestUpload.prototype = EventTarget.instance; /** Implementation of XMLHttpRequest @class XMLHttpRequest @constructor @uses RuntimeClient @extends EventTarget */ var dispatches = ['loadstart', 'progress', 'abort', 'error', 'load', 'timeout', 'loadend']; // & readystatechange (for historical reasons) var NATIVE = 1, RUNTIME = 2; function XMLHttpRequest() { var self = this, // this (together with _p() @see below) is here to gracefully upgrade to setter/getter syntax where possible props = { /** The amount of milliseconds a request can take before being terminated. Initially zero. Zero means there is no timeout. @property timeout @type Number @default 0 */ timeout: 0, /** Current state, can take following values: UNSENT (numeric value 0) The object has been constructed. OPENED (numeric value 1) The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method. HEADERS_RECEIVED (numeric value 2) All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available. LOADING (numeric value 3) The response entity body is being received. DONE (numeric value 4) @property readyState @type Number @default 0 (UNSENT) */ readyState: XMLHttpRequest.UNSENT, /** True when user credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false. @property withCredentials @type Boolean @default false */ withCredentials: false, /** Returns the HTTP status code. @property status @type Number @default 0 */ status: 0, /** Returns the HTTP status text. @property statusText @type String */ statusText: "", /** Returns the response type. Can be set to change the response type. Values are: the empty string (default), "arraybuffer", "blob", "document", "json", and "text". @property responseType @type String */ responseType: "", /** Returns the document response entity body. Throws an "InvalidStateError" exception if responseType is not the empty string or "document". @property responseXML @type Document */ responseXML: null, /** Returns the text response entity body. Throws an "InvalidStateError" exception if responseType is not the empty string or "text". @property responseText @type String */ responseText: null, /** Returns the response entity body (http://www.w3.org/TR/XMLHttpRequest/#response-entity-body). Can become: ArrayBuffer, Blob, Document, JSON, Text @property response @type Mixed */ response: null }, _async = true, _url, _method, _headers = {}, _user, _password, _encoding = null, _mimeType = null, // flags _sync_flag = false, _send_flag = false, _upload_events_flag = false, _upload_complete_flag = false, _error_flag = false, _same_origin_flag = false, // times _start_time, _timeoutset_time, _finalMime = null, _finalCharset = null, _options = {}, _xhr, _responseHeaders = '', _responseHeadersBag ; Basic.extend(this, props, { /** Unique id of the component @property uid @type String */ uid: Basic.guid('uid_'), /** Target for Upload events @property upload @type XMLHttpRequestUpload */ upload: new XMLHttpRequestUpload(), /** Sets the request method, request URL, synchronous flag, request username, and request password. Throws a "SyntaxError" exception if one of the following is true: method is not a valid HTTP method. url cannot be resolved. url contains the "user:password" format in the userinfo production. Throws a "SecurityError" exception if method is a case-insensitive match for CONNECT, TRACE or TRACK. Throws an "InvalidAccessError" exception if one of the following is true: Either user or password is passed as argument and the origin of url does not match the XMLHttpRequest origin. There is an associated XMLHttpRequest document and either the timeout attribute is not zero, the withCredentials attribute is true, or the responseType attribute is not the empty string. @method open @param {String} method HTTP method to use on request @param {String} url URL to request @param {Boolean} [async=true] If false request will be done in synchronous manner. Asynchronous by default. @param {String} [user] Username to use in HTTP authentication process on server-side @param {String} [password] Password to use in HTTP authentication process on server-side */ open: function(method, url, async, user, password) { var urlp; // first two arguments are required if (!method || !url) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 2 - check if any code point in method is higher than U+00FF or after deflating method it does not match the method if (/[\u0100-\uffff]/.test(method) || Encode.utf8_encode(method) !== method) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 3 if (!!~Basic.inArray(method.toUpperCase(), ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'TRACE', 'TRACK'])) { _method = method.toUpperCase(); } // 4 - allowing these methods poses a security risk if (!!~Basic.inArray(_method, ['CONNECT', 'TRACE', 'TRACK'])) { throw new x.DOMException(x.DOMException.SECURITY_ERR); } // 5 url = Encode.utf8_encode(url); // 6 - Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error, throw a "SyntaxError". urlp = Url.parseUrl(url); _same_origin_flag = Url.hasSameOrigin(urlp); // 7 - manually build up absolute url _url = Url.resolveUrl(url); // 9-10, 12-13 if ((user || password) && !_same_origin_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } _user = user || urlp.user; _password = password || urlp.pass; // 11 _async = async || true; if (_async === false && (_p('timeout') || _p('withCredentials') || _p('responseType') !== "")) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 14 - terminate abort() // 15 - terminate send() // 18 _sync_flag = !_async; _send_flag = false; _headers = {}; _reset.call(this); // 19 _p('readyState', XMLHttpRequest.OPENED); // 20 this.convertEventPropsToHandlers(['readystatechange']); // unify event handlers this.dispatchEvent('readystatechange'); }, /** Appends an header to the list of author request headers, or if header is already in the list of author request headers, combines its value with value. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set. Throws a "SyntaxError" exception if header is not a valid HTTP header field name or if value is not a valid HTTP header field value. @method setRequestHeader @param {String} header @param {String|Number} value */ setRequestHeader: function(header, value) { var uaHeaders = [ // these headers are controlled by the user agent "accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "content-transfer-encoding", "date", "expect", "host", "keep-alive", "origin", "referer", "te", "trailer", "transfer-encoding", "upgrade", "user-agent", "via" ]; // 1-2 if (_p('readyState') !== XMLHttpRequest.OPENED || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3 if (/[\u0100-\uffff]/.test(header) || Encode.utf8_encode(header) !== header) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 4 /* this step is seemingly bypassed in browsers, probably to allow various unicode characters in header values if (/[\u0100-\uffff]/.test(value) || Encode.utf8_encode(value) !== value) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); }*/ header = Basic.trim(header).toLowerCase(); // setting of proxy-* and sec-* headers is prohibited by spec if (!!~Basic.inArray(header, uaHeaders) || /^(proxy\-|sec\-)/.test(header)) { return false; } // camelize // browsers lowercase header names (at least for custom ones) // header = header.replace(/\b\w/g, function($1) { return $1.toUpperCase(); }); if (!_headers[header]) { _headers[header] = value; } else { // http://tools.ietf.org/html/rfc2616#section-4.2 (last paragraph) _headers[header] += ', ' + value; } return true; }, /** Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2. @method getAllResponseHeaders @return {String} reponse headers or empty string */ getAllResponseHeaders: function() { return _responseHeaders || ''; }, /** Returns the header field value from the response of which the field name matches header, unless the field name is Set-Cookie or Set-Cookie2. @method getResponseHeader @param {String} header @return {String} value(s) for the specified header or null */ getResponseHeader: function(header) { header = header.toLowerCase(); if (_error_flag || !!~Basic.inArray(header, ['set-cookie', 'set-cookie2'])) { return null; } if (_responseHeaders && _responseHeaders !== '') { // if we didn't parse response headers until now, do it and keep for later if (!_responseHeadersBag) { _responseHeadersBag = {}; Basic.each(_responseHeaders.split(/\r\n/), function(line) { var pair = line.split(/:\s+/); if (pair.length === 2) { // last line might be empty, omit pair[0] = Basic.trim(pair[0]); // just in case _responseHeadersBag[pair[0].toLowerCase()] = { // simply to retain header name in original form header: pair[0], value: Basic.trim(pair[1]) }; } }); } if (_responseHeadersBag.hasOwnProperty(header)) { return _responseHeadersBag[header].header + ': ' + _responseHeadersBag[header].value; } } return null; }, /** Sets the Content-Type header for the response to mime. Throws an "InvalidStateError" exception if the state is LOADING or DONE. Throws a "SyntaxError" exception if mime is not a valid media type. @method overrideMimeType @param String mime Mime type to set */ overrideMimeType: function(mime) { var matches, charset; // 1 if (!!~Basic.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2 mime = Basic.trim(mime.toLowerCase()); if (/;/.test(mime) && (matches = mime.match(/^([^;]+)(?:;\scharset\=)?(.*)$/))) { mime = matches[1]; if (matches[2]) { charset = matches[2]; } } if (!Mime.mimes[mime]) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 3-4 _finalMime = mime; _finalCharset = charset; }, /** Initiates the request. The optional argument provides the request entity body. The argument is ignored if request method is GET or HEAD. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set. @method send @param {Blob|Document|String|FormData} [data] Request entity body @param {Object} [options] Set of requirements and pre-requisities for runtime initialization */ send: function(data, options) { if (Basic.typeOf(options) === 'string') { _options = { ruid: options }; } else if (!options) { _options = {}; } else { _options = options; } this.convertEventPropsToHandlers(dispatches); this.upload.convertEventPropsToHandlers(dispatches); // 1-2 if (this.readyState !== XMLHttpRequest.OPENED || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3 // sending Blob if (data instanceof Blob) { _options.ruid = data.ruid; _mimeType = data.type || 'application/octet-stream'; } // FormData else if (data instanceof FormData) { if (data.hasBlob()) { var blob = data.getBlob(); _options.ruid = blob.ruid; _mimeType = blob.type || 'application/octet-stream'; } } // DOMString else if (typeof data === 'string') { _encoding = 'UTF-8'; _mimeType = 'text/plain;charset=UTF-8'; // data should be converted to Unicode and encoded as UTF-8 data = Encode.utf8_encode(data); } // if withCredentials not set, but requested, set it automatically if (!this.withCredentials) { this.withCredentials = (_options.required_caps && _options.required_caps.send_browser_cookies) && !_same_origin_flag; } // 4 - storage mutex // 5 _upload_events_flag = (!_sync_flag && this.upload.hasEventListener()); // DSAP // 6 _error_flag = false; // 7 _upload_complete_flag = !data; // 8 - Asynchronous steps if (!_sync_flag) { // 8.1 _send_flag = true; // 8.2 // this.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr // 8.3 //if (!_upload_complete_flag) { // this.upload.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr //} } // 8.5 - Return the send() method call, but continue running the steps in this algorithm. _doXHR.call(this, data); }, /** Cancels any network activity. @method abort */ abort: function() { _error_flag = true; _sync_flag = false; if (!~Basic.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED, XMLHttpRequest.DONE])) { _p('readyState', XMLHttpRequest.DONE); _send_flag = false; if (_xhr) { _xhr.getRuntime().exec.call(_xhr, 'XMLHttpRequest', 'abort', _upload_complete_flag); } else { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } _upload_complete_flag = true; } else { _p('readyState', XMLHttpRequest.UNSENT); } }, destroy: function() { if (_xhr) { if (Basic.typeOf(_xhr.destroy) === 'function') { _xhr.destroy(); } _xhr = null; } this.unbindAll(); if (this.upload) { this.upload.unbindAll(); this.upload = null; } } }); /* this is nice, but maybe too lengthy // if supported by JS version, set getters/setters for specific properties o.defineProperty(this, 'readyState', { configurable: false, get: function() { return _p('readyState'); } }); o.defineProperty(this, 'timeout', { configurable: false, get: function() { return _p('timeout'); }, set: function(value) { if (_sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // timeout still should be measured relative to the start time of request _timeoutset_time = (new Date).getTime(); _p('timeout', value); } }); // the withCredentials attribute has no effect when fetching same-origin resources o.defineProperty(this, 'withCredentials', { configurable: false, get: function() { return _p('withCredentials'); }, set: function(value) { // 1-2 if (!~o.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED]) || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3-4 if (_anonymous_flag || _sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 5 _p('withCredentials', value); } }); o.defineProperty(this, 'status', { configurable: false, get: function() { return _p('status'); } }); o.defineProperty(this, 'statusText', { configurable: false, get: function() { return _p('statusText'); } }); o.defineProperty(this, 'responseType', { configurable: false, get: function() { return _p('responseType'); }, set: function(value) { // 1 if (!!~o.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2 if (_sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 3 _p('responseType', value.toLowerCase()); } }); o.defineProperty(this, 'responseText', { configurable: false, get: function() { // 1 if (!~o.inArray(_p('responseType'), ['', 'text'])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2-3 if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return _p('responseText'); } }); o.defineProperty(this, 'responseXML', { configurable: false, get: function() { // 1 if (!~o.inArray(_p('responseType'), ['', 'document'])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2-3 if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return _p('responseXML'); } }); o.defineProperty(this, 'response', { configurable: false, get: function() { if (!!~o.inArray(_p('responseType'), ['', 'text'])) { if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) { return ''; } } if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) { return null; } return _p('response'); } }); */ function _p(prop, value) { if (!props.hasOwnProperty(prop)) { return; } if (arguments.length === 1) { // get return Env.can('define_property') ? props[prop] : self[prop]; } else { // set if (Env.can('define_property')) { props[prop] = value; } else { self[prop] = value; } } } /* function _toASCII(str, AllowUnassigned, UseSTD3ASCIIRules) { // TODO: http://tools.ietf.org/html/rfc3490#section-4.1 return str.toLowerCase(); } */ function _doXHR(data) { var self = this; _start_time = new Date().getTime(); _xhr = new RuntimeTarget(); function loadEnd() { if (_xhr) { // it could have been destroyed by now _xhr.destroy(); _xhr = null; } self.dispatchEvent('loadend'); self = null; } function exec(runtime) { _xhr.bind('LoadStart', function(e) { _p('readyState', XMLHttpRequest.LOADING); self.dispatchEvent('readystatechange'); self.dispatchEvent(e); if (_upload_events_flag) { self.upload.dispatchEvent(e); } }); _xhr.bind('Progress', function(e) { if (_p('readyState') !== XMLHttpRequest.LOADING) { _p('readyState', XMLHttpRequest.LOADING); // LoadStart unreliable (in Flash for example) self.dispatchEvent('readystatechange'); } self.dispatchEvent(e); }); _xhr.bind('UploadProgress', function(e) { if (_upload_events_flag) { self.upload.dispatchEvent({ type: 'progress', lengthComputable: false, total: e.total, loaded: e.loaded }); } }); _xhr.bind('Load', function(e) { _p('readyState', XMLHttpRequest.DONE); _p('status', Number(runtime.exec.call(_xhr, 'XMLHttpRequest', 'getStatus') || 0)); _p('statusText', httpCode[_p('status')] || ""); _p('response', runtime.exec.call(_xhr, 'XMLHttpRequest', 'getResponse', _p('responseType'))); if (!!~Basic.inArray(_p('responseType'), ['text', ''])) { _p('responseText', _p('response')); } else if (_p('responseType') === 'document') { _p('responseXML', _p('response')); } _responseHeaders = runtime.exec.call(_xhr, 'XMLHttpRequest', 'getAllResponseHeaders'); self.dispatchEvent('readystatechange'); if (_p('status') > 0) { // status 0 usually means that server is unreachable if (_upload_events_flag) { self.upload.dispatchEvent(e); } self.dispatchEvent(e); } else { _error_flag = true; self.dispatchEvent('error'); } loadEnd(); }); _xhr.bind('Abort', function(e) { self.dispatchEvent(e); loadEnd(); }); _xhr.bind('Error', function(e) { _error_flag = true; _p('readyState', XMLHttpRequest.DONE); self.dispatchEvent('readystatechange'); _upload_complete_flag = true; self.dispatchEvent(e); loadEnd(); }); runtime.exec.call(_xhr, 'XMLHttpRequest', 'send', { url: _url, method: _method, async: _async, user: _user, password: _password, headers: _headers, mimeType: _mimeType, encoding: _encoding, responseType: self.responseType, withCredentials: self.withCredentials, options: _options }, data); } // clarify our requirements if (typeof(_options.required_caps) === 'string') { _options.required_caps = Runtime.parseCaps(_options.required_caps); } _options.required_caps = Basic.extend({}, _options.required_caps, { return_response_type: self.responseType }); if (data instanceof FormData) { _options.required_caps.send_multipart = true; } if (!_same_origin_flag) { _options.required_caps.do_cors = true; } if (_options.ruid) { // we do not need to wait if we can connect directly exec(_xhr.connectRuntime(_options)); } else { _xhr.bind('RuntimeInit', function(e, runtime) { exec(runtime); }); _xhr.bind('RuntimeError', function(e, err) { self.dispatchEvent('RuntimeError', err); }); _xhr.connectRuntime(_options); } } function _reset() { _p('responseText', ""); _p('responseXML', null); _p('response', null); _p('status', 0); _p('statusText', ""); _start_time = _timeoutset_time = null; } } XMLHttpRequest.UNSENT = 0; XMLHttpRequest.OPENED = 1; XMLHttpRequest.HEADERS_RECEIVED = 2; XMLHttpRequest.LOADING = 3; XMLHttpRequest.DONE = 4; XMLHttpRequest.prototype = EventTarget.instance; return XMLHttpRequest; }); // Included from: src/javascript/runtime/flash/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global ActiveXObject:true */ /** Defines constructor for Flash runtime. @class moxie/runtime/flash/Runtime @private */ define("moxie/runtime/flash/Runtime", [ "moxie/core/utils/Basic", "moxie/core/utils/Env", "moxie/core/utils/Dom", "moxie/core/Exceptions", "moxie/runtime/Runtime" ], function(Basic, Env, Dom, x, Runtime) { var type = 'flash', extensions = {}; /** Get the version of the Flash Player @method getShimVersion @private @return {Number} Flash Player version */ function getShimVersion() { var version; try { version = navigator.plugins['Shockwave Flash']; version = version.description; } catch (e1) { try { version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version'); } catch (e2) { version = '0.0'; } } version = version.match(/\d+/g); return parseFloat(version[0] + '.' + version[1]); } /** Constructor for the Flash Runtime @class FlashRuntime @extends Runtime */ function FlashRuntime(options) { var I = this, initTimer; options = Basic.extend({ swf_url: Env.swf_url }, options); Runtime.call(this, options, type, { access_binary: function(value) { return value && I.mode === 'browser'; }, access_image_binary: function(value) { return value && I.mode === 'browser'; }, display_media: Runtime.capTrue, do_cors: Runtime.capTrue, drag_and_drop: false, report_upload_progress: function() { return I.mode === 'client'; }, resize_image: Runtime.capTrue, return_response_headers: false, return_response_type: function(responseType) { if (responseType === 'json' && !!window.JSON) { return true; } return !Basic.arrayDiff(responseType, ['', 'text', 'document']) || I.mode === 'browser'; }, return_status_code: function(code) { return I.mode === 'browser' || !Basic.arrayDiff(code, [200, 404]); }, select_file: Runtime.capTrue, select_multiple: Runtime.capTrue, send_binary_string: function(value) { return value && I.mode === 'browser'; }, send_browser_cookies: function(value) { return value && I.mode === 'browser'; }, send_custom_headers: function(value) { return value && I.mode === 'browser'; }, send_multipart: Runtime.capTrue, slice_blob: function(value) { return value && I.mode === 'browser'; }, stream_upload: function(value) { return value && I.mode === 'browser'; }, summon_file_dialog: false, upload_filesize: function(size) { return Basic.parseSizeStr(size) <= 2097152 || I.mode === 'client'; }, use_http_method: function(methods) { return !Basic.arrayDiff(methods, ['GET', 'POST']); } }, { // capabilities that require specific mode access_binary: function(value) { return value ? 'browser' : 'client'; }, access_image_binary: function(value) { return value ? 'browser' : 'client'; }, report_upload_progress: function(value) { return value ? 'browser' : 'client'; }, return_response_type: function(responseType) { return Basic.arrayDiff(responseType, ['', 'text', 'json', 'document']) ? 'browser' : ['client', 'browser']; }, return_status_code: function(code) { return Basic.arrayDiff(code, [200, 404]) ? 'browser' : ['client', 'browser']; }, send_binary_string: function(value) { return value ? 'browser' : 'client'; }, send_browser_cookies: function(value) { return value ? 'browser' : 'client'; }, send_custom_headers: function(value) { return value ? 'browser' : 'client'; }, stream_upload: function(value) { return value ? 'client' : 'browser'; }, upload_filesize: function(size) { return Basic.parseSizeStr(size) >= 2097152 ? 'client' : 'browser'; } }, 'client'); // minimal requirement for Flash Player version if (getShimVersion() < 10) { this.mode = false; // with falsy mode, runtime won't operable, no matter what the mode was before } Basic.extend(this, { getShim: function() { return Dom.get(this.uid); }, shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return I.getShim().exec(this.uid, component, action, args); }, init: function() { var html, el, container; container = this.getShimContainer(); // if not the minimal height, shims are not initialized in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc) Basic.extend(container.style, { position: 'absolute', top: '-8px', left: '-8px', width: '9px', height: '9px', overflow: 'hidden' }); // insert flash object html = '<object id="' + this.uid + '" type="application/x-shockwave-flash" data="' + options.swf_url + '" '; if (Env.browser === 'IE') { html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '; } html += 'width="100%" height="100%" style="outline:0">' + '<param name="movie" value="' + options.swf_url + '" />' + '<param name="flashvars" value="uid=' + escape(this.uid) + '&target=' + Env.global_event_dispatcher + '" />' + '<param name="wmode" value="transparent" />' + '<param name="allowscriptaccess" value="always" />' + '</object>'; if (Env.browser === 'IE') { el = document.createElement('div'); container.appendChild(el); el.outerHTML = html; el = container = null; // just in case } else { container.innerHTML = html; } // Init is dispatched by the shim initTimer = setTimeout(function() { if (I && !I.initialized) { // runtime might be already destroyed by this moment I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); } }, 5000); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); clearTimeout(initTimer); // initialization check might be still onwait options = initTimer = destroy = I = null; }; }(this.destroy)) }, extensions); } Runtime.addConstructor(type, FlashRuntime); return extensions; }); // Included from: src/javascript/runtime/flash/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/Blob @private */ define("moxie/runtime/flash/file/Blob", [ "moxie/runtime/flash/Runtime", "moxie/file/Blob" ], function(extensions, Blob) { var FlashBlob = { slice: function(blob, start, end, type) { var self = this.getRuntime(); if (start < 0) { start = Math.max(blob.size + start, 0); } else if (start > 0) { start = Math.min(start, blob.size); } if (end < 0) { end = Math.max(blob.size + end, 0); } else if (end > 0) { end = Math.min(end, blob.size); } blob = self.shimExec.call(this, 'Blob', 'slice', start, end, type || ''); if (blob) { blob = new Blob(self.uid, blob); } return blob; } }; return (extensions.Blob = FlashBlob); }); // Included from: src/javascript/runtime/flash/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/FileInput @private */ define("moxie/runtime/flash/file/FileInput", [ "moxie/runtime/flash/Runtime" ], function(extensions) { var FileInput = { init: function(options) { this.getRuntime().shimExec.call(this, 'FileInput', 'init', { name: options.name, accept: options.accept, multiple: options.multiple }); this.trigger('ready'); } }; return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/flash/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/FileReader @private */ define("moxie/runtime/flash/file/FileReader", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Encode" ], function(extensions, Encode) { var _result = ''; function _formatData(data, op) { switch (op) { case 'readAsText': return Encode.atob(data, 'utf8'); case 'readAsBinaryString': return Encode.atob(data); case 'readAsDataURL': return data; } return null; } var FileReader = { read: function(op, blob) { var target = this, self = target.getRuntime(); // special prefix for DataURL read mode if (op === 'readAsDataURL') { _result = 'data:' + (blob.type || '') + ';base64,'; } target.bind('Progress', function(e, data) { if (data) { _result += _formatData(data, op); } }); return self.shimExec.call(this, 'FileReader', 'readAsBase64', blob.uid); }, getResult: function() { return _result; }, destroy: function() { _result = null; } }; return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/flash/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/FileReaderSync @private */ define("moxie/runtime/flash/file/FileReaderSync", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Encode" ], function(extensions, Encode) { function _formatData(data, op) { switch (op) { case 'readAsText': return Encode.atob(data, 'utf8'); case 'readAsBinaryString': return Encode.atob(data); case 'readAsDataURL': return data; } return null; } var FileReaderSync = { read: function(op, blob) { var result, self = this.getRuntime(); result = self.shimExec.call(this, 'FileReaderSync', 'readAsBase64', blob.uid); if (!result) { return null; // or throw ex } // special prefix for DataURL read mode if (op === 'readAsDataURL') { result = 'data:' + (blob.type || '') + ';base64,' + result; } return _formatData(result, op, blob.type); } }; return (extensions.FileReaderSync = FileReaderSync); }); // Included from: src/javascript/runtime/Transporter.js /** * Transporter.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/runtime/Transporter", [ "moxie/core/utils/Basic", "moxie/core/utils/Encode", "moxie/runtime/RuntimeClient", "moxie/core/EventTarget" ], function(Basic, Encode, RuntimeClient, EventTarget) { function Transporter() { var mod, _runtime, _data, _size, _pos, _chunk_size; RuntimeClient.call(this); Basic.extend(this, { uid: Basic.guid('uid_'), state: Transporter.IDLE, result: null, transport: function(data, type, options) { var self = this; options = Basic.extend({ chunk_size: 204798 }, options); // should divide by three, base64 requires this if ((mod = options.chunk_size % 3)) { options.chunk_size += 3 - mod; } _chunk_size = options.chunk_size; _reset.call(this); _data = data; _size = data.length; if (Basic.typeOf(options) === 'string' || options.ruid) { _run.call(self, type, this.connectRuntime(options)); } else { // we require this to run only once var cb = function(e, runtime) { self.unbind("RuntimeInit", cb); _run.call(self, type, runtime); }; this.bind("RuntimeInit", cb); this.connectRuntime(options); } }, abort: function() { var self = this; self.state = Transporter.IDLE; if (_runtime) { _runtime.exec.call(self, 'Transporter', 'clear'); self.trigger("TransportingAborted"); } _reset.call(self); }, destroy: function() { this.unbindAll(); _runtime = null; this.disconnectRuntime(); _reset.call(this); } }); function _reset() { _size = _pos = 0; _data = this.result = null; } function _run(type, runtime) { var self = this; _runtime = runtime; //self.unbind("RuntimeInit"); self.bind("TransportingProgress", function(e) { _pos = e.loaded; if (_pos < _size && Basic.inArray(self.state, [Transporter.IDLE, Transporter.DONE]) === -1) { _transport.call(self); } }, 999); self.bind("TransportingComplete", function() { _pos = _size; self.state = Transporter.DONE; _data = null; // clean a bit self.result = _runtime.exec.call(self, 'Transporter', 'getAsBlob', type || ''); }, 999); self.state = Transporter.BUSY; self.trigger("TransportingStarted"); _transport.call(self); } function _transport() { var self = this, chunk, bytesLeft = _size - _pos; if (_chunk_size > bytesLeft) { _chunk_size = bytesLeft; } chunk = Encode.btoa(_data.substr(_pos, _chunk_size)); _runtime.exec.call(self, 'Transporter', 'receive', chunk, _size); } } Transporter.IDLE = 0; Transporter.BUSY = 1; Transporter.DONE = 2; Transporter.prototype = EventTarget.instance; return Transporter; }); // Included from: src/javascript/runtime/flash/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/xhr/XMLHttpRequest @private */ define("moxie/runtime/flash/xhr/XMLHttpRequest", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Basic", "moxie/file/Blob", "moxie/file/File", "moxie/file/FileReaderSync", "moxie/xhr/FormData", "moxie/runtime/Transporter" ], function(extensions, Basic, Blob, File, FileReaderSync, FormData, Transporter) { var XMLHttpRequest = { send: function(meta, data) { var target = this, self = target.getRuntime(); function send() { meta.transport = self.mode; self.shimExec.call(target, 'XMLHttpRequest', 'send', meta, data); } function appendBlob(name, blob) { self.shimExec.call(target, 'XMLHttpRequest', 'appendBlob', name, blob.uid); data = null; send(); } function attachBlob(blob, cb) { var tr = new Transporter(); tr.bind("TransportingComplete", function() { cb(this.result); }); tr.transport(blob.getSource(), blob.type, { ruid: self.uid }); } // copy over the headers if any if (!Basic.isEmptyObj(meta.headers)) { Basic.each(meta.headers, function(value, header) { self.shimExec.call(target, 'XMLHttpRequest', 'setRequestHeader', header, value.toString()); // Silverlight doesn't accept integers into the arguments of type object }); } // transfer over multipart params and blob itself if (data instanceof FormData) { var blobField; data.each(function(value, name) { if (value instanceof Blob) { blobField = name; } else { self.shimExec.call(target, 'XMLHttpRequest', 'append', name, value); } }); if (!data.hasBlob()) { data = null; send(); } else { var blob = data.getBlob(); if (blob.isDetached()) { attachBlob(blob, function(attachedBlob) { blob.destroy(); appendBlob(blobField, attachedBlob); }); } else { appendBlob(blobField, blob); } } } else if (data instanceof Blob) { if (data.isDetached()) { attachBlob(data, function(attachedBlob) { data.destroy(); data = attachedBlob.uid; send(); }); } else { data = data.uid; send(); } } else { send(); } }, getResponse: function(responseType) { var frs, blob, self = this.getRuntime(); blob = self.shimExec.call(this, 'XMLHttpRequest', 'getResponseAsBlob'); if (blob) { blob = new File(self.uid, blob); if ('blob' === responseType) { return blob; } try { frs = new FileReaderSync(); if (!!~Basic.inArray(responseType, ["", "text"])) { return frs.readAsText(blob); } else if ('json' === responseType && !!window.JSON) { return JSON.parse(frs.readAsText(blob)); } } finally { blob.destroy(); } } return null; }, abort: function(upload_complete_flag) { var self = this.getRuntime(); self.shimExec.call(this, 'XMLHttpRequest', 'abort'); this.dispatchEvent('readystatechange'); // this.dispatchEvent('progress'); this.dispatchEvent('abort'); //if (!upload_complete_flag) { // this.dispatchEvent('uploadprogress'); //} } }; return (extensions.XMLHttpRequest = XMLHttpRequest); }); // Included from: src/javascript/runtime/html4/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global File:true */ /** Defines constructor for HTML4 runtime. @class moxie/runtime/html4/Runtime @private */ define("moxie/runtime/html4/Runtime", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/Runtime", "moxie/core/utils/Env" ], function(Basic, x, Runtime, Env) { var type = 'html4', extensions = {}; function Html4Runtime(options) { var I = this , Test = Runtime.capTest , True = Runtime.capTrue ; Runtime.call(this, options, type, { access_binary: Test(window.FileReader || window.File && File.getAsDataURL), access_image_binary: false, display_media: Test(extensions.Image && (Env.can('create_canvas') || Env.can('use_data_uri_over32kb'))), do_cors: false, drag_and_drop: false, filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10); }()), resize_image: function() { return extensions.Image && I.can('access_binary') && Env.can('create_canvas'); }, report_upload_progress: false, return_response_headers: false, return_response_type: function(responseType) { if (responseType === 'json' && !!window.JSON) { return true; } return !!~Basic.inArray(responseType, ['text', 'document', '']); }, return_status_code: function(code) { return !Basic.arrayDiff(code, [200, 404]); }, select_file: function() { return Env.can('use_fileinput'); }, select_multiple: false, send_binary_string: false, send_custom_headers: false, send_multipart: true, slice_blob: false, stream_upload: function() { return I.can('select_file'); }, summon_file_dialog: Test(function() { // yeah... some dirty sniffing here... return (Env.browser === 'Firefox' && Env.version >= 4) || (Env.browser === 'Opera' && Env.version >= 12) || !!~Basic.inArray(Env.browser, ['Chrome', 'Safari']); }()), upload_filesize: True, use_http_method: function(methods) { return !Basic.arrayDiff(methods, ['GET', 'POST']); } }); Basic.extend(this, { init : function() { this.trigger("Init"); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); destroy = I = null; }; }(this.destroy)) }); Basic.extend(this.getShim(), extensions); } Runtime.addConstructor(type, Html4Runtime); return extensions; }); // Included from: src/javascript/core/utils/Events.js /** * Events.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Events', [ 'moxie/core/utils/Basic' ], function(Basic) { var eventhash = {}, uid = 'moxie_' + Basic.guid(); // IE W3C like event funcs function preventDefault() { this.returnValue = false; } function stopPropagation() { this.cancelBubble = true; } /** Adds an event handler to the specified object and store reference to the handler in objects internal Plupload registry (@see removeEvent). @method addEvent @for Utils @static @param {Object} obj DOM element like object to add handler to. @param {String} name Name to add event listener to. @param {Function} callback Function to call when event occurs. @param {String} [key] that might be used to add specifity to the event record. */ var addEvent = function(obj, name, callback, key) { var func, events; name = name.toLowerCase(); // Add event listener if (obj.addEventListener) { func = callback; obj.addEventListener(name, func, false); } else if (obj.attachEvent) { func = function() { var evt = window.event; if (!evt.target) { evt.target = evt.srcElement; } evt.preventDefault = preventDefault; evt.stopPropagation = stopPropagation; callback(evt); }; obj.attachEvent('on' + name, func); } // Log event handler to objects internal mOxie registry if (!obj[uid]) { obj[uid] = Basic.guid(); } if (!eventhash.hasOwnProperty(obj[uid])) { eventhash[obj[uid]] = {}; } events = eventhash[obj[uid]]; if (!events.hasOwnProperty(name)) { events[name] = []; } events[name].push({ func: func, orig: callback, // store original callback for IE key: key }); }; /** Remove event handler from the specified object. If third argument (callback) is not specified remove all events with the specified name. @method removeEvent @static @param {Object} obj DOM element to remove event listener(s) from. @param {String} name Name of event listener to remove. @param {Function|String} [callback] might be a callback or unique key to match. */ var removeEvent = function(obj, name, callback) { var type, undef; name = name.toLowerCase(); if (obj[uid] && eventhash[obj[uid]] && eventhash[obj[uid]][name]) { type = eventhash[obj[uid]][name]; } else { return; } for (var i = type.length - 1; i >= 0; i--) { // undefined or not, key should match if (type[i].orig === callback || type[i].key === callback) { if (obj.removeEventListener) { obj.removeEventListener(name, type[i].func, false); } else if (obj.detachEvent) { obj.detachEvent('on'+name, type[i].func); } type[i].orig = null; type[i].func = null; type.splice(i, 1); // If callback was passed we are done here, otherwise proceed if (callback !== undef) { break; } } } // If event array got empty, remove it if (!type.length) { delete eventhash[obj[uid]][name]; } // If mOxie registry has become empty, remove it if (Basic.isEmptyObj(eventhash[obj[uid]])) { delete eventhash[obj[uid]]; // IE doesn't let you remove DOM object property with - delete try { delete obj[uid]; } catch(e) { obj[uid] = undef; } } }; /** Remove all kind of events from the specified object @method removeAllEvents @static @param {Object} obj DOM element to remove event listeners from. @param {String} [key] unique key to match, when removing events. */ var removeAllEvents = function(obj, key) { if (!obj || !obj[uid]) { return; } Basic.each(eventhash[obj[uid]], function(events, name) { removeEvent(obj, name, key); }); }; return { addEvent: addEvent, removeEvent: removeEvent, removeAllEvents: removeAllEvents }; }); // Included from: src/javascript/runtime/html4/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/file/FileInput @private */ define("moxie/runtime/html4/file/FileInput", [ "moxie/runtime/html4/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Events", "moxie/core/utils/Mime", "moxie/core/utils/Env" ], function(extensions, Basic, Dom, Events, Mime, Env) { function FileInput() { var _uid, _files = [], _mimes = [], _options; function addInput() { var comp = this, I = comp.getRuntime(), shimContainer, browseButton, currForm, form, input, uid; uid = Basic.guid('uid_'); shimContainer = I.getShimContainer(); // we get new ref everytime to avoid memory leaks in IE if (_uid) { // move previous form out of the view currForm = Dom.get(_uid + '_form'); if (currForm) { Basic.extend(currForm.style, { top: '100%' }); } } // build form in DOM, since innerHTML version not able to submit file for some reason form = document.createElement('form'); form.setAttribute('id', uid + '_form'); form.setAttribute('method', 'post'); form.setAttribute('enctype', 'multipart/form-data'); form.setAttribute('encoding', 'multipart/form-data'); Basic.extend(form.style, { overflow: 'hidden', position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }); input = document.createElement('input'); input.setAttribute('id', uid); input.setAttribute('type', 'file'); input.setAttribute('name', _options.name || 'Filedata'); input.setAttribute('accept', _mimes.join(',')); Basic.extend(input.style, { fontSize: '999px', opacity: 0 }); form.appendChild(input); shimContainer.appendChild(form); // prepare file input to be placed underneath the browse_button element Basic.extend(input.style, { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }); if (Env.browser === 'IE' && Env.version < 10) { Basic.extend(input.style, { filter : "progid:DXImageTransform.Microsoft.Alpha(opacity=0)" }); } input.onchange = function() { // there should be only one handler for this var file; if (!this.value) { return; } if (this.files) { file = this.files[0]; } else { file = { name: this.value }; } _files = [file]; this.onchange = function() {}; // clear event handler addInput.call(comp); // after file is initialized as o.File, we need to update form and input ids comp.bind('change', function onChange() { var input = Dom.get(uid), form = Dom.get(uid + '_form'), file; comp.unbind('change', onChange); if (comp.files.length && input && form) { file = comp.files[0]; input.setAttribute('id', file.uid); form.setAttribute('id', file.uid + '_form'); // set upload target form.setAttribute('target', file.uid + '_iframe'); } input = form = null; }, 998); input = form = null; comp.trigger('change'); }; // route click event to the input if (I.can('summon_file_dialog')) { browseButton = Dom.get(_options.browse_button); Events.removeEvent(browseButton, 'click', comp.uid); Events.addEvent(browseButton, 'click', function(e) { if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file] input.click(); } e.preventDefault(); }, comp.uid); } _uid = uid; shimContainer = currForm = browseButton = null; } Basic.extend(this, { init: function(options) { var comp = this, I = comp.getRuntime(), shimContainer; // figure out accept string _options = options; _mimes = options.accept.mimes || Mime.extList2mimes(options.accept, I.can('filter_by_extension')); shimContainer = I.getShimContainer(); (function() { var browseButton, zIndex, top; browseButton = Dom.get(options.browse_button); // Route click event to the input[type=file] element for browsers that support such behavior if (I.can('summon_file_dialog')) { if (Dom.getStyle(browseButton, 'position') === 'static') { browseButton.style.position = 'relative'; } zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 1; browseButton.style.zIndex = zIndex; shimContainer.style.zIndex = zIndex - 1; } /* Since we have to place input[type=file] on top of the browse_button for some browsers, browse_button loses interactivity, so we restore it here */ top = I.can('summon_file_dialog') ? browseButton : shimContainer; Events.addEvent(top, 'mouseover', function() { comp.trigger('mouseenter'); }, comp.uid); Events.addEvent(top, 'mouseout', function() { comp.trigger('mouseleave'); }, comp.uid); Events.addEvent(top, 'mousedown', function() { comp.trigger('mousedown'); }, comp.uid); Events.addEvent(Dom.get(options.container), 'mouseup', function() { comp.trigger('mouseup'); }, comp.uid); browseButton = null; }()); addInput.call(this); shimContainer = null; // trigger ready event asynchronously comp.trigger({ type: 'ready', async: true }); }, getFiles: function() { return _files; }, disable: function(state) { var input; if ((input = Dom.get(_uid))) { input.disabled = !!state; } }, destroy: function() { var I = this.getRuntime() , shim = I.getShim() , shimContainer = I.getShimContainer() ; Events.removeAllEvents(shimContainer, this.uid); Events.removeAllEvents(_options && Dom.get(_options.container), this.uid); Events.removeAllEvents(_options && Dom.get(_options.browse_button), this.uid); if (shimContainer) { shimContainer.innerHTML = ''; } shim.removeInstance(this.uid); _uid = _files = _mimes = _options = shimContainer = shim = null; } }); } return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/html5/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global File:true */ /** Defines constructor for HTML5 runtime. @class moxie/runtime/html5/Runtime @private */ define("moxie/runtime/html5/Runtime", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/Runtime", "moxie/core/utils/Env" ], function(Basic, x, Runtime, Env) { var type = "html5", extensions = {}; function Html5Runtime(options) { var I = this , Test = Runtime.capTest , True = Runtime.capTrue ; var caps = Basic.extend({ access_binary: Test(window.FileReader || window.File && window.File.getAsDataURL), access_image_binary: function() { return I.can('access_binary') && !!extensions.Image; }, display_media: Test(Env.can('create_canvas') || Env.can('use_data_uri_over32kb')), do_cors: Test(window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()), drag_and_drop: Test(function() { // this comes directly from Modernizr: http://www.modernizr.com/ var div = document.createElement('div'); // IE has support for drag and drop since version 5, but doesn't support dropping files from desktop return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && (Env.browser !== 'IE' || Env.version > 9); }()), filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10); }()), return_response_headers: True, return_response_type: function(responseType) { if (responseType === 'json' && !!window.JSON) { // we can fake this one even if it's not supported return true; } return Env.can('return_response_type', responseType); }, return_status_code: True, report_upload_progress: Test(window.XMLHttpRequest && new XMLHttpRequest().upload), resize_image: function() { return I.can('access_binary') && Env.can('create_canvas'); }, select_file: function() { return Env.can('use_fileinput') && window.File; }, select_folder: function() { return I.can('select_file') && Env.browser === 'Chrome' && Env.version >= 21; }, select_multiple: function() { // it is buggy on Safari Windows and iOS return I.can('select_file') && !(Env.browser === 'Safari' && Env.os === 'Windows') && !(Env.os === 'iOS' && Env.verComp(Env.osVersion, "7.0.4", '<')); }, send_binary_string: Test(window.XMLHttpRequest && (new XMLHttpRequest().sendAsBinary || (window.Uint8Array && window.ArrayBuffer))), send_custom_headers: Test(window.XMLHttpRequest), send_multipart: function() { return !!(window.XMLHttpRequest && new XMLHttpRequest().upload && window.FormData) || I.can('send_binary_string'); }, slice_blob: Test(window.File && (File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice)), stream_upload: function(){ return I.can('slice_blob') && I.can('send_multipart'); }, summon_file_dialog: Test(function() { // yeah... some dirty sniffing here... return (Env.browser === 'Firefox' && Env.version >= 4) || (Env.browser === 'Opera' && Env.version >= 12) || (Env.browser === 'IE' && Env.version >= 10) || !!~Basic.inArray(Env.browser, ['Chrome', 'Safari']); }()), upload_filesize: True }, arguments[2] ); Runtime.call(this, options, (arguments[1] || type), caps); Basic.extend(this, { init : function() { this.trigger("Init"); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); destroy = I = null; }; }(this.destroy)) }); Basic.extend(this.getShim(), extensions); } Runtime.addConstructor(type, Html5Runtime); return extensions; }); // Included from: src/javascript/runtime/html5/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/file/FileReader @private */ define("moxie/runtime/html5/file/FileReader", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Encode", "moxie/core/utils/Basic" ], function(extensions, Encode, Basic) { function FileReader() { var _fr, _convertToBinary = false; Basic.extend(this, { read: function(op, blob) { var target = this; _fr = new window.FileReader(); _fr.addEventListener('progress', function(e) { target.trigger(e); }); _fr.addEventListener('load', function(e) { target.trigger(e); }); _fr.addEventListener('error', function(e) { target.trigger(e, _fr.error); }); _fr.addEventListener('loadend', function() { _fr = null; }); if (Basic.typeOf(_fr[op]) === 'function') { _convertToBinary = false; _fr[op](blob.getSource()); } else if (op === 'readAsBinaryString') { // readAsBinaryString is depricated in general and never existed in IE10+ _convertToBinary = true; _fr.readAsDataURL(blob.getSource()); } }, getResult: function() { return _fr && _fr.result ? (_convertToBinary ? _toBinary(_fr.result) : _fr.result) : null; }, abort: function() { if (_fr) { _fr.abort(); } }, destroy: function() { _fr = null; } }); function _toBinary(str) { return Encode.atob(str.substring(str.indexOf('base64,') + 7)); } } return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/html4/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/file/FileReader @private */ define("moxie/runtime/html4/file/FileReader", [ "moxie/runtime/html4/Runtime", "moxie/runtime/html5/file/FileReader" ], function(extensions, FileReader) { return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/html4/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/xhr/XMLHttpRequest @private */ define("moxie/runtime/html4/xhr/XMLHttpRequest", [ "moxie/runtime/html4/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Url", "moxie/core/Exceptions", "moxie/core/utils/Events", "moxie/file/Blob", "moxie/xhr/FormData" ], function(extensions, Basic, Dom, Url, x, Events, Blob, FormData) { function XMLHttpRequest() { var _status, _response, _iframe; function cleanup(cb) { var target = this, uid, form, inputs, i, hasFile = false; if (!_iframe) { return; } uid = _iframe.id.replace(/_iframe$/, ''); form = Dom.get(uid + '_form'); if (form) { inputs = form.getElementsByTagName('input'); i = inputs.length; while (i--) { switch (inputs[i].getAttribute('type')) { case 'hidden': inputs[i].parentNode.removeChild(inputs[i]); break; case 'file': hasFile = true; // flag the case for later break; } } inputs = []; if (!hasFile) { // we need to keep the form for sake of possible retries form.parentNode.removeChild(form); } form = null; } // without timeout, request is marked as canceled (in console) setTimeout(function() { Events.removeEvent(_iframe, 'load', target.uid); if (_iframe.parentNode) { // #382 _iframe.parentNode.removeChild(_iframe); } // check if shim container has any other children, if - not, remove it as well var shimContainer = target.getRuntime().getShimContainer(); if (!shimContainer.children.length) { shimContainer.parentNode.removeChild(shimContainer); } shimContainer = _iframe = null; cb(); }, 1); } Basic.extend(this, { send: function(meta, data) { var target = this, I = target.getRuntime(), uid, form, input, blob; _status = _response = null; function createIframe() { var container = I.getShimContainer() || document.body , temp = document.createElement('div') ; // IE 6 won't be able to set the name using setAttribute or iframe.name temp.innerHTML = '<iframe id="' + uid + '_iframe" name="' + uid + '_iframe" src="javascript:&quot;&quot;" style="display:none"></iframe>'; _iframe = temp.firstChild; container.appendChild(_iframe); /* _iframe.onreadystatechange = function() { console.info(_iframe.readyState); };*/ Events.addEvent(_iframe, 'load', function() { // _iframe.onload doesn't work in IE lte 8 var el; try { el = _iframe.contentWindow.document || _iframe.contentDocument || window.frames[_iframe.id].document; // try to detect some standard error pages if (/^4(0[0-9]|1[0-7]|2[2346])\s/.test(el.title)) { // test if title starts with 4xx HTTP error _status = el.title.replace(/^(\d+).*$/, '$1'); } else { _status = 200; // get result _response = Basic.trim(el.body.innerHTML); // we need to fire these at least once target.trigger({ type: 'progress', loaded: _response.length, total: _response.length }); if (blob) { // if we were uploading a file target.trigger({ type: 'uploadprogress', loaded: blob.size || 1025, total: blob.size || 1025 }); } } } catch (ex) { if (Url.hasSameOrigin(meta.url)) { // if response is sent with error code, iframe in IE gets redirected to res://ieframe.dll/http_x.htm // which obviously results to cross domain error (wtf?) _status = 404; } else { cleanup.call(target, function() { target.trigger('error'); }); return; } } cleanup.call(target, function() { target.trigger('load'); }); }, target.uid); } // end createIframe // prepare data to be sent and convert if required if (data instanceof FormData && data.hasBlob()) { blob = data.getBlob(); uid = blob.uid; input = Dom.get(uid); form = Dom.get(uid + '_form'); if (!form) { throw new x.DOMException(x.DOMException.NOT_FOUND_ERR); } } else { uid = Basic.guid('uid_'); form = document.createElement('form'); form.setAttribute('id', uid + '_form'); form.setAttribute('method', meta.method); form.setAttribute('enctype', 'multipart/form-data'); form.setAttribute('encoding', 'multipart/form-data'); form.setAttribute('target', uid + '_iframe'); I.getShimContainer().appendChild(form); } if (data instanceof FormData) { data.each(function(value, name) { if (value instanceof Blob) { if (input) { input.setAttribute('name', name); } } else { var hidden = document.createElement('input'); Basic.extend(hidden, { type : 'hidden', name : name, value : value }); // make sure that input[type="file"], if it's there, comes last if (input) { form.insertBefore(hidden, input); } else { form.appendChild(hidden); } } }); } // set destination url form.setAttribute("action", meta.url); createIframe(); form.submit(); target.trigger('loadstart'); }, getStatus: function() { return _status; }, getResponse: function(responseType) { if ('json' === responseType) { // strip off <pre>..</pre> tags that might be enclosing the response if (Basic.typeOf(_response) === 'string' && !!window.JSON) { try { return JSON.parse(_response.replace(/^\s*<pre[^>]*>/, '').replace(/<\/pre>\s*$/, '')); } catch (ex) { return null; } } } else if ('document' === responseType) { } return _response; }, abort: function() { var target = this; if (_iframe && _iframe.contentWindow) { if (_iframe.contentWindow.stop) { // FireFox/Safari/Chrome _iframe.contentWindow.stop(); } else if (_iframe.contentWindow.document.execCommand) { // IE _iframe.contentWindow.document.execCommand('Stop'); } else { _iframe.src = "about:blank"; } } cleanup.call(this, function() { // target.dispatchEvent('readystatechange'); target.dispatchEvent('abort'); }); } }); } return (extensions.XMLHttpRequest = XMLHttpRequest); }); // Included from: src/javascript/runtime/silverlight/Runtime.js /** * RunTime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global ActiveXObject:true */ /** Defines constructor for Silverlight runtime. @class moxie/runtime/silverlight/Runtime @private */ define("moxie/runtime/silverlight/Runtime", [ "moxie/core/utils/Basic", "moxie/core/utils/Env", "moxie/core/utils/Dom", "moxie/core/Exceptions", "moxie/runtime/Runtime" ], function(Basic, Env, Dom, x, Runtime) { var type = "silverlight", extensions = {}; function isInstalled(version) { var isVersionSupported = false, control = null, actualVer, actualVerArray, reqVerArray, requiredVersionPart, actualVersionPart, index = 0; try { try { control = new ActiveXObject('AgControl.AgControl'); if (control.IsVersionSupported(version)) { isVersionSupported = true; } control = null; } catch (e) { var plugin = navigator.plugins["Silverlight Plug-In"]; if (plugin) { actualVer = plugin.description; if (actualVer === "1.0.30226.2") { actualVer = "2.0.30226.2"; } actualVerArray = actualVer.split("."); while (actualVerArray.length > 3) { actualVerArray.pop(); } while ( actualVerArray.length < 4) { actualVerArray.push(0); } reqVerArray = version.split("."); while (reqVerArray.length > 4) { reqVerArray.pop(); } do { requiredVersionPart = parseInt(reqVerArray[index], 10); actualVersionPart = parseInt(actualVerArray[index], 10); index++; } while (index < reqVerArray.length && requiredVersionPart === actualVersionPart); if (requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart)) { isVersionSupported = true; } } } } catch (e2) { isVersionSupported = false; } return isVersionSupported; } /** Constructor for the Silverlight Runtime @class SilverlightRuntime @extends Runtime */ function SilverlightRuntime(options) { var I = this, initTimer; options = Basic.extend({ xap_url: Env.xap_url }, options); Runtime.call(this, options, type, { access_binary: Runtime.capTrue, access_image_binary: Runtime.capTrue, display_media: Runtime.capTrue, do_cors: Runtime.capTrue, drag_and_drop: false, report_upload_progress: Runtime.capTrue, resize_image: Runtime.capTrue, return_response_headers: function(value) { return value && I.mode === 'client'; }, return_response_type: function(responseType) { if (responseType !== 'json') { return true; } else { return !!window.JSON; } }, return_status_code: function(code) { return I.mode === 'client' || !Basic.arrayDiff(code, [200, 404]); }, select_file: Runtime.capTrue, select_multiple: Runtime.capTrue, send_binary_string: Runtime.capTrue, send_browser_cookies: function(value) { return value && I.mode === 'browser'; }, send_custom_headers: function(value) { return value && I.mode === 'client'; }, send_multipart: Runtime.capTrue, slice_blob: Runtime.capTrue, stream_upload: true, summon_file_dialog: false, upload_filesize: Runtime.capTrue, use_http_method: function(methods) { return I.mode === 'client' || !Basic.arrayDiff(methods, ['GET', 'POST']); } }, { // capabilities that require specific mode return_response_headers: function(value) { return value ? 'client' : 'browser'; }, return_status_code: function(code) { return Basic.arrayDiff(code, [200, 404]) ? 'client' : ['client', 'browser']; }, send_browser_cookies: function(value) { return value ? 'browser' : 'client'; }, send_custom_headers: function(value) { return value ? 'client' : 'browser'; }, use_http_method: function(methods) { return Basic.arrayDiff(methods, ['GET', 'POST']) ? 'client' : ['client', 'browser']; } }); // minimal requirement if (!isInstalled('2.0.31005.0') || Env.browser === 'Opera') { this.mode = false; } Basic.extend(this, { getShim: function() { return Dom.get(this.uid).content.Moxie; }, shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return I.getShim().exec(this.uid, component, action, args); }, init : function() { var container; container = this.getShimContainer(); container.innerHTML = '<object id="' + this.uid + '" data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%" style="outline:none;">' + '<param name="source" value="' + options.xap_url + '"/>' + '<param name="background" value="Transparent"/>' + '<param name="windowless" value="true"/>' + '<param name="enablehtmlaccess" value="true"/>' + '<param name="initParams" value="uid=' + this.uid + ',target=' + Env.global_event_dispatcher + '"/>' + '</object>'; // Init is dispatched by the shim initTimer = setTimeout(function() { if (I && !I.initialized) { // runtime might be already destroyed by this moment I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); } }, Env.OS !== 'Windows'? 10000 : 5000); // give it more time to initialize in non Windows OS (like Mac) }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); clearTimeout(initTimer); // initialization check might be still onwait options = initTimer = destroy = I = null; }; }(this.destroy)) }, extensions); } Runtime.addConstructor(type, SilverlightRuntime); return extensions; }); // Included from: src/javascript/runtime/silverlight/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/Blob @private */ define("moxie/runtime/silverlight/file/Blob", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/file/Blob" ], function(extensions, Basic, Blob) { return (extensions.Blob = Basic.extend({}, Blob)); }); // Included from: src/javascript/runtime/silverlight/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileInput @private */ define("moxie/runtime/silverlight/file/FileInput", [ "moxie/runtime/silverlight/Runtime" ], function(extensions) { var FileInput = { init: function(options) { function toFilters(accept) { var filter = ''; for (var i = 0; i < accept.length; i++) { filter += (filter !== '' ? '|' : '') + accept[i].title + " | *." + accept[i].extensions.replace(/,/g, ';*.'); } return filter; } this.getRuntime().shimExec.call(this, 'FileInput', 'init', toFilters(options.accept), options.name, options.multiple); this.trigger('ready'); } }; return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/silverlight/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileReader @private */ define("moxie/runtime/silverlight/file/FileReader", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/file/FileReader" ], function(extensions, Basic, FileReader) { return (extensions.FileReader = Basic.extend({}, FileReader)); }); // Included from: src/javascript/runtime/silverlight/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileReaderSync @private */ define("moxie/runtime/silverlight/file/FileReaderSync", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/file/FileReaderSync" ], function(extensions, Basic, FileReaderSync) { return (extensions.FileReaderSync = Basic.extend({}, FileReaderSync)); }); // Included from: src/javascript/runtime/silverlight/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/xhr/XMLHttpRequest @private */ define("moxie/runtime/silverlight/xhr/XMLHttpRequest", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/xhr/XMLHttpRequest" ], function(extensions, Basic, XMLHttpRequest) { return (extensions.XMLHttpRequest = Basic.extend({}, XMLHttpRequest)); }); expose(["moxie/core/utils/Basic","moxie/core/I18n","moxie/core/utils/Mime","moxie/core/utils/Env","moxie/core/utils/Dom","moxie/core/Exceptions","moxie/core/EventTarget","moxie/core/utils/Encode","moxie/runtime/Runtime","moxie/runtime/RuntimeClient","moxie/file/Blob","moxie/file/File","moxie/file/FileInput","moxie/runtime/RuntimeTarget","moxie/file/FileReader","moxie/core/utils/Url","moxie/file/FileReaderSync","moxie/xhr/FormData","moxie/xhr/XMLHttpRequest","moxie/runtime/Transporter","moxie/core/utils/Events"]); })(this);/** * o.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global moxie:true */ /** Globally exposed namespace with the most frequently used public classes and handy methods. @class o @static @private */ (function(exports) { "use strict"; var o = {}, inArray = exports.moxie.core.utils.Basic.inArray; // directly add some public classes // (we do it dynamically here, since for custom builds we cannot know beforehand what modules were included) (function addAlias(ns) { var name, itemType; for (name in ns) { itemType = typeof(ns[name]); if (itemType === 'object' && !~inArray(name, ['Exceptions', 'Env', 'Mime'])) { addAlias(ns[name]); } else if (itemType === 'function') { o[name] = ns[name]; } } })(exports.moxie); // add some manually o.Env = exports.moxie.core.utils.Env; o.Mime = exports.moxie.core.utils.Mime; o.Exceptions = exports.moxie.core.Exceptions; // expose globally exports.mOxie = o; if (!exports.o) { exports.o = o; } return o; })(this);
files/rxjs/2.3.7/rx.lite.extras.js
photonstorm/jsdelivr
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (factory) { 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; } // Because of build optimizers if (typeof define === 'function' && define.amd) { define(['rx', 'exports'], function (Rx, exports) { root.Rx = factory(root, exports, Rx); return root.Rx; }); } else if (typeof module === 'object' && module && module.exports === freeExports) { module.exports = factory(root, module.exports, require('./rx')); } else { root.Rx = factory(root, {}, root.Rx); } }.call(this, function (root, exp, Rx, undefined) { // References var Observable = Rx.Observable, observableProto = Observable.prototype, observableNever = Observable.never, observableThrow = Observable.throwException, AnonymousObservable = Rx.AnonymousObservable, Observer = Rx.Observer, Subject = Rx.Subject, internals = Rx.internals, helpers = Rx.helpers, ScheduledObserver = internals.ScheduledObserver, SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, CompositeDisposable = Rx.CompositeDisposable, RefCountDisposable = Rx.RefCountDisposable, disposableEmpty = Rx.Disposable.empty, immediateScheduler = Rx.Scheduler.immediate, defaultKeySerializer = helpers.defaultKeySerializer, addRef = Rx.internals.addRef, identity = helpers.identity, isPromise = helpers.isPromise, inherits = internals.inherits, noop = helpers.noop, isScheduler = helpers.isScheduler, observableFromPromise = Observable.fromPromise, slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var argumentOutOfRange = 'Argument out of range'; 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 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)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); /** * 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; }); }; /** * 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(); } }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); if (resource) { disposable = resource; } source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { self(); })); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * 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; }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * 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(); }); }); }; /** * 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)); }); }; return Rx; }));