code
stringlengths 2
1.05M
|
---|
function extend(child, super)
{
for (var property in super.prototype) {
if (typeof child.prototype[property] == "undefined")
child.prototype[property] = new super.prototype[property];
}
return child;
};
|
'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 _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _IconBase = require('./../components/IconBase/IconBase');
var _IconBase2 = _interopRequireDefault(_IconBase);
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 Easel = function (_React$Component) {
_inherits(Easel, _React$Component);
function Easel() {
_classCallCheck(this, Easel);
return _possibleConstructorReturn(this, Object.getPrototypeOf(Easel).apply(this, arguments));
}
_createClass(Easel, [{
key: 'render',
value: function render() {
if (this.props.bare) {
return _react2.default.createElement(
'g',
null,
_react2.default.createElement(
'g',
null,
_react2.default.createElement('rect', { x: '80', y: '144', width: '352', height: '192' }),
_react2.default.createElement('path', { d: 'M464,96H48c-8.837,0-16,7.163-16,16v256c0,8.837,6.932,16,15.768,16H464c8.837,0,16-7.163,16-16V112 C480,103.163,472.837,96,464,96z M448,352H64V128h384V352z' }),
_react2.default.createElement('polygon', { points: '80,480 112,480 140.147,400 108.835,400 \t' }),
_react2.default.createElement('polygon', { points: '270.83,32 241.472,32 224.171,80 288.099,80 \t' }),
_react2.default.createElement('polygon', { points: '371.853,400 400,480 432,480 403.22,400 \t' }),
_react2.default.createElement('rect', { x: '240', y: '400', width: '32', height: '48' })
)
);
}return _react2.default.createElement(
_IconBase2.default,
null,
_react2.default.createElement(
'g',
null,
_react2.default.createElement('rect', { x: '80', y: '144', width: '352', height: '192' }),
_react2.default.createElement('path', { d: 'M464,96H48c-8.837,0-16,7.163-16,16v256c0,8.837,6.932,16,15.768,16H464c8.837,0,16-7.163,16-16V112 C480,103.163,472.837,96,464,96z M448,352H64V128h384V352z' }),
_react2.default.createElement('polygon', { points: '80,480 112,480 140.147,400 108.835,400 \t' }),
_react2.default.createElement('polygon', { points: '270.83,32 241.472,32 224.171,80 288.099,80 \t' }),
_react2.default.createElement('polygon', { points: '371.853,400 400,480 432,480 403.22,400 \t' }),
_react2.default.createElement('rect', { x: '240', y: '400', width: '32', height: '48' })
)
);
}
}]);
return Easel;
}(_react2.default.Component);
exports.default = Easel;
;Easel.defaultProps = { bare: false }; |
// server injected code
/* Debug info: {"server":"WEB519","utc_time":"2016-04-04T20:05:03.641Z","src_ip":"192.204.11.162","method":"HTTPS","api_key":"2_fq_ZOJSR4xNZtv2rA8DALl1Gxp7yTYMb3UdER6zerupB55mwkzh9pVBz4Blzi8SW","site_found":true} */
if (typeof gigya == 'undefined' || !gigya.isGigya) { gigya = { isGigya: true } };
if (!gigya.__initialized) {
gigya.__initialized = true;
gigya.env='prod';
gigya.gaeDomain='chat.gigya.com';
gigya.build={version:'6.2',time:'Mon 04/04/2016 16:16:02.34'};
if (typeof gigya.partnerSettings == 'undefined') {
gigya.partnerSettings={"authMode":"cookie","baseDomains":"agea.com.ar,clarin.com","ssoLogoutUrl":"http://clarin.com/login/logout","ssoKey":"3_IcGpUrIh3Kn0Wf3moX4YjqY4Km6evWEY0dqTU3Yh46OS622zpJQeo5-28q6_L-94"};
gigya.partnerSettings.plugins={"apiDomain":"US1.gigya.com"};
}
gigya.providersConfig = {"facebook":{"appID":"344479319002359","version":"v2.0"},"googlePlus":{"clientId":"8386975267.apps.googleusercontent.com","scopes":"https://www.googleapis.com/auth/plus.login email"}};
gigya.abTesting = null;
gigya.samlConfig = null;
//end server injected code
// API adapters
var gigya;
(function(b){(function(e){(function(e){(function(d){(function(d){function h(a,g){g=b.utils.object.clone(g);if(b.partnerSettings.ssoKey){g||(g={});var d=g.callback;g.callback=function(f){e.parentNode.removeChild(e);b.log.addLog("SSO: About to invoke callback for "+a+" with this response",f);d&&d(f)};g.m=a;g.d=f;g.lid=b.utils.xd._flashListenerID;b.thisScript.globalConf.legacyCrossSiteMethod&&"localstorage"!=b.thisScript.globalConf.legacyCrossSiteMethod.toLowerCase()&&(g.lid=b.thisScript.globalConf.legacyCrossSiteMethod+":"+
b.utils.xd._flashListenerID);g.callbackID="gig_sso_cb"+(new Date).getTime()+"_"+m++;b.utils.xd.addMessageListener(g.callbackID,{},!1,g.callback);delete g.callback;g.sAPIKey=b.thisScript.APIKey;var h=b.utils.keyValue.serialize(g),e=c(g.callbackID),k=function(){e.src="https://cdns.gigya.com/gs/sso.htm?APIKey="+b.partnerSettings.ssoKey+"&version=1#"+h;b.utils.DOM.removeEventListener(e,"load",k)};b.utils.DOM.addEventListener(e,"load",k);b.log.addLog("SSO: Calling "+a,{SSOKey:b.partnerSettings.ssoKey,
params:g});document.body?b.utils.DOM.appendToBody(e):b.utils.functions.invokeOnPageLoad(function(){return b.utils.DOM.appendToBody(e)})}else g&&g.callback&&g.callback()}function c(a){var f=document.getElementById("gig_sso"),f=document.createElement("iframe");b.localInfo.isIOS||b.localInfo.isIOSChrome||b.localInfo.isAndroid?(f.style.width="0px",f.style.height="0px",f.style.display="none"):(f.style.width="30px",f.style.height="10px",f.style.position="absolute",f.style.top="-1000px",f.style.left="-1000px");
f.id="gig_sso_"+a;return f}function a(a){h("setToken",a)}var f=document.location.protocol+"//"+document.location.href.split("?")[0].split("#")[0].split("/")[2],m=0;d.getGroupToken=function(a){h("getToken",a)};d.setGroupTokenFromResponse=function(b,f,m){b.sessionInfo&&(b=b.sessionInfo);var c=b.expires_in,c=null==c||""===c||isNaN(c)?47304E7:0==c?null:1E3*c,d=new Date;d.setTime(d.getTime()+c);a({lt:b.login_token,expiration:null==c?0:d.getTime(),legacyCrossSiteMethod:m,callback:f})};d.setGroupToken=a;
d.logout=function(a){h("logout",a)};d.removeGroupToken=function(a){h("removeToken",a)}})(d.sso||(d.sso={}))})(e.web||(e.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
(function(b){(function(e){(function(e){(function(d){var e=function(){function h(b,a,f,m,d,g){void 0===g&&(g={});this.id=b;this.baseUrl=a;this.methodName=f;this.params=m;this.callback=d;this.settings=g}h.prototype.getUrl=function(){return this.baseUrl+"/"+this.methodName};h.prototype.send=function(b){};h.prototype.getAuthParams=function(){var c={};if(this.params.oauth_token)this.params.authMode="token";else if(!this.params.noAuth){var a=d.tokenStore.get(this.params.APIKey);if(a){this.sentLoginToken=
a;var f=b.utils.cookie.get("gltexp_"+this.params.APIKey);null!=f&&(c.loginTokenExp=f);c.login_token=a}c.authMode="cookie"}delete this.params.noAuth;b.localInfo.isAndroidBrowser&&(delete this.params.login_token,delete this.params.loginTokenExp,delete this.params.authMode);return c};return h}();d.BaseRequest=e})(e.web||(e.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
var __extends=this&&this.__extends||function(b,e){function k(){this.constructor=b}for(var d in e)e.hasOwnProperty(d)&&(b[d]=e[d]);k.prototype=e.prototype;b.prototype=new k};
(function(b){(function(e){(function(e){(function(d){d.callback=function(b,c){!c&&b&&(c=b.context);if(c){var a=d.pendingRequests[c];a&&a.handleResponse(b)}};var e=function(e){function c(){e.apply(this,arguments);this.ifrName="gigyaPostIframe_"+(new Date).getTime();this.retry=0}__extends(c,e);c.prototype.addDefaultParams=function(){this.params.format="jsonp";this.params.callback=c.callbackName;this.params.context=this.id;var a=this.getAuthParams();this.paramsLoginToken=this.params.login_token;b.utils.object.add(this.params,
a,!0);this.sentLoginToken=this.params.login_token};c.prototype.getCacheKey=function(){return this.methodName+"_"+b.utils.keyValue.serialize(this.params)};c.prototype.send=function(a){var f=this;if(!this.inProgress){d.pendingRequests[this.id]=this;this.inProgress=!0;this.params.sdk="js_"+b.build.version;this.addDefaultParams();var c=b.utils.keyValue.serialize(this.params);if(!a&&this.settings.cacheTimeout)c=this.getCacheKey(),b.utils.sessionCache.get(c,this.settings.cacheTimeout,function(a){a?(delete f.settings.cacheTimeout,
d.callback(a,f.id)):(f.inProgress=!1,f.send(!0))});else{a=0;b.localInfo.isIE&&(a=2048);var l=this.getUrl();b.events.global.dispatch({eventName:"jsonp-beforeRequest",url:l,params:this.params,level:9});4096>=l.length+1+c.length+a&&!this.settings.forcePost?b.utils.script.load(l+"?"+c,function(){d.callback({context:f.id,errorCode:500026,errorMessage:"Network_error"})}):b.utils.functions.invokeOnPageLoad(function(){var a=document.getElementById("gigyaRequestForms");null==a&&(a=document.createElement("span"),
a.id="gigyaRequestForms",a.style.display="none",b.utils.DOM.appendToBody(a));var c=f.getPostContainer();a.appendChild(c)})}}};c.prototype.createParamFormElements=function(){var a=[],f="";for(f in this.params)a=a.concat(['<textarea name="',f,'">']),"object"==typeof this.params[f]?a.push(b.utils.URL.URLEncode(b.utils.JSON.serialize(this.params[f]))):a.push(this.params[f]),a.push("</textarea>");return a.join("")};c.prototype.getPostContainer=function(){var a=this;if(!this.postContainer){var f=document.createElement("span"),
c=this.ifrName+"form",d=this.id;f.innerHTML=['<form accept-charset="UTF-8" id="',c,'" method="post" action="',this.getUrl(),"?context="+this.id+"&saveResponseID="+this.id+'" target="',this.ifrName,'">',this.createParamFormElements(),'<input name="utf8" type="hidden" value="✓" /><input type="submit" value="" /></form>'].join("");var g,e=b.utils.DOM.createElement("iframe",this.ifrName);e.setAttribute("id",this.ifrName);b.utils.DOM.addEventListener(e,"load",function(){g?a.getSavedFormResponse(d):
(window.setTimeout(function(){var a=document.getElementById(c);a&&a.submit()},10),g=!0)});f.appendChild(e);this.postContainer=f}return f};c.prototype.getSavedFormResponse=function(a){var b=this;(new c(a,this.baseUrl,"socialize.getSavedResponse",{APIKey:this.params.APIKey,saveResponseID:this.id,ucid:this.params.ucid,noAuth:!0},function(a){b.handleResponse(a)})).send()};c.prototype.getDataPendingTimeout=function(a){return 4>=a?500:8>=a?1E3:21>=a?2E3:39>=a?5E3:-1};c.prototype.handleResponse=function(a){var f=
this;this.settings.cacheTimeout&&b.utils.sessionCache.set(this.getCacheKey(),0==a.errorCode?a:null);null!=this.retryTimerID&&window.clearTimeout(this.retryTimerID);this.loaded=!0;this.inProgress=!1;100001==a.errorCode?(a=this.getDataPendingTimeout(this.retry++),0<a&&window.setTimeout(function(){f.send()},a)):(this.dispose(),this.callback(a))};c.prototype.dispose=function(){delete d.pendingRequests[this.id];this.postContainer&&b.utils.DOM.removeElement(this.postContainer);delete this.postContainer};
c.callbackName="gigya._.apiAdapters.web.callback";return c}(d.BaseRequest);d.JsonpRequest=e})(e.web||(e.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
(function(b){(function(e){(function(k){(function(d){var k=function(h){function c(a,b,c,d,g,e){void 0===e&&(e={});h.call(this,a,b,c,d,g,e);this.windowName=this.methodName.replace(/\./g,"_").replace(/\//g,"")+"_"+(new Date).getTime();this.requestID=this.windowName+(new Date).getTime()}__extends(c,h);c.prototype.beforeRequest=function(){};c.prototype.afterResponse=function(a){a.dontClose&&"false"!=a.dontClose||b.utils.win.close(this.windowName);this.callback(a)};c.prototype.getAuthFlow=function(){return this.params.authFlow?
this.params.authFlow:"popup"};c.prototype.getStateString=function(){var a=b.utils.xd._flashListenerID;if(b.thisScript.globalConf.legacyCrossSiteMethod&&"localstorage"!=b.thisScript.globalConf.legacyCrossSiteMethod.toLowerCase()||b.localInfo.isIE&&window.navigator.msDoNotTrack)a=b.thisScript.globalConf.legacyCrossSiteMethod+":"+b.utils.xd._flashListenerID;var f=this.getAuthFlow(),a={domain:document.location.href.split("?")[0].split("#")[0],id:this.requestID,lid:a,messaging:b.localInfo.messagingMethod};
b.localInfo.isIE11&&window.indexedDB&&(a.messaging=e.MessagingMethod.LocalStorageListener);if("redirect"==f||b.localInfo.isWindowsPhone)a.sourceURL=window.top.document.location.href,this.params.redirectURL?(a.redirectURL=b.utils.URL.addParamsToURL(this.params.redirectURL,{gig_events:b.events.global.getEventsForOperation(this.methodName)}),a.addUserInfo=!0,this.params.redirectMethod&&(a.redirectMethod=this.params.redirectMethod)):a.sourceURL=b.utils.URL.addParamsToURL(a.sourceURL,{gig_events:b.events.global.getEventsForOperation(this.methodName)});
this.params.provider&&"facebook"==this.params.provider.toLowerCase()&&(a.invite=this.params.invite);(f=b.external.backplane.getChannelId())&&(a.bp_channel_url=f);return b.utils.keyValue.serialize(a)};c.prototype.getServerParamsString=function(){var a={},f;for(f in this.params)0!=f.indexOf("x_")&&null!=this.params[f]&&(a["x_"+f]=this.params[f],delete a[f]);a.x_APIKey&&(a.client_id=a.x_APIKey,delete a.x_APIKey);a.x_oauth_token&&(a.oauth_token=a.x_oauth_token,delete a.x_oauth_token);a.redirect_uri="/GS/AfterLogin.aspx";
a.response_type=this.params.authCodeOnly?"code":"server_token";a.format="jsonp";a.x_sdk="js_"+b.build.version;(f=b.utils.cookie.get("_gigRefUid_"+this.params.APIKey))&&(a.x_refUID=f);(f=b.utils.cookie.get("_gigRefUid_"+this.params.APIKey))&&(a.x_refUID=f);a.state=this.getStateString();b.utils.object.add(a,this.getAuthParams());d.useAPIProxy&&d.gmidTicket&&(a.gmidTicket=d.gmidTicket);delete a.redirectURL;this.sentLoginToken=a.login_token;return b.utils.keyValue.serialize(a)};c.prototype.send=function(){var a=
this;this.beforeRequest();var f=this.getServerParamsString(),c;this.params.provider&&(c=b.socialize._getProviderByName(this.params.provider.toLowerCase()));var d=null;null!=c&&(d=(this.params.enablePopupLocation?"location=1,toolbar=1":"toolbar=0,")+"menubar=0,resizable=1,scrollbars=1,width="+c.width+",height="+c.height);var g=this.methodName.split(".");b.reports.report(this.params.originalMethodName||g[g.length-1],this.params.APIKey,this.params.cid,this.params.source,this.params.sourceData,{sn:c?
c.toString():null});f=this.getUrl()+"?"+f;"redirect"==this.getAuthFlow()?window.top.document.location.href=f:(b.utils.xd.addMessageListener(this.requestID,this.params,!0,function(b){a.afterResponse(b)}),b.utils.win.open(f,this.windowName,d))};return c}(d.BaseRequest);d.OauthRequest=k})(k.web||(k.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
(function(b){(function(e){(function(e){(function(d){var e=function(e){function c(){e.apply(this,arguments)}__extends(c,e);c.prototype.send=function(a){var f=this;if(d.proxyState.ready){var c=function(a){(a=b.utils.JSON.deserialize(a.data))&&a.id==f.id&&(b.utils.DOM.removeEventListener(window,"message",c),f.callback(a.response))};b.utils.DOM.addEventListener(window,"message",c);b.utils.object.add(this.params,this.getAuthParams());d.ifrAPIProxy.contentWindow.postMessage(this.json(),"https://cdns.gigya.com")}else d.proxyState.error&&
this.callback({context:this.id,errorCode:500026,errorMessage:"APIProxy error: "+d.proxyState.error})};c.prototype.json=function(){return b.utils.JSON.serialize({id:this.id,methodName:this.methodName,params:this.params,settings:this.settings})};return c}(d.BaseRequest);d.APIProxyRequest=e})(e.web||(e.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
(function(b){(function(e){(function(k){(function(d){(function(k){function h(a){void 0===a&&(a=b.thisScript.APIKey);return a?"glt_"+a:"_gig_lt"}var c={};k.activeNamespaces={};k.get=function(a){void 0===a&&(a=b.thisScript.APIKey);return(a=b.utils.cookie.get(h(a)))?a.split("|")[0]:null};k.set=function(a,f,c,d){b.utils.localStorage.removeItem("gigyaSettings");a||(a=b.thisScript.APIKey);a?(b.utils.cookie.set("glt_"+a,f,c),b.utils.cookie.remove("gac_"+a)):b.utils.cookie.set("_gig_lt",f,c)};k.setFromGAC=
function(a,f){if(b.thisScript.APIKey){var d=b.utils.cookie.get("gac_"+b.thisScript.APIKey);d&&!a.neverTryGAC?('"'==d.charAt(0)&&'"'==d.charAt(d.length-1)&&(d=d.substring(1,d.length-1)),c[d]?f():(c[d]=!0,b.socialize.updateRefUID(),b.socialize.notifyLogin({ignoreApiQueue:!0,neverTryGAC:!0,authCode:d,APIKey:b.thisScript.APIKey,client_id:b.thisScript.APIKey},{callback:function(){b.utils.cookie.remove("gac_"+b.thisScript.APIKey);f();b.socialize.refreshUI({neverTryGAC:!0})}}))):f()}else f()};k.setFromSsoResponse=
function(a,f){void 0===f&&(f=b.thisScript.APIKey);0==a.errorCode&&(k.set(f,a.login_token,a.expires_in),b.accounts.verifyLogin({include:"profile,data",extraProfileFields:"samlData",callback:function(a){b.events.global.dispatchWhenHandlerAdded({eventName:"socialize.login"},null,function(f,c){b.socialize.getUserInfo({signIDs:!0,extraFields:"samlData",callback:function(d){f||(f={});0==a.errorCode&&0==d.errorCode?(f=e.addUserInfoToEvent(d,{eventName:"login"},!0),b.external.backplane.executeOnInit(function(){b.external.backplane.getChannelId()&&
b.socialize.notifySSOLogin({bp_channel_url:b.external.backplane.getChannelId()})})):f.cancel=!0;c(f)}})});b.events.global.dispatchWhenHandlerAdded({eventName:"accounts.login"},null,function(f,c){f||(f={});0==a.errorCode?(f.eventName="accounts.login",b.utils.object.extractProperties(a,f,"signature|UIDSig|timestamp|UIDSignature|signatureTimestamp|UID|profile|data")):f.cancel=!0;c(f)})}}))};k.remove=function(a){void 0===a&&(a=b.thisScript.APIKey);d.sso.removeGroupToken();b.utils.cookie.remove("glt_"+
a);b.utils.cookie.remove("_gig_lt")};k.migrateExisting=function(){var a=b.utils.cookie.get("_gig_lt");a&&b.thisScript.APIKey&&!k.get(b.thisScript.APIKey)&&(b.utils.cookie.remove("_gig_lt"),k.set(b.thisScript.APIKey,a))};k.getTokenParam=function(a,f){var c=b.utils.cookie.get(h(a));if(c)return c=c.split("|"),1<c.length?b.utils.keyValue.deserialize(c[1])[f]:null}})(d.tokenStore||(d.tokenStore={}))})(k.web||(k.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
gigya.isGigya||(gigya.isGigya=!0);
(function(b){(function(e){(function(k){(function(d){d.newApiAdapter=function(b){return new h(b)};var k=function(){return function(){}}();d.APIProxyState=k;d.useAPIProxy;d.ifrAPIProxy;d.proxyState;d.gmidTicket;d.callbacks={};d.pendingRequests={};var h=function(){function c(a){this.name="Web"}c.prototype.init=function(a){var f=this;this.initAPIProxy(function(){b.utils.functions.createAlias("gigya.auth.loginToken.get",d.tokenStore.get);f.checkReturnFromURL();f.isSessionValid(void 0,function(b){b?a():
d.sso.getGroupToken({callback:function(b){b&&d.tokenStore.setFromSsoResponse(b);a()}})})})};c.prototype.initAPIProxy=function(a){d.ifrAPIProxy&&(b.utils.DOM.removeElement(d.ifrAPIProxy),d.ifrAPIProxy=null);this.isAPIProxyNeeded()?this.loadAPIProxy(a):this.isThirdPartyCookiesBlockCheckNeeded()?this.checkThirdPartyCookiesBlocked(a):(d.useAPIProxy=!1,a())};c.prototype.isAPIProxyNeeded=function(){d.useAPIProxy=!1;if(b.partnerSettings.ssoKey&&b.partnerSettings.customAPIDomainPrefix||"1"===b.utils.localStorage.getItem("_gig_APIProxy_enabled"))b.utils.localStorage.setItem("_gig_APIProxy_enabled",
"1"),d.useAPIProxy=!0;return d.useAPIProxy};c.prototype.isThirdPartyCookiesBlockCheckNeeded=function(){var a=b.thisScript.globalConf.bypassCookiePolicy||"whenBlockedByDefault";return("whenBlockedByDefault"==a&&b.localInfo.isSafari||"always"==a)&&!window._isAPIProxy&&b.localInfo.supportsPostMessage&&!b.partnerSettings.customAPIDomainPrefix};c.prototype.checkThirdPartyCookiesBlocked=function(a){var f=this,c=document.location.protocol+"//"+document.location.href.split("?")[0].split("#")[0].split("/")[2],
e=b.utils.DOM.createHiddenIframe(("https:"==document.location.protocol?"https://cdns.gigya.com":"http://cdn.gigya.com")+"/gs/3PCTest.html#domain="+encodeURIComponent(c)),g=function(c){(c=b.utils.keyValue.deserialize(c.data))&&"3pcTestResult"==c.id&&(b.utils.DOM.removeEventListener(window,"message",g),"true"==c.enabled?(d.useAPIProxy=!1,d.gmidTicket=null,a()):(b.utils.localStorage.setItem("_gig_APIProxy_enabled","1"),d.useAPIProxy=!0,f.loadAPIProxy(a)),e.parentElement.removeChild(e))};b.utils.DOM.addEventListener(window,
"message",g)};c.prototype.loadAPIProxy=function(a){var f=document.location.protocol+"//"+document.location.href.split("?")[0].split("#")[0].split("/")[2];d.gmidTicket=b.utils.localStorage.getItem("_gig_gmidt");var f="https://cdns.gigya.com/gs/APIProxy.html#apikey="+encodeURIComponent(b.thisScript.APIKey)+"&domain="+encodeURIComponent(f)+"&hasTicket="+(d.gmidTicket?"true":"false"),c=function(f){(f=b.utils.JSON.deserialize(f.data))&&f.apiKey==b.thisScript.APIKey&&(d.proxyState=f,d.proxyState.gmidTicket&&
(d.gmidTicket=d.proxyState.gmidTicket,b.utils.localStorage.setItem("_gig_gmidt",d.gmidTicket,86400)),b.utils.DOM.removeEventListener(window,"message",c),a())};b.utils.DOM.addEventListener(window,"message",c);d.ifrAPIProxy=b.utils.DOM.createHiddenIframe(f)};c.prototype.isSessionValid=function(a,b){void 0===a&&(a={});d.tokenStore.setFromGAC(a,function(){if(b){var c=null!=d.tokenStore.get(a.APIKey)||null!=a.oauth_token;b(c)}})};c.prototype.registerForNamespaceEvents=function(a){};c.prototype.onPluginEvent=
function(a){};c.prototype.onJSLog=function(a,b){};c.prototype.getGmidTicket=function(a){a&&a(d.useAPIProxy?d.gmidTicket:null)};c.prototype.sendRequest=function(a,b,c,l){var g=this;void 0===l&&(l={});this.beforeRequest(a,b,l);var h=this.getBaseUrl(a,b,l),k=this.getRequestId({baseUrl:h,methodName:a,params:b,settings:l});d.callbacks[k]=d.callbacks[k]||[];d.callbacks[k].push(c);if(!d.pendingRequests[k]){var n;c=function(a){g.afterResponse(n,a,function(a){g.dispatchCallbacks(k,a)})};n=d.useAPIProxy&&0!=
h.indexOf("http://")?new d.APIProxyRequest(k,h,a,b,c,l):new d.JsonpRequest(k,h,a,b,c,l);n.send();e.logoutMethods[a]&&e.logoutBehaviour.logoutBeforeServerResponse&&this.clearSession(b)}};c.prototype.clearSession=function(a,b){d.tokenStore.remove(a.APIKey);b&&b()};c.prototype.sendOauthRequest=function(a,b,c,e){var g=this;this.beforeRequest(a,b,e);var h=this.getBaseUrl(a,b,e),k=new d.OauthRequest("",h,a,b,function(a){g.afterResponse(k,a,function(a){c(a)})},e);k.send()};c.prototype.getBaseUrl=function(a,
f,c){a=a.split(".");a=b.partnerSettings.customAPIDomainPrefix?b.partnerSettings.customAPIDomainPrefix+"."+b.partnerSettings.baseDomain:b.utils.stringUtils.format("{0}.{1}",a[0],f.apiDomain?f.apiDomain:b.partnerSettings.plugins.apiDomain);return((d.tokenStore.get()||f.regToken||f.oauth_token)&&!f.noAuth||c.forceHttps||"https"==b.thisScript.protocol?"https://":"http://")+a};c.prototype.beforeRequest=function(a,f,c){void 0===c&&(c={});(c.clearSession||c.clearSessionCondition&&c.clearSessionCondition(f))&&
d.tokenStore.remove(f.APIKey);!b.utils.localStorage.getItem("_gig_3pc_enabled")&&b.thisScript.globalConf.enableSSOToken&&e.loginMethods[a]&&(f.includeSSOToken=!0)};c.prototype.afterResponse=function(a,b,c){var d=this;this.handleTokenResponse(a,b,function(){d.logoutSsoIfNeeded(a,b,function(){c(b)})})};c.prototype.onSDKEvent=function(a){};c.prototype.getTokenParam=function(a,b){return d.tokenStore.getTokenParam(a,b)};c.prototype.checkReturnFromURL=function(){var a=b.utils.URL.getParamsFromURL(document.location.href);
a.gig_events&&0==a.errorCode&&null!=d.tokenStore.get()&&d.sso.setGroupTokenFromResponse({errorCode:0,login_token:d.tokenStore.get(),expires_in:a.expires_in},function(){var c=a.gig_events.split(",");-1!=b.utils.array.indexOf(c,"accounts.login")?b.accounts.getAccountInfo({extraProfileFields:"samlData",include:"profile,data,userinfo",callback:function(a){var d={errorCode:0,eventName:"accounts.login"};b.utils.object.extractProperties(a,d,"signature|UIDSig|timestamp|UIDSignature|signatureTimestamp|UID|profile|data");
b.events.global.dispatchWhenHandlerAdded(d);-1!=b.utils.array.indexOf(c,"socialize.login")&&(a=e.addUserInfoToEvent(a,{errorCode:0,eventName:"socialize.login"},!0),b.events.global.dispatchWhenHandlerAdded(a))}}):b.socialize.getUserInfo({signIDs:!0,extraFields:"samlData",callback:function(a){for(var d=0;d<c.length;d++){var e=b._.addUserInfoToEvent(a,{errorCode:0,eventName:c[d]},!0);b.events.global.dispatchWhenHandlerAdded(e)}}})},b.thisScript.globalConf.legacyCrossSiteMethod)};c.prototype.setNewLoginTokenFromResponse=
function(a,c,e){var h=c.sessionInfo?c.sessionInfo.login_token:c.login_token;if(h){var g=null!=c.sessionInfo?c.sessionInfo.expires_in:c.expires_in;(!g||0==g)&&0>a.params.sessionExpiration&&(g=b.utils.cookie.setInfiniteExpirationTimeInSeconds());d.tokenStore.set(a.params.APIKey,h,g,b.thisScript.globalConf.legacyCrossSiteMethod);d.sso.setGroupTokenFromResponse(c,e,b.thisScript.globalConf.legacyCrossSiteMethod)}else e()};c.prototype.onInvalidTokenResponse=function(a,b){var c=this;a.paramsLoginToken?b():
d.sso.getGroupToken({callback:function(e){e&&e.login_token&&e.login_token.split("|")[0]!=a.sentLoginToken&&!a.paramsLoginToken?c.initAPIProxy(function(){d.tokenStore.setFromSsoResponse(e,a.params.APIKey);a.params.login_token=void 0;a.send()}):(d.tokenStore.remove(a.params.APIKey),a.settings.requiresSession()?b():(delete a.params.login_token,delete a.sentLoginToken,a.send()))}})};c.prototype.handleTokenResponse=function(a,c,h){var l=this;c=b.utils.object.clone(c);if(c.ssoToken){var g=(new Date).getTime();
(new Date(g+3E5)).getTime();b.utils.localStorage.setItem("_gig_ssoToken",b.utils.JSON.serialize({ssoToken:c.ssoToken,exp:g}))}if(403030==c.errorCode){if(this.shouldWaitForService(a,c))return}else 409012==c.errorCode&&(d.gmidTicket=null,b.utils.localStorage.removeItem("_gig_gmidt"));a.sentLoginToken&&e.logoutMethods[a.methodName]&&0==c.errorCode&&c.logoutActiveSession&&this.clearSession(a.params);this.setNewLoginTokenFromResponse(a,c,function(){if(a.sentLoginToken&&403005==c.errorCode)l.onInvalidTokenResponse(a,
h);else h()})};c.prototype.logoutSsoIfNeeded=function(a,c,h){var l=this;b.partnerSettings.ssoKey&&e.logoutMethods[a.methodName]&&0==c.errorCode&&c.logoutActiveSession?document.location.href!=b.partnerSettings.ssoLogoutUrl?d.sso.logout({callback:function(b){var d;void 0!==a.params.sustainLogoutURLs&&(d=!a.params.sustainLogoutURLs);l.loadLogoutUrls(b.logoutURLs,h,{UID:c.UID,UIDSignature:c.UIDSignature,signatureTimestamp:c.signatureTimestamp},d)}}):h():h()};c.prototype.loadLogoutUrls=function(a,c,d,
e){var g=0,h=a?a.split(","):[];a=function(){g++;g>h.length&&c()};for(var k=0;k<h.length;k++)if(h[k]){var n=b.utils.URL.addParamsToURL(h[k],d);this.loadLogoutUrl(n,a,e)}else a();a()};c.prototype.loadLogoutUrl=function(a,c,d){void 0===d&&(d=5E3);var e=document.createElement("iframe");e.src=a;e.style.position="absolute";e.style.top="-1000px";e.style.left="-1000px";var g=!1,h=function(){g=!0;!1!==d&&e.parentElement.removeChild(e);c()};window.setTimeout(function(){g||h()},d);e.onload=function(){h()};b.utils.DOM.appendToBody(e)};
c.prototype.shouldWaitForService=function(a,c){return 1==a.params.retryPossible?(a.params.retryPossible=!1,b.external.facebook.runWhenLoaded(function(){a.send()}),!0):!1};c.prototype.dispatchCallbacks=function(a,c){var e=d.callbacks[a];if(e)for(var h=0;h<e.length;h++)if("function"==typeof e[h])e[h](b.utils.object.clone(c,!0));delete d.callbacks[a]};c.prototype.getRequestId=function(a){var c=a.settings.jsSdkRequestId;if(c)return c;if(a.settings.disableCache||this.getIsForceBrowserRequest(a))return"R"+
(new Date).getTime()+"_"+Math.random();var c=b.utils.object.clone(a.params),d;for(d in c)0!=d.indexOf("fb_")&&"source"!=d&&"sourceData"!=d||delete c[d];return"R"+b.utils.object.getMurmurHash(a.baseUrl+a.methodName+b.utils.object.getHash(c))};c.prototype.getIsForceBrowserRequest=function(a){return b.localInfo.isSafari||b.localInfo.isIE10&&"accounts.getAccountInfo"===a.methodName?!0:!1};return c}();d.WebAdapter=h})(k.web||(k.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya=
{}));
(function(b){(function(e){(function(e){(function(d){var e=function(){function d(){this.flashStorageLoaded=!1;this.swfStorage=null;var b=document.location.href.split("#")[1];this.apiKey=decodeURIComponent(b.split("apikey=")[1].split("&")[0]);this.originDomain=decodeURIComponent(b.split("domain=")[1].split("&")[0]);this.hasTicket="true"===decodeURIComponent(b.split("hasTicket=")[1].split("&")[0]);this.urlScheme=0==document.location.href.indexOf("https:")?"https":"http"}d.init=function(){d.instance=new d;
d.instance.init()};d.prototype.init=function(){var c=this;this.isOriginDomainValid()?this.loadIDs(function(a){if(a)c.postState({ready:!1,error:a});else{if(c.gmid&&c.ucid)c.hasTicket?c.postState({ready:!0}):c.getGmidTicketFromServer(function(a){c.postState({ready:!0,gmidTicket:a})});else{var d=10,e=function(a,b,e,k,m){0!=a&&403036!=a&&--d?window.setTimeout(h,10):(c.gmid=b,c.ucid=k,c.storeIDs(function(){c.postState({ready:0==a,gmidTicket:e,error:m})}))},h=function(){return c.getIDsFromServer(e)};h()}b.utils.DOM.addEventListener(window,
"message",function(a){return c.onRequest(a)})}}):this.postState({ready:!1,error:"domain_mismatch"})};d.prototype.onRequest=function(c){var a=this;c=b.utils.JSON.deserialize(c.data);var d,e;if(c&&"object"==typeof c&&c.methodName&&c.id&&c.params){d=c.methodName;e=c.id;var h=b.utils.object.clone(c.params,!0,!0);h.gmid=this.gmid;h.ucid=this.ucid;(new b._.apiAdapters.web.JsonpRequest(e,this.getAPIBaseUrl(d),d,h,function(c){c=b.utils.JSON.serialize({id:e,response:c});b.utils.JSON.deserialize(c)||(c=b.utils.JSON.serialize({id:e,
response:{errorCode:400004,errorMessage:"Invalid parameter format. One of the parameters of this request has been set with a value which is not in the expected format."}}));window.parent.postMessage(c,a.originDomain)},c.settings)).send()}};d.prototype.isOriginDomainValid=function(){return!!b._.getPageBaseDomain(this.originDomain)};d.prototype.getIDsFromServer=function(c){var a={APIKey:this.apiKey,includeTicket:!0,ticketExpires:86400};(new b._.apiAdapters.web.JsonpRequest("idsRequest",this.getAPIBaseUrl("socialize.getIDs"),
"socialize.getIDs",a,function(a){var d=a.errorCode;0!=d&&b.log.addLog("Failed to get IDs from server",a);c(d,a.gcid,a.gmidTicket,a.ucid,a.errorMessage)})).send()};d.prototype.getGmidTicketFromServer=function(c){var a={gmid:this.gmid,APIKey:this.apiKey,expires:86400};(new b._.apiAdapters.web.JsonpRequest("gmidTicketRequest",this.getAPIBaseUrl("socialize.getGmidTicket"),"socialize.getGmidTicket",a,function(a){c(a.gmidTicket)})).send()};d.prototype.getAPIBaseUrl=function(c){c=c.split(".");return"https://"+
b.utils.stringUtils.format("{0}.{1}",c[0],b.partnerSettings.plugins.apiDomain)};d.prototype.postState=function(c){c||(c={});c.apiKey=this.apiKey;window.parent.postMessage(b.utils.JSON.serialize(c),this.originDomain)};d.prototype.loadIDs=function(b){var a=this;this.getIDsFromStorage(function(d,e,h,g){a.gmid=d;a.ucid=e;h?(a.hasTicket=!1,a.storeIDs(function(){b(g)})):b(g)})};d.prototype.getIDsFromStorage=function(c){var a=this,f,e,k,g;try{var p=function(a){a=localStorage.getItem(a);return"undefined"==
a?null:a};f=p(d.SSO_GMID_STORAGE_KEY);e=p(d.GMID_STORAGE_KEY);f&&f!=e&&(g=!0,e=f);(k=p(d.SSO_UCID_STORAGE_EKY))||(k=p(d.UCID_STORAGE_EKY));c(e,k,g)}catch(q){b.localInfo.isMobile?c(null,null,!1,"no_supported_cookie_storage"):this.loadFlashStorageJS(function(b){if(b){b=function(b){b=a.swfStorage.get(b);return"undefined"==b?null:b};var e=b(d.GMID_STORAGE_KEY),f=b(d.UCID_STORAGE_EKY)}else var g="no_supported_cookie_storage";c(e,f,!1,g)})}};d.prototype.storeIDs=function(b){var a=this;try{localStorage.setItem(d.GMID_STORAGE_KEY,
this.gmid),localStorage.setItem(d.UCID_STORAGE_EKY,this.ucid),b()}catch(e){this.loadFlashStorageJS(function(e){e&&(a.swfStorage.set(d.GMID_STORAGE_KEY,a.gmid),a.swfStorage.set(d.UCID_STORAGE_EKY,a.ucid));b()})}};d.prototype.loadFlashStorageJS=function(c){var a=this,d=function(b){a.flashStorageLoaded=!0;try{a.swfStorage?b(!0):a.swfStorage=new SwfStore({namespace:"gigIDs",swf_url:"https://cdns.gigya.com/gs/swf/swfstore.swf",onready:function(){b(!0)},onerror:function(){"object"==typeof console&&console.log&&
console.log("Failed loading swfstore.swf");b(!1)}})}catch(c){b(!1)}};this.flashStorageLoaded?d(c):b.utils.script.load("https://cdns.gigya.com/gs/js/swfstore.min.js",null,function(){d(c)})};d.SSO_GMID_STORAGE_KEY="gig_sso_gmid";d.SSO_UCID_STORAGE_EKY="gig_sso_ucid";d.GMID_STORAGE_KEY="gig_gmid";d.UCID_STORAGE_EKY="gig_ucid";return d}();d.APIProxy=e})(e.web||(e.web={}))})(e.apiAdapters||(e.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
var gigya;
(function(b){(function(g){(function(e){(function(h){h.newApiAdapter=function(a){return new d(a)};h.mobileCallbacks={};var e="is_session_valid send_request send_oauth_request get_ids on_plugin_event on_custom_event register_for_namespace_events".split(" "),f={logLevel:[]},d=function(){function a(c){this.adapterSettings=c;this.name="Mobile"}a.prototype.init=function(c){var a=this;this.features=this.adapterSettings&&"function"===typeof this.adapterSettings.getFeatures?b.utils.JSON.deserialize(this.adapterSettings.getFeatures()):e;
this.adapterSettings&&"function"===typeof this.adapterSettings.getSettings?(this.settings=b.utils.JSON.deserialize(this.adapterSettings.getSettings())||{},this.settings.logLevel=b.utils.array.getArrayFromString(this.settings.logLevel||f.logLevel.join(","),",")):this.settings=f;b.events.addMap({defaultMethod:function(c){a.onPluginEvent(c)},eventMap:[{events:"*",args:["$event"]}]});this.sendToMobile("get_ids",null,function(d){a.ucid=d.ucid;a.gcid=d.gcid;for(var l in b.events.global._activeNamespaces)a.registerForNamespaceEvents(l);
b.localInfo.isNativeMobileApp=!0;c()})};a.prototype.getTokenParam=function(c,a){return""};a.prototype.onPluginEvent=function(c){c.isGlobal||this.sendToMobile("on_plugin_event",c)};a.prototype.onCustomEvent=function(c){this.sendToMobile("on_custom_event",c)};a.prototype.onJSLog=function(c,a){this.isLogLevelSupported(c)&&this.sendToMobile("on_js_log",{logType:c,logInfo:a})};a.prototype.registerForNamespaceEvents=function(c){this.sendToMobile("register_for_namespace_events",{namespace:c})};a.prototype.getGmidTicket=
function(c){c&&this.sendRequest("socialize.getGmidTicket",{expires:30},function(a){c(a.gmidTicket)},{forceHttps:!0})};a.prototype.clearSession=function(c,a){this.sendToMobile("clear_session",c,a)};a.prototype.isSessionValid=function(c,a){this.sendToMobile("is_session_valid",{},a)};a.prototype.sendRequest=function(c,a,b,d){this.sendToMobile("send_request/"+c,a,b,d)};a.prototype.sendOauthRequest=function(a,b,d,e){this.sendToMobile("send_oauth_request/"+a,b,d,e)};a.prototype.sendToMobile=function(a,
d,e,g){if(this.isActionSupported(a)){var f=document.createElement("iframe");f.style.display="none";d&&delete d.APIKey;if(e){var k=(new Date).getTime()+"_"+Math.random();h.mobileCallbacks[k]=function(a){e(a);document.documentElement.removeChild(f);delete h.mobileCallbacks[k]}}a="gsapi://"+a+"?callbackID="+(k||"")+"¶ms="+(d?encodeURIComponent(b.utils.keyValue.serialize(d)):"")+"&settings="+(g?encodeURIComponent(b.utils.keyValue.serialize(g)):"");f.src=a;window.setTimeout(function(){return document.documentElement.appendChild(f)},
0)}else e&&e({errorCode:400096,errorMessage:"Mobile SDK does not support feature "+a})};a.prototype.onSDKEvent=function(a){a&&a.user&&g.convertIdentitiesArrayToObject(a.user);b.events.global.dispatch(a)};a.prototype.isActionSupported=function(a){if(!a)return!1;a=a.split("/")[0].toLowerCase();return-1<b.utils.array.indexOf(this.features,a)};a.prototype.isLogLevelSupported=function(a){return-1!=b.utils.array.indexOf(this.settings.logLevel,"*")||-1!=b.utils.array.indexOf(this.settings.logLevel,a)};return a}();
h.MobileAdapter=d})(e.mobile||(e.mobile={}))})(g.apiAdapters||(g.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
(function(b){(function(g){(function(e){(function(e){e.showPlugin=function(e,f){var d=e.split("."),a=d.splice(d.length-1,1)[0];d.length||(d=["socialize"]);"commentsUI"==e&&(d=["comments"]);a="show"+b.utils.stringUtils.capitalize(a);d.push(a);for(a=b;a&&d.length;)a=a[d.shift()];if("function"!==typeof a)return b.events.dispatchInvalidParamError(b.utils.object.merge([{plugin:e},f]),"plugin");a(f)}})(e.mobile||(e.mobile={}))})(g.apiAdapters||(g.apiAdapters={}))})(b._||(b._={}))})(gigya||(gigya={}));
// end API adapters
var gigya;
(function(a){var b=navigator.userAgent.toLowerCase(),g="function"===typeof FileReader||"object"===typeof FileReader?!0:!1,h=new Date,f=document.location.hostname,e="http:"==document.location.protocol?"http":"https",d=-1!=b.indexOf("win"),c=-1!=b.indexOf("msie")||-1!=b.indexOf("mozilla")&&-1!=b.indexOf("trident"),l=-1!=b.indexOf("msie 6."),p=-1!=b.indexOf("msie 7."),q=-1!=b.indexOf("msie 8."),k=-1!=b.indexOf("msie 9."),m=-1!=b.indexOf("msie 10."),r=-1!=b.indexOf("mozilla")&&-1!=b.indexOf("trident/7.0"),n=
-1!=b.indexOf("edge"),t=-1!=b.indexOf("iphone")||-1!=b.indexOf("ipad")||-1!=b.indexOf("ipod"),u=-1!=b.indexOf("safari/534"),v;v=-1!=b.indexOf("applewebkit")&&-1!=b.indexOf("version/")?parseInt(b.split("version/")[1].split(" ")[0]):0;var w=-1!=b.indexOf("android"),A=function(a){return-1===a.indexOf("mozilla/5.0")||-1===a.indexOf("android 4")||-1===a.indexOf("applewebkit")||-1!==a.indexOf("windows phone")?!1:(a=/chrome\/(\d+)/.exec(a))?20>parseInt(a[1]):!0}(b),x;x=-1!=b.indexOf("android")?parseFloat(b.slice(b.indexOf("android")+
8)):0;a.localInfo={isBrowserSupportsFilesAPI:g,initTime:h,version:0,pageDomain:f,protocol:e,userAgent:b,isWin:d,isIE:c,isIE6:l,isIE7:p,isIE8:q,isIE9:k,isIE10:m,isIE11:r,isEdge:n,isIOS:t,isSafari534:u,iosVersion:v,isAndroid:w,isAndroidBrowser:A,currentBrowser:"",androidVersion:x,isChrome:-1!=b.indexOf("chrome")&&-1==b.indexOf("edge"),isFF:-1!=b.indexOf("firefox"),isOpera:-1!=b.indexOf("opera"),isSafari:navigator.appVersion&&-1!=navigator.appVersion.toLowerCase().indexOf("safari")&&-1==navigator.appVersion.toLowerCase().indexOf("chrome")&&
-1==b.indexOf("android"),isIOSWebView:/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent),isIOSChrome:-1!=b.indexOf("crios"),isMAC:navigator.appVersion&&-1!=navigator.appVersion.toLowerCase().indexOf("mac")?!0:!1,isWindowsPhone:-1!=b.indexOf("windows phone"),supportsPostMessage:null!=window.postMessage&&(-1==b.indexOf("msie")||-1!=b.indexOf("iemobile")),supportsLocalStorage:function(){try{if(null!=window.localStorage){var a=window.localStorage.getItem("_gig_localStorage_test");
window.localStorage.setItem("_gig_localStorage_test","just checking for localStorage");var d="just checking for localStorage"===window.localStorage.getItem("_gig_localStorage_test");a?window.localStorage.setItem("_gig_localStorage_test",a):window.localStorage.removeItem("_gig_localStorage_test");return d}return!1}catch(c){return!1}}(),quirksMode:"BackCompat"==document.compatMode&&-1!=b.indexOf("msie"),backCompat:"BackCompat"==document.compatMode,isMobile:function(){var a="iphone;ipod;android;midp;240x320;blackberry;netfront;nokia;panasonic;portalmmm;sharp;sie-;sonyericsson;symbian;windows ce;benq;mda;mot-;opera mini;philips;pocket pc;sagem;samsung;htc".split(";"),
d;for(d in a)if(-1!=b.indexOf(a[d]))return!0;return!1}(),isMobileApp:function(){if(!document.getElementsByTagName)return!1;for(var a=document.getElementsByTagName("meta"),d=0;d<a.length;d++)if("viewport"==a[d].getAttribute("name")){var c=a[d].getAttribute("content");if(c&&-1!==c.indexOf("width=device-width"))return!0}return!1}(),isNativeMobileApp:!1,isTouch:function(){if("ontouchstart"in window)return!0;if("onmsgesturechange"in window)try{new ActiveXObject("htmlfile")}catch(a){return!0}return!1}(),
messagingMethod:0};a.localInfo.isIE11&&!window.indexedDB&&(a.localInfo.supportsPostMessage=!1);a.localInfo.isMAC=a.localInfo.isMAC&&!a.localInfo.isIOS;(g=a.localInfo.isWin?"windows":a.localInfo.isWindowsPhone?"winphone":a.localInfo.isIOS?"ios-v"+a.localInfo.iosVersion:a.localInfo.isMAC?"mac":a.localInfo.isAndroid?"android":"")&&(g+=" ");a.localInfo.currentBrowser=g+(a.localInfo.isChrome?"chrome":a.localInfo.isFF?"firefox":a.localInfo.isSafari?"safari":a.localInfo.isEdge?"edge":a.localInfo.isIE11?
"ie11":a.localInfo.isIE10?"ie10":a.localInfo.isIE9?"ie9":a.localInfo.isIE8?"ie8":"")})(gigya||(gigya={}));
(function(a){(function(a){(function(a){function b(a,c){for(var e=0;e<a.length;++e)c(a[e],e,a)}function f(a,c){for(var e=0;e<a.length;++e)if(c(a[e],e,a))return!0;return!1}function e(a,c){var e=-1;f(a,function(a,d,f){return c(a,d,f)?(e=d,!0):!1});return e}a.indexOf=function(a,c){for(var e=0;e<a.length;e++)if(a[e]==c)return e;return-1};a.clone=function(a){for(var c=[],e=0;e<a.length;e++)c[e]=a[e];return c};a.removeByValue=function(a,c){if(a)for(var e=a.length-1;0<=e;e--)a[e]==c&&a.splice(e,1)};a.removeByProperty=
function(a,c,e){if(a)for(var f=a.length-1;0<=f;f--)a[f][c]==e&&a.splice(f,1)};a.getArrayFromString=function(a,c,e){if(!a||"string"!=typeof a)return[];e&&(a=a.toLowerCase());return(a=a.replace(/[ ]/g,"").replace(/,,/g,","))?a.split(c):[]};a.intersect=function(a){for(var c=1;c<arguments.length;c++);if(null==a)return[];for(var c=[],e=arguments.length,f=0,b=a.length;f<b;f++){var g=a[f];if(-1==this.indexOf(c,g)){for(var h=1;h<e;h++){var r=arguments[h];if(null==r||-1==this.indexOf(r,g))break}h===e&&c.push(g)}}return c};
a.lastIndexOf=function(a,c,e){void 0===e&&(e=0);for(var f=a.length;--f>=e;)if(a[f]===c)return f;return-1};a.forEach=b;a.forEachProp=function(a,c){for(var e in a)a.hasOwnProperty(e)&&c(a[e],e,a)};a.some=f;a.every=function(a,c){for(var e=0;e<a.length;++e)if(!c(a[e],e,a))return!1;return!0};a.everyProp=function(a,c){for(var e in a)if(a.hasOwnProperty(e)&&!c(a[e],e,a))return!1;return!0};a.map=function(a,c){var e=[];b(a,function(a,d,f){return e.push(c(a,d,f))});return e};a.firstIndex=e;a.first=function(a,
c){return a[e(a,c)]};a.getAllEnumValues=function(a){var c=[],e;for(e in a)"number"==typeof a[e]&&c.push(a[e]);return c}})(a.array||(a.array={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));(function(a){(function(a){(function(a){a.create=function(a,f){return function(){for(var e=[],d=0;d<arguments.length;d++)e[d-0]=arguments[d];return f.apply(a,e)}}})(a.delegate||(a.delegate={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.fill=function(b,f){"function"==typeof b&&(b=b(f));b instanceof Array&&(b=b.join(""));var e=/(\$)(!?)([a-z_][a-z_.\d]*)([(][^()]*[)])?|(\$)(!?)\{([a-z_][a-z_.\d]*)([(][^()]*[)])?\}/gi;e.lastIndex=0;for(var d=b,c=e.exec(d),l;null!=c;){l="$"==c[1]?0:4;var p="!"==c[2+l],g=c[3+l];l=c[4+l];null==l&&(l="");"."==g.substring(0,1)&&(g=g.substring(1));"DBG"==g.substring(0,3)&&(g=g.substring(3));var k="";for(l=g+l;l!=k;){var k=l,m=e.lastIndex;l=a.utils.templates.fill(k,
f);e.lastIndex=m}k="";m=0;if(null!=f[g.split(".")[0]])try{k=(new Function("o","p",'return eval("o." + p)'))(f,l)}catch(r){}else k="$"+(p?"!":"")+l,m=1;d=p?d.replace(c[0],""):d.substr(0,c.index)+k+d.substr(c.index+c[0].length);e.lastIndex=c.index+m;c=e.exec(d)}return d}})(b.templates||(b.templates={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.callFunction=function(a,f){var e=eval(a),d=a.split(".");d.splice(d.length-1,1);d=eval(d.join("."));e.apply(d,f)};b.invokeOnPageLoad=function(b,f){if(!document.readyState&&document.body||"loaded"==document.readyState||"complete"==document.readyState||!f&&"interactive"==document.readyState&&document.body)b();else{var e=!1,d=function(){e||(e=!0,b())};window.setTimeout(d,2E4);a.utils.DOM.addEventListener(window,"load",d);a.utils.DOM.addEventListener(document,"DOMContentLoaded",
d)}};b.createAlias=function(a,f){for(var e=a.split("."),d=window,c=0;c<e.length-1;c++){var b=e[c];d[b]||(d[b]={});d=d[b]}d[e[e.length-1]]=f}})(b.functions||(b.functions={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){var h={},f=0;b.open=function(e,d,c){c||(c="menubar=0,toolbar=0,resizable=1,scrollbars=1,width=960,height=680");var b=c;try{var p=parseInt(c.split("width=")[1].split(",")[0]),g=parseInt(c.split("height=")[1].split(",")[0]),k=(screen.width-p)/2,m=(screen.height-g)/2;0>k&&(k=0);0>m&&(m=0);b+=",top="+m+",left="+k}catch(r){}c=a.localInfo.isIE&&2048<e.length||4096<e.length;p=e;c&&(p="",a.localInfo.isIE&&(p="about:blank"),d&&"_blank"!=d.toLowerCase()||(d="_gigWindow_"+
(new Date).getTime()+"_"+ ++f));(b=window.open(p,d,b))&&b.focus&&b.focus();h[d]=b;c&&a.utils.HTTP.redirect(e.split("?")[0],[a.utils.URL.getParamsFromURL(e)],"POST",d);return null!=h[d]};b.close=function(e){if(null!=h[e]){var d=function(){try{null!=h[e]&&h[e].close(),delete h[e]}catch(a){}};6<=a.localInfo.iosVersion?d():window.setTimeout(d,10)}}})(b.win||(b.win={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(a){(function(a){a.isExplicitTrue=function(a){a=(""+a).toLowerCase();return"true"==a||"1"==a};a.isExplicitFalse=function(a){a=(""+a).toLowerCase();return"false"==a||"0"==a}})(a.validation||(a.validation={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(a){(function(a){function b(a,e,d,c,l){void 0===e&&(e=!1);void 0===d&&(d=!1);void 0===c&&(c=0);void 0===l&&(l=20);c||(c=0);if(c>l)return"[Too deep]";var p=l="",g="";if(d)for(var g="\t",p="\n",k=0;k<c+1;k++)l+=g;var m=typeof a;if("function"==m)return m.toString();if("object"!=m||null===a)return"string"==m&&(a='"'+a.replace(/(\"|\\)/g,"\\$1").replace(/\r\n|\r|\n/g,"\\n")+'"'),String(a);var r,n,t=[],u=a&&a.constructor==Array;if(u)for(k=0;k<a.length;k++)n=a[k],m=typeof n,null==n||
"undefined"==m?n="":"string"==m?n='"'+n.replace(/(\"|\\)/g,"\\$1").replace(/\r\n|\r|\n/g,"\\n")+'"':"function"==m?n=e?"Function":"":n.parentNode&&n.innerHTML?n="HTMLElement":n.constructor==Date?n="":"object"==m&&null!==n&&(n=b(n,e,d,c+1)),""!=String(n)&&t.push(l+g+String(n));else for(r in a)n=a[r],m=typeof n,null==n||"undefined"==m?n=String(n):"string"==m?n='"'+n.replace(/(\"|\\)/g,"\\$1").replace(/\r\n|\r|\n/g,"\\n")+'"':"function"==m?n=e?"Function":"":n.parentNode&&n.innerHTML?n="HTMLElement":n.constructor==
Date?n="":"object"==m&&null!==n&&(n=p+b(n,e,d,c+1)),""!=String(n)&&t.push(l+g+'"'+r.replace(/(\"|\\)/g,"\\$1").replace(/\r\n|\r|\n/g,"\\n")+'":'+String(n));return p+l+(u?"[":"{")+p+t.join(","+p)+p+l+(u?"]":"}")}a.serialize=b;a.deserialize=function(a){""===a&&(a='""');eval("var o");try{eval("o="+a)}catch(e){}return eval("o")}})(a.JSON||(a.JSON={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){function h(a,c,e){if(!c)return a;c=c.split(".");for(var b=0;b<c.length;b++){var f=c[b];e&&!a[f]&&(a[f]={});if(a[f])a=a[f];else return null}return a}function f(a,c,e,b,g,h){void 0===b&&(b=20);void 0===g&&(g=0);if(g>b||"undefined"==typeof a||null==a||"function"==typeof a&&e)return null;if(a.constructor==Array){for(var m=[],r=0;r<a.length;r++)e&&"function"==typeof a[r]||(m[r]=c?f(a[r],c,e,b,g+1,h):a[r]);return m}if("object"==typeof a){m={};for(r in a)h&&"context"==
r||e&&"function"==typeof a[r]||(m[r]=c?f(a[r],c,e,b,g+1,h):a[r]);return m}return a}function e(d,c,b){if(null!=d){null==c&&(c={});if(d.constructor==Array)for(var f=0;f<d.length;f++)e(d[f],c,b);else if(b){b=b.split("|");var f={},g;for(g in d)f[g.toLowerCase()]=1;for(g=0;g<b.length;g++){var h=b[g];f[h.toLowerCase()]&&(c[h]=d[h])}}else c=a.utils.object.clone(d,!1);return c}}b.removeUndefined=function(a){var c={},e;for(e in a)null!=a[e]&&void 0!=a[e]&&(c[e]=a[e]);return c};b.getPropertyBySerializedName=
h;b.setPropertyBySerializedName=function(a,c,e){c=c.split(".");var b=c.pop();h(a,c.join("."),!0)[b]=e};b.add=function(a,c,e){for(var b in c)e&&"undefined"!=typeof a[b]||(a[b]=c[b])};b.getHash=function(d){var c=[],e;for(e in d){var b;"object"==typeof d[e]?b=a.utils.JSON.serialize(d[e],!1):d[e]&&(b=d[e].toString());c.push(e+"="+b)}return c.sort().join("&")};b.getMurmurHash=function(a,c){c||(c=0);var e,b,f,g,h;e=a.length&3;b=a.length-e;f=c;for(h=0;h<b;)g=a.charCodeAt(h)&255|(a.charCodeAt(++h)&255)<<
8|(a.charCodeAt(++h)&255)<<16|(a.charCodeAt(++h)&255)<<24,++h,g=3432918353*(g&65535)+((3432918353*(g>>>16)&65535)<<16)&4294967295,g=g<<15|g>>>17,g=461845907*(g&65535)+((461845907*(g>>>16)&65535)<<16)&4294967295,f^=g,f=f<<13|f>>>19,f=5*(f&65535)+((5*(f>>>16)&65535)<<16)&4294967295,f=(f&65535)+27492+(((f>>>16)+58964&65535)<<16);g=0;switch(e){case 3:g^=(a.charCodeAt(h+2)&255)<<16;case 2:g^=(a.charCodeAt(h+1)&255)<<8;case 1:g^=a.charCodeAt(h)&255,g=3432918353*(g&65535)+((3432918353*(g>>>16)&65535)<<16)&
4294967295,g=g<<15|g>>>17,f^=461845907*(g&65535)+((461845907*(g>>>16)&65535)<<16)&4294967295}f^=a.length;f^=f>>>16;f=2246822507*(f&65535)+((2246822507*(f>>>16)&65535)<<16)&4294967295;f^=f>>>13;f=3266489909*(f&65535)+((3266489909*(f>>>16)&65535)<<16)&4294967295;return(f^f>>>16)>>>0};b.clone=f;b.merge=function(a){for(var c={},e=0;e<a.length;e++)if(a[e]&&a[e].length)for(var b=0;b<a[e].length;b++)for(var f in a[e][b])c[f]=a[e][b][f];else for(f in a[e])c[f]=a[e][f];return c};b.extractProperties=e;b.extractProperty=
function(a,c){return e(a,void 0,c)[c]}})(b.object||(b.object={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){function h(f,e,d,c,l){var p=a.localInfo.pageDomain,h=a.partnerSettings.baseDomain;null==c&&(c=0<h.length&&p.length>=h.length&&p.lastIndexOf(h)==p.length-h.length?h:p);d=null==d||""===d||isNaN(d)?47304E7:0==d?null:1E3*d;h=new Date;h.setTime(h.getTime()+d);c=f+"="+escape(e)+(l?"":"; path=/")+(null==d?"":"; expires="+h.toUTCString())+(c&&""!=c&&-1!=c.indexOf(".")?"; domain="+c:"");document.cookie=c;d&&!(0<d)||b.get(f)||(c=f+"="+escape(e)+(l?"":"; path=/")+(null==
d?"":"; expires="+h.toUTCString())+(p&&""!=p&&-1!=p.indexOf(".")?"; domain="+p:""),document.cookie=c)}b.get=function(a){a=a.replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1").replace(/^[ \t]+|[ \t]+$/g,"");return(a=document.cookie.match(new RegExp("(?:^|;)\\s?"+a+"=(.*?)(?:;|$)")))&&unescape(a[1])};b.set=h;b.remove=function(b){var e=a.localInfo.pageDomain,d=a.partnerSettings.baseDomain;0<d.length&&e.length>=d.length&&e.lastIndexOf(d)==e.length-d.length&&(h(b,"",-1,d),h(b,"",-1,d,!0));h(b,"",-1,a.localInfo.pageDomain);
h(b,"",-1,a.localInfo.pageDomain,!0);h(b,"",-1,"");h(b,"",-1,"",!0)};b.setInfiniteExpirationTimeInSeconds=function(){return 47304E4}})(b.cookie||(b.cookie={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(a){(function(a){a.sanitizeHTML=function(a){return null==a||"undefined"==typeof a?a:a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\"/g,""").replace(/'/g,"'").replace(/&#173;/g,"­")};a.sanitizeAttribute=function(a){return null==a||"undefined"==typeof a?a:a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\"/g,""").replace(/\=/g,"=")}})(a.sanitize||(a.sanitize={}))})(a.utils||(a.utils={}))})(gigya||
(gigya={}));
(function(a){(function(a){(function(a){function b(){var a=0,d=0;"number"==typeof window.pageYOffset?(d=window.pageYOffset,a=window.pageXOffset):document.body&&(document.body.scrollLeft||document.body.scrollTop)?(d=document.body.scrollTop,a=document.body.scrollLeft):document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)&&(d=document.documentElement.scrollTop,a=document.documentElement.scrollLeft);return{left:a,top:d}}function f(){var a,d;d=document.documentElement;var c=
document.body;window.innerHeight?(a=window.innerHeight,d=window.innerWidth):(a=d.clientHeight,0==a&&(a=c.clientHeight),d=d.clientWidth,0==d&&(d=c.clientWidth));return{w:d,h:a}}a.getScroll=b;a.getFullSize=function(){var a=document.documentElement,d=document.body,c=a.clientHeight;0==c&&(c=d.clientHeight);a=a.clientWidth;0==a&&(a=d.clientWidth);return{w:a,h:c}};a.getOrientation=function(){var a=parseInt(window.orientation||"0");0>a&&(a+=360);return a};a.getInnerSize=f;a.getMiddleCenter=function(){var a=
b(),d=f();return{top:a.top+Math.floor(d.h/2),left:a.left+Math.floor(d.w/2)}};a.isRectHorizontallyVisible=function(a){var d=b(),c=f();return a.left>=d.left&&a.right<=d.left+c.w};a.isRectFullyVisible=function(a){var d=b(),c=f();return a.top>=d.top&&a.bottom<=d.top+c.h&&a.left>=d.left&&a.right<=d.left+c.w};a.scrollIntoView=function(a){a&&a.scrollIntoView&&a.scrollIntoView()}})(a.viewport||(a.viewport={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(a){(function(a){a.getPosition=function(){var a=0,b=0;if(document.body){var e=null,e={clientX:0,clientY:0};if(e.pageX||e.pageY)a=e.pageX,b=e.pageY;else if(e.clientX||e.clientY)a=e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,b=e.clientY+document.body.scrollTop+document.documentElement.scrollTop;return{x:a,y:b}}}})(a.mouse||(a.mouse={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){var g=function(){function b(a,e){void 0===e&&(e="/");this.domain=a;this.path=e}b.prototype.isIn=function(a){return(this.domain==a.domain||this.isSubDomainOf(a))&&(!a.path||0==this.path.indexOf(a.path))};b.prototype.isForSubDomains=function(){return 0==this.domain.indexOf(".")};b.prototype.isSubDomainOf=function(b){var e="";b.isForSubDomains()||(e=".");e+=b.domain;return a.utils.stringUtils.endsWith(this.domain,e)};b.parse=function(a,e){void 0===e&&(e=!0);if(a){var d=document.createElement("a");
e&&0!=a.indexOf("http")&&(a="http://"+a);d.href=a;return new b(d.hostname,d.pathname)}};return b}();b.Uri=g})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.URLEncode=function(a){return encodeURIComponent(a)};b.URLDecode=function(a){return decodeURIComponent(a.replace(/\+/g," "))};b.getParamsFromURL=function(b,f){return-1==b.indexOf("?")?{}:a.utils.keyValue.deserialize(b.split("#")[0].split("?")[1],"&",f)};b.getParamValueFromURL=function(a,b,e){if(null==b||""==b)return e;var d=b.indexOf("?");if(-1==d)return e;d="&"+b.substr(d+1);b=d.toLowerCase().indexOf("&"+a.toLowerCase()+"=");if(-1==b)return e;a=d.substr(b+
(1+a.length+1))+"&";b=a.indexOf("&");return a.substr(0,b)};b.addParamsToURL=function(b,f){var e=a.utils.URL.getParamsFromURL(b);a.utils.object.add(e,f);var d=b.split("#"),e=d[0].split("?")[0]+"?"+a.utils.keyValue.serialize(e,"&");1<d.length&&(e+="#"+d[1]);return e}})(b.URL||(b.URL={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.serialize=function(b,f){var e=[];f||(f="&");for(var d in b)switch(typeof b[d]){case "function":break;case "array":case "object":null!=b[d]&&e.push(d+"="+a.utils.URL.URLEncode(a.utils.JSON.serialize(b[d])));break;case "undefined":break;default:e.push(d+"="+a.utils.URL.URLEncode(b[d]))}return e.join(f)};b.deserialize=function(b,f,e,d){var c={};if(!b)return c;f||(f="&");b=b.split(f);for(f=0;f<b.length;f++){var l=b[f],p=l.indexOf("=");if(-1==p){var g=e?l.toLowerCase():
l;c[g]="1"}else{g=l.substr(0,p);e&&(g=g.toLowerCase());l=l.substr(p+1).replace(/\+/g," ");try{c[g]=d?unescape(l):a.utils.URL.URLDecode(l)}catch(k){c[g]=unescape(l)}}}return c}})(b.keyValue||(b.keyValue={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){function h(a,c,d){"undefined"!==typeof d&&(d=(new Date).getTime()+1E3*d,c=c+"|exp="+d);f(a,c)}var f=function(a,c){},e=function(a){return null},d=function(a){};if(a.localInfo.supportsLocalStorage)f=function(a,c){try{window.localStorage[a]=c}catch(d){}},e=function(a){return window.localStorage[a]},d=function(a){window.localStorage.removeItem(a)};else if(a.localInfo.isIE6||a.localInfo.isIE7)var c=function(){try{p(),q.load("gigya_ud")}catch(a){}},l=function(){try{p(),
q.save("gigya_ud")}catch(a){}},p=function(){q||(q=document.createElement("div"),q.addBehavior("#default#userData"),a.utils.DOM.appendToBody(q))},q,f=function(a,d){c();q.setAttribute(encodeURIComponent(a).replace(/\%/g,""),d);l()},e=function(a){c();return q.getAttribute(encodeURIComponent(a).replace(/\%/g,""))},d=function(a){c();q.removeAttribute(encodeURIComponent(a).replace(/\%/g,""));l()};else if(a.localInfo.isFF&&window.globalStorage)var k=window.globalStorage,f=function(a,c){try{k[location.hostname][a]=
c}catch(d){}},e=function(a){return k[location.hostname][a]},d=function(a){delete k[location.hostname][a]};b.getItem=function(a){var c=e(a);if(c&&c.split){var b=c.split("|exp=");if(1<b.length){c=parseInt(b[1]);if((new Date).getTime()<c)return b[0];d(a);return}}return c};b.setItem=h;b.removeItem=function(a){d(a)};b.setObject=function(c,d){h(c,a.utils.JSON.serialize(d))};b.getObject=function(c){c=this.getItem(c);try{c=a.utils.JSON.deserialize(c)}catch(d){}return c}})(b.localStorage||(b.localStorage=
{}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(g){function h(a,d){if(a){if(!d)return!0;if(!a.className)return!1}else return!1;for(var c=!1,b=a.className.split(" "),f=0;f<b.length;f++)if(b[f]==d){c=!0;break}return c}g._nextZIndex=999999999;g._popupContainers=[];g._pseudoContainers=[];var f=null;g.addEventListener=function(a,d,c){a&&c&&(a.addEventListener?a.addEventListener(d,c,!0):a.attachEvent("on"+d,c))};g.removeEventListener=function(a,d,c){c&&(a.removeEventListener?a.removeEventListener(d,c,!0):a.detachEvent("on"+
d,c))};g.disableDefaultEventHandling=function(a){a.preventDefault?a.preventDefault():window.event&&(window.event.returnValue=!1)};g.addDialogBackListener=function(e){a.utils.DOM._removeDialogBackListener();f=function(d){d&&d.newURL&&-1==d.newURL.indexOf("|gigyaMobileDialog")&&(e(d),a.utils.DOM._removeDialogBackListener())};window.setTimeout(function(){-1==window.location.hash.indexOf("|gigyaMobileDialog")&&(window.location.hash+="|gigyaMobileDialog");a.utils.DOM.addEventListener(window,"hashchange",
f)},50)};g._removeDialogBackListener=function(){f&&(a.utils.DOM.removeEventListener(window,"hashchange",f),f=null,window.location.hash=window.location.hash.replace("|gigyaMobileDialog",""))};g.appendToBody=function(a){document.body&&(document.body.insertBefore&&document.body.firstChild?document.body.insertBefore(a,document.body.firstChild):document.body.appendChild(a))};g.removeElement=function(a){a&&a.parentElement&&a.parentElement.removeChild(a)};g.isChildOf=function(a,d){for(var c=a.parentNode;c;){if(d==
c)return!0;c=c.parentNode}return!1};g.isVisible=function(e){if(!e||!e.parentNode||e.style&&"none"==e.style.display)return!1;if(e.parentNode)return a.utils.DOM.isVisible(e.parentNode)};g.getCenteredDivID=function(e){return"gig_"+a.localInfo.initTime.getTime().toString()+"_"+e};g.createTopLevelDiv=function(e){var d;d=document.createElement("iframe");d.id="gigya_ifr_"+e;d.frameborder="0";d.frameBorder="0";d.allowtransparency=!0;d.style.position="absolute";d.style.width=a.localInfo.isChrome?"30px":"1px";
d.style.height="1px";null!=d.style.zIndex&&(d.style.zIndex=a.utils.DOM._nextZIndex++);a.localInfo.isIE6&&(d.src=a._.getCdnResource("/gs/blank.htm"));var c=document.createElement("div");null!=c.style.zIndex&&(c.style.zIndex=""+a.utils.DOM._nextZIndex++);c.innerHTML="";e&&(c.id=e);document.body&&document.body.insertBefore&&(document.body.firstChild?(null!=d&&document.body.insertBefore(d,document.body.firstChild),document.body.insertBefore(c,document.body.firstChild)):document.body.appendChild&&(null!=
d&&document.body.appendChild(d),document.body.appendChild(c)));return c};g.hideByID=function(a){if(a=document.getElementById(a))a.style.display="none"};g.showByID=function(e){if(e=document.getElementById(e))e.style.display=a.localInfo.isIE6?"TD"==e.tagName?"table-cell":"TR"==e.tagName?"":"TABLE"==e.tagName?"":"block":""};g.clearByID=function(a){try{var d=document.getElementById(a);null!=d&&(d.innerHTML="")}catch(c){}};g.getHTMLSize=function(a,d){var c=document.createElement("div");c.style.position=
"absolute";c.style.left="-1000px";c.innerHTML=a;d.appendChild(c);var b=c.offsetWidth,f=c.offsetHeight;c.parentNode.removeChild(c);return{w:b,h:f}};g.getElementsByClass=function(a,d,c){if(!a)return[];var b=[];c&&h(a,d)&&b.push(a);a=a.getElementsByTagName("*");for(c=0;c<a.length;c++)h(a[c],d)&&b.push(a[c]);return b||[]};g.getElementsByAttribute=function(a,d,c,b){var f=[];a=a.getElementsByTagName(d);for(d=0;d<a.length;d++)a[d].getAttribute(c)==b&&f.push(a[d]);return f};g.getElementPosition=function(e){if(!e)return{left:0,
top:0,bottom:0,right:0};e=e.getBoundingClientRect();var d=a.utils.viewport.getScroll(),c=e.left+d.left,d=e.top+d.top;return{left:c,top:d,right:c+e.width,bottom:d+e.height}};g.addClassToElement=function(a,d){if(a){var c=a.className?a.className.split(" "):[],b=c.length,f=d.split(" "),g;for(g in f){var h=!1;if(!f[g])break;for(var m in c)if(c[m]==f[g]){h=!0;break}h||c.push(f[g])}c.length!=b&&(a.className=c.join(" "))}};g.removeClassFromElement=function(a,d,c){void 0===c&&(c=!1);if(a){for(var b=a.className.split(" "),
f=b.length-1;0<=f;f--)(b[f]==d||c&&-1!=b[f].indexOf(d))&&b.splice(f,1);a.className=b.join(" ")}};g.isElementClass=h;g.cancelEvent=function(a){a&&("cancelable"in a?a.preventDefault():a.returnValue=!1)};g.createElement=function(a,d){var c=document.createElement("div");d=d||"";c.innerHTML="<"+a+' name="'+d+'" id="'+d+'"></'+a+">";return c.firstChild};g.setSize=function(e,d,c,f){if(null!=e&&null!=e.style){if(d){d=""+d;var g=0<d.indexOf("%");if(!isNaN(d)||g)g=""+(g?d:d+"px"),e.style.width!=g&&(e.style.width=
g)}c&&(c=""+c,g=0<c.indexOf("%"),!isNaN(d)||g)&&(g=""+(g?c:c+"px"),e.style.height!=g&&(e.style.height=g));if(f&&d&&c){if(null==e.style.zIndex||f)e.style.zIndex=(this._nextZIndex++).toString();f=b.viewport.getInnerSize();var g=a.utils.viewport.getScroll(),h=g.left;e.style.top=""+Math.max(0,g.top+Math.floor((f.h-c)/2))+"px";e.style.left=""+Math.max(0,h+Math.floor((f.w-d)/2))+"px";e.style.visibility=""}}};g.createHiddenIframe=function(b){var d=document.createElement("iframe");d.src=b;d.style.width="30px";
d.style.height="10px";d.style.position="absolute";d.style.top="-1000px";d.style.left="-1000px";document.body?a.utils.DOM.appendToBody(d):a.utils.functions.invokeOnPageLoad(function(){a.utils.DOM.appendToBody(d)});return d};g.attributeEncode=function(a){return a.replace(/</g,"<").replace(/>/g,">").replace(/\"/g,""").replace(/\'/g,"'")}})(b.DOM||(b.DOM={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){function h(c){c=a.utils.object.clone(c);var b=function(){var b=c.data.split("="),f=d[b[0]];if(null!=f){if("function"==typeof f.callback){var l=unescape(b[1]),l=a.utils.keyValue.deserialize(l,null,null,!0);f.callback(l,f.context)}e(b[0]);(b=document.getElementById(b[0]))&&b.parentElement&&b.parentElement.removeChild(b)}};c&&c.data&&c.data.split&&(6<=a.localInfo.iosVersion?b():window.setTimeout(b,100))}function f(c){var d=document.createElement("iframe");d.style.width=
"30px";d.style.height="10px";d.style.position="absolute";d.style.top="-1000px";d.style.left="-1000px";d.id=c;d.src="https://cdns.gigya.com/gs/LocalStorageListener.htm?mode=receive&id="+encodeURIComponent(c);a.utils.DOM.appendToBody(d);return d}function e(a){delete d[a]}var d={};b._flashListenerID="flid"+(new Date).getTime();var c=!1,l={};b._onFlashMessage=function(c){c=a.utils.keyValue.deserialize(c,null,null,!0);var b=c.id,f=d[b];null!=f&&("function"==typeof f.callback&&f.callback(c,f.context),e(b))};
b.addMessageListener=function(e,q,k,m){d[e]={callback:m,context:q,t:(new Date).getTime()};q=a.localInfo.messagingMethod;a.localInfo.isIE11&&k&&window.indexedDB&&(q=a._.MessagingMethod.LocalStorageListener);if(q==a._.MessagingMethod.LocalStorageListener||q==a._.MessagingMethod.PostMessage)q==a._.MessagingMethod.LocalStorageListener&&k&&f(e),c||(e=function(a){if(a&&a.data&&"string"===typeof a.data){var c=a.data.split("=")[0];d[c]&&h(a)}},window.addEventListener?window.addEventListener("message",e,!1):
window.attachEvent&&window.attachEvent("onmessage",e),c=!0);else{var r="localstorage";a.thisScript.globalConf.legacyCrossSiteMethod&&"localstorage"!=a.thisScript.globalConf.legacyCrossSiteMethod.toLowerCase()&&(r=a.thisScript.globalConf.legacyCrossSiteMethod);l[r]||window.setTimeout(function(){var c=document.createElement("div");c.style.width="1px";c.style.height="1px";c.style.overflow="hidden";c.style.position="absolute";c.style.left="-1000px";var d=b._flashListenerID;"localstorage"!=r&&(d=r+":"+
b._flashListenerID);var e=document.location.protocol+"//"+document.location.href.split("?")[0].split("#")[0].split("/")[2],f=(new Date).getTime(),p=document.createElement("object");p.setAttribute("id","eventsBroadcaster"+f);p.setAttribute("codebase","https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0");p.setAttribute("width","50");p.setAttribute("height","50");p.setAttribute("src","https://cdns.gigya.com/GS/swf/eventsBroadcaster2.swf");p.setAttribute("data","https://cdns.gigya.com/GS/swf/eventsBroadcaster2.swf");
p.setAttribute("style","display:inline");f=document.createElement("param");f.name="movie";f.setAttribute("value","https://cdns.gigya.com/GS/swf/eventsBroadcaster2.swf");p.appendChild(f);f=document.createElement("param");f.setAttribute("name","allowScriptAccess");f.setAttribute("value","always");p.appendChild(f);f=document.createElement("param");f.setAttribute("name","FlashVars");f.setAttribute("value","action=listen&id="+d+"&eventName=loginComplete&callback=gigya.utils.xd._onFlashMessage&domain="+
e);p.appendChild(f);c.appendChild(p);a.utils.functions.invokeOnPageLoad(function(){a.utils.DOM.appendToBody(c);p.setAttribute("type","application/x-shockwave-flash");p.setAttribute("classid","clsid:d27cdb6e-ae6d-11cf-96b8-444553540000")});l[r]=!0},500)}};b.removeMessageListener=e})(b.xd||(b.xd={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(g){function h(a){return a.replace(/^http(s?):\/\/cdn(s?)[0-9]*.gigya.com\//,"http$1://cdn$2.gigya.com/")}function f(d,b,e,f,l,g){void 0===l&&(l=5E3);var t;if(f){f=h(d);if(c[f]){c[f].loaded?e&&e():(c[f].onLoad.push(e),c[f].onError.push(b));return}t=c[f]={loaded:!1,onLoad:[e],onError:[b]};g&&0<g.length&&a.utils.array.forEach(g,function(a){c[a]=t})}else t={loaded:!1,onLoad:[e],onError:[b]};b=function(){var b=document.createElement("script");b.async=!0;b.type="text/javascript";
b.charset="UTF-8";var e=!1,f=function(){if(!e){if(t.onLoad&&t.onLoad.length)for(var a=0;a<t.onLoad.length;a++)if("function"==typeof t.onLoad[a])t.onLoad[a]();t.loaded=!0;t.onError=t.onLoad=null;e=!0;!0===l&&(l=0);!1!==l&&setTimeout(function(){b.parentNode&&b.parentNode.removeChild(b)},l)}};b.onload=f;b.onreadystatechange=function(){"loaded"==this.readyState&&f()};b.onerror=function(){for(var a=0;a<t.onError.length;a++)if("function"==typeof t.onError[a])t.onError[a]();delete c[d]};var g=document.getElementsByTagName("head");
g&&0<g.length&&g[0].appendChild(b);g=function(){b.src=d};6<=a.localInfo.iosVersion?g():setTimeout(g,1)};a.localInfo.isIE?a.utils.functions.invokeOnPageLoad(b):b()}function e(a,c){var d=new Image,b=!1;d.onload=d.onerror=function(){b||(b=!0,c())};d.src=a}function d(c,d,e){void 0===e&&(e=5E3);var f=document.createElement("iframe");f.style.width="30px";f.style.height="10px";f.style.position="absolute";f.style.top="-1000px";f.style.left="-1000px";!0===e&&(e=0);var l=function(a){var c;c=a&&a.srcElement?
a.srcElement:a&&a.target?a.target:this;!c.loaded&&c.parentNode&&(c.loaded=!0,d(),!1!==e&&window.setTimeout(function(){try{document.body.removeChild(c)}catch(a){}},e))};b.DOM.addEventListener(f,"load",l);b.DOM.addEventListener(f,"error",l);f.onload=function(a){l(a)};f.onerror=l;f.src=c;a.utils.DOM.appendToBody(f)}var c={};g.isLoaded=function(a){a=h(a);return!(!c[a]||!c[a].loaded)};g.load=f;(function(a){a[a.script=0]="script";a[a.image=1]="image";a[a.iframe=2]="iframe"})(g.ResourceTypes||(g.ResourceTypes=
{}));var l=g.ResourceTypes;g.triggerResource=function(a,c,b,g){void 0===b&&(b=l.image);void 0===g&&(g=5E3);switch(b){case l.script:f(a,c,c,!1,g);break;case l.image:e(a,c);break;case l.iframe:d(a,c,g);break;default:throw Error("Unsupported resource type");}};g.loadService=function(c,d,b){var e=a._.getCdnResource()+"/js/gigya.services."+c+".js";f(e,function(){"object"==typeof console&&console.error&&(console.error("error loading gigya service "+c+" from url: "+e),d&&d())},b,!0)}})(b.script||(b.script=
{}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){var h;try{h=!!window.sessionStorage}catch(f){h=!1}b.set=function(b,d){if(h){var c;try{(c=a.utils.JSON.deserialize(window.sessionStorage.getItem("gigyaCache")))||(c={}),null==d&&c[b]?delete c[b]:c[b]={response:d,time:(new Date).getTime()},window.sessionStorage.setItem("gigyaCache",a.utils.JSON.serialize(c))}catch(f){}a.utils.queue.release("cache","cache_"+b)}};b.get=function(b,d,c){if(h)try{if(!a.utils.queue.isActive("cache_"+b)){var f=window.sessionStorage.getItem("gigyaCache"),
g=a.utils.JSON.deserialize(f),q=g?g[b]:null;if(q){if(d&&d+q.time>(new Date).getTime()){c(q.response);return}a.utils.sessionCache.remove(b);q=null}if(!q){a.utils.queue.hold("cache","cache_"+b);c(null);return}}a.utils.queue.isActive("cache_"+b)&&a.utils.queue.waitFor("cache_"+b,a.utils.sessionCache.get,arguments)}catch(k){c(null)}else"function"==typeof c&&c(null)};b.remove=function(b){a.utils.sessionCache.set(b,null)}})(b.sessionCache||(b.sessionCache={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){var h=navigator.userAgent.toLowerCase(),f=null;b.isModern=function(){return a.localInfo.isChrome||a.localInfo.isFF||a.localInfo.isOpera||a.localInfo.isIOSWebView||a.localInfo.isIE&&9<=a.utils.browser.getVersion()||a.localInfo.isEdge||a.localInfo.isSafari&&4<=a.utils.browser.getVersion()};b.getVersion=function(){if(f)return f;try{var a=h.match(/(opera|chrome|safari|firefox|msie|trident.*rv:)\/?\s*(\.?\d+(\.\d+)*)/i);if(a[2]){var d=a[2].split(".")[0];if(!isNaN(parseInt(d)))return f=
parseInt(d)}}catch(c){}return 0}})(b.browser||(b.browser={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(a){(function(a){function b(a){return a.replace(/([.*+?^=!:${}()|\[\]\/\\])/g,"\\$1")}a.trim=function(a){return a.replace(/^\s*(\S*(.*\S)?)\s*$/,"$1")};a.format=function(a){for(var b=1;b<arguments.length;b++);for(b=0;b<arguments.length-1;b++)null!=arguments[b+1]&&(a=a.split("{"+b+"}").join(arguments[b+1]));return a};a.capitalize=function(a){return a.substring(0,1).toUpperCase()+a.substring(1)};a.endsWith=function(a,b){return-1!==a.indexOf(b,a.length-b.length)};a.escapeRegExp=
b;a.replaceAll=function(a,e,d){return e?a.replace(new RegExp(b(e),"g"),d):a}})(a.stringUtils||(a.stringUtils={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){function h(a){if(!f[a])return!1;for(var d in f[a].ids)return!0;return!1}var f={};b._servicesStatus=function(){var a={},d;for(d in f)h(d)?a[d]={active:!0,waitingFor:f[d].ids,queuedCount:f[d].q.length}:a[d]={active:!1};return a};b.isActive=h;b.release=function(a,d){if(f[d]&&(delete f[d].ids[a],!h(d))){var c=f[d].q;for(f[d].q=[];0<c.length;){var b=c.splice(0,1)[0];try{b.func.apply(this,b.args)}catch(g){"object"==typeof console&&console.log&&console.log("Gigya: Exception while invoking queued method ("+
d+": "+a+")")}if(h(d)){f[d].q=c;break}}}};b.hold=function(a,d){f[d]||(f[d]={q:[],ids:{}});f[d].ids[a]=!0};b.waitFor=function(a,d,c){f[a]||(f[a]={q:[],ids:{}});f[a].q.push({func:d,args:c})};b.queueForExecution=function(b,d,c){c=c||[];a.utils.queue.isActive(b)?a.utils.queue.waitFor(b,d,c):d.apply(this,c)}})(b.queue||(b.queue={}))})(a.utils||(a.utils={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.redirect=function(b,f,e,d){if(e&&"post"==e.toLowerCase()){e=document.createElement("form");var c=[];e.setAttribute("accept-charset","UTF-8");e.setAttribute("method","POST");e.setAttribute("action",b);d&&e.setAttribute("target",d);b=a.utils.object.merge(f);for(var l in b)"boolean"!=typeof b[l]&&"string"!=typeof b[l]||"eventName"==l||c.push('<textarea name="'+encodeURIComponent(l)+'">'+b[l].toString().replace(/\&/g,"&")+"</textarea>");e.innerHTML=c.join("");
e.style.display="none";a.utils.DOM.appendToBody(e);e.submit()}else{e=b.split("?");b=e[0];d={};if(1<e.length)for(e=e[1].split("&"),c=0;c<e.length;c++){var g=e[c].split("=");d[decodeURIComponent(g[0])]=decodeURIComponent(g[1])}for(e=0;e<f.length;e++)for(l in c=f[e],c)"boolean"!=typeof c[l]&&"string"!=typeof c[l]||"eventName"==l||(d[l]=c[l]);f=[];for(l in d)f.push(l+"="+encodeURIComponent(d[l]));document.location.href=b+"?"+f.join("&")}}})(b.HTTP||(b.HTTP={}))})(a.utils||(a.utils={}))})(gigya||(gigya=
{}));(function(a){a.socialize={};a.gcs={};a.gm={};a.comments={};a.accounts={};a.chat={};a.gscounters={}})(gigya||(gigya={}));
(function(a){(function(b){function g(c){var d,b=a.localInfo.protocol;"cdn.gigya.com"==a.thisScript.baseDomain||"cdns.gigya.com"==a.thisScript.baseDomain?(d=e[b],d.length<=f&&(f=0),d=d[f++]):d=a.thisScript.baseDomain;return b+"://"+d+(c?c:"")}var h={};b.getApi=function(a){return h[a]};var f=0,e={http:["cdn.gigya.com","cdn1.gigya.com","cdn2.gigya.com","cdn3.gigya.com"],https:["cdns.gigya.com","cdns1.gigya.com","cdns2.gigya.com","cdns3.gigya.com"]};b.getCdnResource=g;b.getImgCdnResource=function(){return g("/gs/i/")};
var d=function(){function c(a,c){this.methodName=a;this.settings=c;this.addAlias();h[a]=this}c.prototype.run=function(a){};c.prototype.preprocessRequest=function(a,c){this.settings.preprocessor?this.settings.preprocessor(a,c):c()};c.prototype.addAlias=function(){var c=this;a.utils.functions.createAlias("gigya."+this.methodName,function(){for(var d=[],b=0;b<arguments.length;b++)d[b-0]=arguments[b];var b=function(){var d=a.utils.object.merge([a.thisScript.globalConf,e]);c.run(d)},e=a.utils.object.merge([d]);
a.thisScript&&a.thisScript.globalConf?b():a.utils.queue.queueForExecution("API",b)})};return c}();b.BaseApi=d})(a._||(a._={}))})(gigya||(gigya={}));(function(a){a.defaultEventMaps=a.defaultEventMaps||[]})(gigya||(gigya={}));
(function(a){(function(b){function g(a){return"on"===a.substring(0,2)?a:"on"+a.substring(0,1).toUpperCase()+a.substring(1)}function h(b,e){var d;try{"function"==typeof b?d=b(e):b instanceof Array?a.utils.array.forEach(b,function(c){"function"==typeof c?c(e):a.log.addLog("Not a function registered to event: "+c,c)}):a.log.addLog("Not a function or function array registered to event",b)}catch(c){a.log.addLog("Error invoking function registered to event",b)}return d}(function(b){function e(c,b,d,e){var f=
function(c){var d=0;c.cancel||(d=a.events.global.dispatch(c,b));e&&e(d)};d?d(c,f):f(c)}var d={},c={};b._activeNamespaces={};b.add=function(b,f,h,k,m,r){void 0===h&&(h="other");void 0===m&&(m="socialize");b=m+"_"+g(b);d[b]||(d[b]=[]);f={handler:f,type:h,context:k,params:r,fullEventName:b};d[b].push(f);!this._activeNamespaces[m]&&a._.apiAdapter&&a._.apiAdapter.registerForNamespaceEvents(m);this._activeNamespaces[m]=1;if((m=c[b])&&"other"==h)for(c[b]=[],h=0;h<m.length;h++)b=m[h],e(b.eventObj,b.params,
b.preProcess);return f};b.remove=function(c,b){d[c]&&a.utils.array.removeByValue(d[c],b)};b.dispatch=function(c,b){var e=0,f=c.isInternal,h=c.eventName.split(",");a.log.addLog('Dispatching global event "'+c.eventName+'" with this event object',c);for(var r=0;r<h.length;r++){var n=h[r].split("."),t=1<n.length?n.shift():"socialize",u=n[0],n=g(u),v=a.utils.object.clone(d[t+"_"+n]);v||(v=[]);n=a.utils.object.clone(c);n.isGlobal=!0;n.eventName=u;b&&(b.source&&(n.source=b.source),b.sourceData&&(n.sourceData=
b.sourceData),b.context&&(n.context=b.context));u=["component"];f||u.push("other");for(var w=0;w<u.length;w++)for(var A=u[w],x=0;x<v.length;x++){var z=v[x];if(z.type==A){var y=a.utils.object.clone(n);null==y.context&&null!=z.context&&(y.context=z.context);null==y.context&&delete y.context;"component"!=A&&(e++,a._.handleSpecialFields(y));z.params&&z.params.signKey&&(y.UIDSignature=c.signKeysUIDSignature[z.params.signKey],delete y.signKeysUIDSignature);try{z.handler(y)}catch(B){a.log.addLog('Error while trying to invoke "'+
c.eventName+'" global event handler',B)}}}f||a.events._dispatchFromMaps(n,!0);v=window.GenesisExchange_Gigya;u=window.gigya_omniture_conf;w=window.myOmnitureIntegrationFunc;f||"undefined"==typeof v||"undefined"==typeof u||"socialize"!=t||((new v(u)).processAction(n),"undefined"!=typeof w&&w(u,n))}return e};b.dispatchWhenHandlerAdded=function(a,b,d){void 0===b&&(b={});var f=a.eventName.split("."),g=1<f.length?f.shift():"socialize",h=f[0];e(a,b,d,function(e){0==e&&(e="on"+h.substring(0,1).toUpperCase()+
h.substring(1),e=g+"_"+e,c[e]||(c[e]=[]),c[e].push({eventObj:a,params:b,preProcess:d}))})};b.getEventsForOperation=function(a){var c=[];-1!=a.toLowerCase().indexOf("login")?(this._activeNamespaces.socialize&&c.push("socialize.login"),this._activeNamespaces.accounts&&c.push("accounts.login")):-1!=a.toLowerCase().indexOf("addconnection")&&this._activeNamespaces.socialize&&c.push("socialize.connectionAdded");return c.join(",")}})(b.global||(b.global={}));b.addMap=function(b){a.defaultEventMaps.splice(0,
0,b)};b.dispatchErrorFromResponse=function(b,e,d){e||(e={});var c=e;c.response&&(c=c.response);e={eventName:"error",status:c.status?c.status:"FAIL",statusMessage:c.statusMessage?c.statusMessage:"General Server Error",errorMessage:c.errorMessage?c.errorMessage:"General Server Error",errorDetails:c.errorDetails?c.errorDetails:"",errorCode:c.errorCode?c.errorCode:500001,response:e};a.utils.object.add(e,d);a.events.dispatchForWidget(e,b)};b.dispatchInvalidParamError=function(b,e){var d={eventName:"error"};
"undefined"==typeof b[e]||null==b[e]?(d.errorCode=400002,d.errorMessage="Missing_required_parameter ("+e+")"):(d.errorCode=400006,d.errorMessage="Invalid_parameter_value ("+e+")");d.status=d.errorCode;d.statusMessage=d.errorMessage;a.events.dispatchForWidget(d,b)};b.dispatchForWidget=function(b,e){if(b&&b.eventName){var d=b.eventName;a.log.addLog('Dispatching widget event "'+d+'" for '+e.lastSource+" with this event object",b);a._.handleSpecialFields(b);for(var c=d.split(","),l,p=0;p<c.length;p++){var d=
c[p],q=g(d);e&&(e.context&&(b.context=e.context),e.source&&(b.source=e.source),e.sourceData&&(b.sourceData=e.sourceData),e.containerID&&(b.sourceContainerID=e.containerID),e.instanceID&&(b.instanceID=e.instanceID));e[q]&&(l=h(e[q],b));"undefined"===typeof l&&(l=!0);if(-1==d.indexOf("login")&&-1==d.indexOf("logout")&&"connectionRemoved"!=d&&"connectionAdded"!=d){this._dispatchFromMaps(b);var d=window.GenesisExchange_Gigya,q=window.gigya_omniture_conf,k=window.myOmnitureIntegrationFunc;"undefined"!=
typeof d&&"undefined"!=typeof q&&((new d(q)).processAction(b),"undefined"!=typeof k&&k(q,b))}}return l}};b.dispatchEventObject=h;b._dispatchFromMaps=function(b,e){for(var d=[],c=!1,g=0;g<a.defaultEventMaps.length;g++){for(var h=a.defaultEventMaps[g].eventMap,q=a.defaultEventMaps[g].defaultMethod,k=0;k<h.length;k++){var m=h[k],r=[];m.args||(m.args=[]);for(var n=0;n<m.args.length;n++)"$event"==m.args[n]?r.push(b):r.push(a.utils.templates.fill(m.args[n],b));m.events.split(",");n=","+m.events.toLowerCase()+
",";-1==n.indexOf(",*,")&&(-1==n.indexOf(",on"+b.eventName.toLowerCase()+",")&&-1==n.indexOf(","+b.eventName.toLowerCase()+",")||(b.source||m.sources)&&m.sources&&-1==m.sources.indexOf(b.source))||(d.push(m),(m.method?m.method:q).apply(this,r),m.override&&(c=!0))}if(c)break}}})(a.events||(a.events={}))})(gigya||(gigya={}));var __extends=this&&this.__extends||function(a,b){function g(){this.constructor=a}for(var h in b)b.hasOwnProperty(h)&&(a[h]=b[h]);g.prototype=b.prototype;a.prototype=new g};
(function(a){(function(b){b.apiAdapter;var g=function(g){function f(a,b,c,f,p,q){void 0===f&&(f={});void 0===p&&(p={});g.call(this,a,f);this.schema=b;this.requiresSession=c;this.settings=f;this.adapterSettings=p;this.altSessionParams=q;"undefined"===typeof p.requiresSession&&(p.requiresSession=function(){return c})}__extends(f,g);f.prototype.run=function(e){var d=this,c=function(){g.prototype.run.call(d,e);(new b.ServerApiRequest(d,e)).start()};e.ignoreApiQueue?c():a.utils.queue.queueForExecution("API",
function(){c()})};return f}(b.BaseApi);b.ServerApi=g})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){function g(a){return{status:"OK",statusMessage:"",errorCode:0,statusCode:0,errorMessage:"",errorDetails:"",statusReason:"",originalResponse:a}}var h;a.events.global.add("onFBCRefreshed",function(){h=!1},"component");var f;(function(a){a[a._unknown=0]="_unknown";a[a.facebook=1]="facebook";a[a.yahoo=2]="yahoo";a[a.googleplus=3]="googleplus";a[a.linkedin=4]="linkedin";a[a.samlProvider=5]="samlProvider";a[a.samlSession=6]="samlSession"})(f||(f={}));var e=function(){function d(c,
b){this.api=c;this.params=a.utils.object.merge([a.utils.object.clone(b),c.settings.defaultParams]);this.originalParams=a.utils.object.clone(b);this.callback=b.callback}d.prototype.start=function(){var c=this;b.apiAdapter.isSessionValid(this.params,function(b){!c.api.adapterSettings.requiresSession()||b||c.doesHaveAltSessionParam()?c.sendRequest(b):c.afterServerApiResponse(a.utils.object.clone({status:"FAIL",errorMessage:"Unauthorized user",statusMessage:"Unauthorized user",errorCode:403005}),!1)})};
d.prototype.sendRequest=function(c){var d=this,e=a.utils.object.merge([this.api.adapterSettings,{cacheTimeout:this.params.cacheTimeout}]);this.beforeRequest(c,function(f){f?d.afterServerApiResponse(f,c):(a.events.global.dispatch({eventName:"beforeRequest",methodName:d.api.methodName,rawParams:d.originalParams,params:d.params},d.originalParams),d.api.settings.oauth?b.apiAdapter.sendOauthRequest(d.api.methodName,d.params,function(a){d.afterServerApiResponse(a,c)},e):b.apiAdapter.sendRequest(d.api.methodName,
d.params,function(a){d.afterServerApiResponse(a,c)},e))})};d.prototype.beforeRequest=function(c,d){var e=this;a.external.backplane.isLoaded()&&!a.external.backplane._ready&&b.loginMethods[this.api.methodName]?a.external.backplane.executeOnInit(function(){e.beforeRequest(c,d)}):(a._.logoutMethods[this.api.methodName]&&(!c&&!this.params.regToken||a.partnerSettings.ssoLogoutUrl&&document.location.href==a.partnerSettings.ssoLogoutUrl)&&d(g(null)),this.handleDeprecatedParams(),this.handleCollections(),
this.handleConnectWithoutLoginBehavior(c),this.params.extraPermissions=this.params[this.params.provider+"ExtraPermissions"]||this.params.permissions,this.api.preprocessRequest(this.params,function(){e.setOverridableParams(function(){e.setNonOverridableParams(c,function(){e.filterParams(e.params);a.log.logCall(e.api.methodName,e.originalParams,e.originalParams.lastSource);d()})})}))};d.prototype.setOverridableParams=function(c){a.utils.object.merge([{},this.params]);c()};d.prototype.doesHaveAltSessionParam=
function(){if(this.api.altSessionParams){for(var a=this.api.altSessionParams.split("|"),b=0;b<a.length;b++)if(this.params[a[b]])return!0;return!1}};d.prototype.setNonOverridableParams=function(c,d){if(null!=this.params.APIKey){var e=a.utils.cookie.get("gltexp_"+this.params.APIKey);null!=e&&(this.params.loginTokenExp=e)}(e=a.utils.cookie.get("_gigRefUid_"+this.params.APIKey))&&(c||b.loginMethods[this.api.methodName])&&(this.params.refUID=e);if(a.providersConfig.facebook&&!h){var e=a.external.facebook.getParams(),
f;for(f in e)this.params[f]=e[f];h=!0}0==this.api.methodName.indexOf("accounts.")&&(a.events.global._activeNamespaces.socialize&&null==this.params.includeUserInfo&&(this.params.includeUserInfo=!0),this.params.include=this.params.include?this.params.include+",":"profile,data");"accounts.getSchema"==this.api.methodName&&(this.params.includeDynamicSchema="clientOnly");(f=a.external.backplane.getChannelId())&&(this.params.bp_channel_url=f);this.params.targetEnv="jssdk";d()};d.prototype.handleDeprecatedParams=
function(){this.params.pendingRegistration?this.params.pending_registration=this.params.pendingRegistration:this.params.newUsersPendingRegistration&&(this.params.pending_registration=this.params.newUsersPendingRegistration);1==this.params.alwaysForceAuthentication&&(this.params.forceAuthentication=!0);this.params.timestamp&&(this.params.UIDTimestamp=this.params.timestamp,delete this.params.timestamp);this.params.signature&&0==this.api.methodName.indexOf("socialize.")&&(this.params.UIDSig=this.params.signature,
delete this.params.signature);this.params.nonce&&(this.params.UIDNonce=this.params.nonce,delete this.params.nonce);this.params.format&&!this.params.dataFormat&&(this.params.dataFormat=this.params.format,delete this.params.format)};d.prototype.handleCollections=function(){this.params.recipients&&(this.params.recipients=this.extractListOfGIGUIDs(this.params.recipients));if(this.params.friends){var a=this.extractListOfGIGUIDs(this.params.friends);0<this.params.UIDs.length&&(this.params.UIDs+=",");this.params.UIDs+=
a}};d.prototype.extractListOfGIGUIDs=function(c){var b=this;switch(typeof c){case "string":return c;case "object":if("undefined"!=typeof c.UID)return c.UID;if(c instanceof a.socialize.Collection){var d=[];c.each(function(a,c){var e=b.extractListOfGIGUIDs(a);null!=e&&""!=e&&d.push(e)});return d.join(",")}}};d.prototype.handleConnectWithoutLoginBehavior=function(a){if("socialize.addConnection"==this.api.methodName){var d=this.params.connectWithoutLoginBehavior;d&&(d=d.toLowerCase());"loginexistinguser"==
d&&(this.params.loginIfExists=!0);a||(this.api=b.getApi("socialize.login"),"alwayslogin"!=d&&(this.params.temporary_account=!0))}};d.prototype.filterParams=function(c){this.params=a.utils.object.extractProperties(c,{},this.getFullSchema())};d.prototype.getFullSchema=function(){if(null==this.api.schema)return"";for(var c=(this.api.schema+"|"+a._.defaultApiSchema).split("|"),b=0;b<c.length;b++){var d=c[b];if(-1!=d.toLowerCase().indexOf("[providercapability=")){for(var e=d.toLowerCase().split("=")[1].split("]")[0],
d=d.split("]")[1],e=a.socialize.getProvidersForRequiredCapabilities(a.socialize.getProvidersByName("*"),[e]),f=[],g=0;g<e.length;g++)f.push(e[g].name+d);c[b]=f.join("|")}}return c.join("|")};d.prototype.preprocessServerResponse=function(c){c.userInfo&&0!=this.api.methodName.indexOf("accounts.")&&("string"==typeof c.userInfo&&(c.userInfo=a.utils.JSON.deserialize(c.userInfo)),c.userInfo&&(c=a.utils.object.merge([c.userInfo,c]),c.errorCode=c.userInfo.errorCode,delete c.userInfo));c.accountInfo&&"string"==
typeof c.accountInfo&&(c.accountInfo=a.utils.JSON.deserialize(c.accountInfo),c.accountInfo&&(c=a.utils.object.merge([c.accountInfo,c]),delete c.accountInfo));try{c.settings&&"string"==typeof c.settings&&(c.settings=a.utils.JSON.deserialize(c.settings))}catch(b){}return c};d.prototype.onAfterLogoutMethod=function(){a.external.backplane.resetChannel()};d.prototype.getExpiredSessionResponse=function(a){switch(this.api.methodName){case "socialize.setUserSettings":this.originalParams.disableLocalSettings||
(b.setGigyaSettings(this.params.group,this.params.settings),a=g(a));break;case "socialize.delUserSettings":this.originalParams.disableLocalSettings||(b.delGigyaSettings(this.params.group,this.params.settings),a=g(a));break;case "socialize.getUserSettings":if(!this.originalParams.disableLocalSettings){var d=b.getGigyaSettings(this.params.group);a=g(a);a.settings=d}break;case "socialize.getUserInfo":a.status="OK";a.statusMessage="";a.errorCode=0;a.statusCode=0;a.errorMessage="";a.errorDetails="";a.statusReason=
"";break;case "accounts.logout":case "socialize.logout":a=g(a)}return a};d.prototype.afterServerApiResponse=function(c,d){var e=this;b.checkCompleteRegistration(c,this.originalParams,function(f,g,h){c=f;c=e.preprocessServerResponse(c);if(b.logoutMethods[e.api.methodName]&&0==c.errorCode&&c.logoutActiveSession)e.onAfterLogoutMethod();403005==c.errorCode&&(c=e.getExpiredSessionResponse(c));0==c.errorCode&&(d||b.loginMethods[e.api.methodName])&&a.utils.cookie.remove("_gigRefUid_"+e.originalParams.APIKey);
e.handleMethodResponse(c,function(f){c=f;e.addDefaultResponseProperties(c);b.handleSpecialFields(c);e.logoutFromProvidersIfNeeded(c,function(b){b?e.sendRequest(d):(g||e.generateEventsFromResponse(c,d),h?e.sendRequest(d):(a.events.global.dispatch({eventName:"afterResponse",methodName:e.api.methodName,filteredParams:e.params,response:c},e.originalParams),"function"==typeof e.callback&&(a.log.addLog("Calling callback for "+e.api.methodName+" with this response object",c),e.callback(c)),e.api.settings.postprocessor&&
e.api.settings.postprocessor(e.originalParams,c)))})})})};d.prototype.addDefaultResponseProperties=function(a){delete a.statusCode;delete a.statusReason;a.errorCode=a.errorCode||0;a.status=a.status||(0==a.errorCode?"OK":"FAIL");a.errorMessage=a.errorMessage||"";a.statusMessage=a.statusMessage||a.errorMessage;a.requestParams=this.originalParams;a.requestParams.password&&delete a.requestParams.password;a.context=this.originalParams.context;var b=this.api.methodName.split(".")[0];a.operation="socialize"==
b?this.api.methodName.split(".")[1]:"/"+this.api.methodName};d.prototype.handleMethodResponse=function(c,d){if(0==c.errorCode)switch(this.api.methodName){case "accounts.socialLogin":case "socialize.login":c.newUser=c.x_newUser?!0:!1,delete c.x_newUser;case "socialize.notifyLogin":case "socialize.addConnection":case "accounts.linkAccounts":case "accounts.finalizeRegistration":case "accounts.login":case "accounts.register":case "socialize.getUserInfo":delete c.login_token;delete c.expires_in;delete c.id;
c.code&&(c.authCode=c.code,delete c.code);if(!(c.authCode||"socialize.notifyLogin"==this.api.methodName&&this.params.authCode)){var e=c;c.userInfo&&(e=c.userInfo,delete c.userInfo);-1==this.api.methodName.indexOf("accounts.")?(c={user:e},a.utils.object.extractProperties(e,c,"status|statusMessage|callId|errorCode|errorMessage|errorDetails|settings|context|UIDSig|timestamp|UIDSignature|signatureTimestamp|UID|profile|data|newUser|signKeysUIDSignature"),c.user.hasOwnProperty("UIDSig")&&(c.signature=c.user.UIDSig),
e.profile&&delete e.profile,e.data&&delete e.data,delete e.status,delete e.statusMessage,delete e.callId,delete e.errorCode,delete e.errorMessage,delete e.errorDetails,delete e.settings,delete e.context):c!=e&&(c.user=e);""==e.age||isNaN(parseInt(e.age))||(e.age=parseInt(e.age));e.suppressEvents&&(c.suppressEvents=!0);if("string"==typeof e.capabilities){var f=e.capabilities;f||(f="");"object"!=typeof e.capabilities&&(e.capabilities={});f=f.toLowerCase();e.capabilities={actions:-1<f.indexOf("actions"),
friends:-1<f.indexOf("friends"),login:-1<f.indexOf("login"),status:-1<f.indexOf("status"),notifications:-1<f.indexOf("notifications"),contacts:-1<f.indexOf("contacts"),photos:-1<f.indexOf("photos")}}b.convertIdentitiesArrayToObject(e);"string"==typeof e.providers&&(e.providers=e.providers.split(","));this.params.group&&!c.settings&&(e=b.getGigyaSettings(this.params.group),c.settings=e)}break;case "socialize.getAvailableProviders":e={};for(f=0;f<c.availableProviders.length;f++)e[c.availableProviders[f].name]=
c.availableProviders[f];c.availableProviders=e}"socialize.removeConnection"==this.api.methodName&&0==c.errorCode?a.socialize.getUserInfo(this.originalParams,{callback:function(a){d(a)}}):d(c)};d.prototype.logoutFromProvidersIfNeeded=function(c,d){var e=c.errorCode;if(b.logoutMethods[this.api.methodName]&&0===e){c.logoutActiveSession&&a._.apiAdapter.clearSession(this.params.APIKey);var g=[],e=5E3,h=0,m;c.connectedProviders?m=c.connectedProviders.toLowerCase():c.provider&&(m=c.provider.toLowerCase());
if(m&&!a.utils.validation.isExplicitFalse(this.originalParams.forceProvidersLogout)){var r=m.split(",");for(m=0;m<r.length;++m){var n=r[m],t=f[n],u=null,v=5E3;0===n.indexOf("saml-")&&(t=f.samlProvider,u=n.substring(5),v=!1,e=1E4,h=5E3);g.push({type:t,data:u,removeAfter:v})}}if(c.samlContext&&c.connectedSamlSessions)for(r=c.samlContext,n=c.connectedSamlSessions.split(","),m=0;m<n.length;++m)g.push({type:f.samlSession,data:{samlContext:r,samlSession:n[m]},removeAfter:!1}),e=1E4,h=5E3;if(g.length){var w=
0,A=!1,x=function(){A||(A=!0,d(!1))};window.setTimeout(x,e);e=function(){w++;w==g.length&&window.setTimeout(x,h)};for(m=0;m<g.length;m++)this.logoutFromProvider(g[m],e)}else d(!1)}else 403013==c.errorCode&&"accounts.verifyLogin"!=this.api.methodName?a.accounts.verifyLogin({callback:function(a){0==a.errorCode?d(!0):d(!1)}}):d(!1)};d.prototype.logoutFromProvider=function(b,d){var e="",g=!1,h=!0,m;m=a.partnerSettings.customAPIDomainPrefix?a.partnerSettings.customAPIDomainPrefix+"."+a.partnerSettings.baseDomain:
"fidm."+a.partnerSettings.plugins.apiDomain;switch(b.type){case f.facebook:if(a.providersConfig.facebook){a.socialize.waitForService({service:"facebook",callback:function(){a.external.facebook.isLoggedIn&&FB.logout?FB.logout(function(){a.external.facebook.refreshSession();d()}):d()}});return}break;case f.yahoo:e="https://login.yahoo.com/config/login?.src=fpctx&logout=1&r=";break;case f.googleplus:e="https://accounts.google.com/logout";h=!1;break;case f.samlProvider:e=a.utils.URL.addParamsToURL("https://"+
m+"/saml/v2.0/"+this.params.APIKey+"/sp/jsslo",{name:b.data});g=!0;h=!1;break;case f.samlSession:e=a.utils.URL.addParamsToURL("https://"+m+"/saml/v2.0/"+this.params.APIKey+"/idp/slo/continue/",b.data),g=!0,h=!1}e?(h&&(e+=(new Date).getTime()),a.utils.script.triggerResource(e,d,g?a.utils.script.ResourceTypes.iframe:a.utils.script.ResourceTypes.image,b.removeAfter)):d()};d.prototype.generateEventsFromResponse=function(c,d){var e=this,f;if(0==c.errorCode)switch(this.api.methodName){case "accounts.logout":case "socialize.logout":case "socialize.unlinkAccounts":case "socialize.deleteAccount":f=
{eventName:"logout,accounts.logout"};break;case "socialize.linkAccounts":case "socialize.setUID":b.addUserInfoToEvent(c,f,!0);break;case "socialize.removeConnection":f={eventName:"connectionRemoved,disconnect",provider:this.params.provider||""};b.addUserInfoToEvent(c,f);break;case "socialize.addConnection":!d&&c.user.isLoggedIn?(f={eventName:"login",provider:this.params.provider},b.addUserInfoToEvent(c,f,!0)):(f={eventName:"connectionAdded,connect",provider:this.params.provider},b.addUserInfoToEvent(c,
f));break;case "accounts.linkAccounts":case "accounts.finalizeRegistration":case "accounts.login":case "accounts.register":case "accounts.socialLogin":this.dispatchAccountsLoginEvent(c);case "socialize.finalizeRegistration":case "socialize.register":case "socialize.login":if(!c.user&&!c.authCode)break;f={eventName:"login"};var g=this.params.provider;if(!g&&c.providerSessions)for(var h in c.providerSessions){g=h;break}f.provider=g||"site";f.loginMode=this.originalParams.loginMode||"standard";f.newUser=
c.newUser||!1;c.authCode&&(f.authCode=c.authCode);b.addUserInfoToEvent(c,f,!0);c.user&&g&&(g=g.toLowerCase(),a.utils.cookie.set("_gig_llp",g),a.utils.cookie.set("_gig_llu",c.user.firstName||""));break;case "socialize.notifyLogin":this.params.authCode||(f||(f={eventName:"login"}),f.provider="site",b.addUserInfoToEvent(c,f,!0));break;case "gm.notifyAction":a.events.global.dispatch({eventName:"actionNotified",isInternal:!0})}b.loginMethods[this.api.methodName]&&this.originalParams.redirectURL&&f&&f.user&&
0==c.errorCode&&a.utils.HTTP.redirect(this.originalParams.redirectURL,[f,f.user],this.originalParams.redirectMethod);0==c.errorCode&&f&&"login"==f.eventName&&!c.profile&&a.events.global._activeNamespaces.accounts&&-1==this.api.methodName.indexOf("accounts")&&a.accounts.getAccountInfo(this.originalParams,{include:"profile,data",includeUserInfo:!1,callback:function(a){e.dispatchAccountsLoginEvent(a)}});null!=f&&(f.context=this.originalParams.context,a.events.global.dispatch(f,this.originalParams))};
d.prototype.dispatchAccountsLoginEvent=function(b){var d={eventName:"accounts.login",remember:a.utils.validation.isExplicitTrue(this.originalParams.remember),provider:this.originalParams.provider?this.originalParams.provider.toLowerCase():"",loginMode:this.originalParams.loginMode||"standard"};a.utils.object.extractProperties(b,d,"newUser|signature|UIDSig|timestamp|UIDSignature|signatureTimestamp|UID|profile|data|signKeysUIDSignature");a.events.global.dispatch(d,this.originalParams)};return d}();
b.ServerApiRequest=e})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){b.__pluginsCoreLoaded=!1;var g={showReactionsBarUI:["barID"],showCommentsUI:["categoryID","streamID"],showFeedUI:["feedID"],showChatUI:["configID","streamID","chatID"]},h=function(f){function e(a,b,g,h,q,k){void 0===g&&(g={});void 0===h&&(h={});void 0===q&&(q="");void 0===k&&(k={});f.call(this,e.getApiName(b,a,k),k);this.methodName=a;this.jsName=b;this.settings=k;k.defaultParams=g||{};k.defaultPopupParams=h||{};k.requiredParams=q||""}__extends(e,f);e.getApiName=function(a,
b,e){void 0===e&&(e={});return e.apiName||a.split(".")[0]+"."+b};e.versionSelector=function(d,c,e,f,g){void 0===g&&(g="version");var h=new b.api.VersionSelector(d,f,e);a.utils.functions.createAlias("gigya."+c+"."+d,function(){for(var b=[],c=0;c<arguments.length;c++)b[c-0]=arguments[c];var d=b[0],c=b[1];c||(c=d,d=null);c||(c={},b.push(c));d=a.utils.object.merge([{},d,c]);h.callVersion(""+d[g],c,b)});return h};e.createApi=function(a,b,f,g,h,k){void 0===h&&(h={});h.useBasePlugin=!0;a=new e(a,g,null,
null,null,h);a.namespace=b;a.className=f;a.instanceMethods=k||[];a.addInstanceMethodsAliases();return a};e.prototype.addInstanceMethodsAliases=function(){for(var a=0;a<this.instanceMethods.length;a++)this.createInstanceMethodAlias(this.instanceMethods[a])};e.prototype.createInstanceMethodAlias=function(d){var c=this;a.utils.functions.createAlias("gigya."+this.namespace+"."+d,function(e){if(c.injectionInfo){var f=c.getPublicMethod(d),g=b.plugins.getPluginInstance(e,c.injectionInfo);if(g){var h=[];
a.utils.array.forEach(f.argNames,function(a){a&&void 0!==e[a]&&h.push(e[a])});g[f.instanceMethod].apply(g,h)}else a.log.addLog("couldn't find instance",c,!1)}else a.log.addLog("invalid injection info",c,!1)})};e.prototype.getPublicMethod=function(a){var b;this.injectionInfo.publicMethods&&(b=this.injectionInfo.publicMethods[a]);if(!b)throw Error("public method "+a+" is not configured for "+this.injectionInfo.name);return b};e.prototype.preprocessRequest=function(a,b){var e=this;f.prototype.preprocessRequest.call(this,
a,function(){a.source||e.setSourceData(a);b&&b()})};e.prototype.run=function(b){var c=this;!this.settings.waitForAPIQueue||b.ignoreApiQueue?this.startUI(b):a.utils.queue.queueForExecution("API",function(){c.startUI(b)})};e.prototype.startUI=function(b){var c=this;f.prototype.run.call(this,b);b=a.utils.object.clone(b);this.prepareParameters(b);this.preprocessRequest(b,function(){c.settings.useBasePlugin?c.loadPluginJS(b,function(e){a.utils.queue.queueForExecution("UI",function(){e&&c.className&&(c.pluginType=
eval("gigya._.plugins."+c.className),c.injectionInfo=c.pluginType.injectionInfo(c));var f=function(){c.startPlugin(b)};0==b.waitForDebug?f():a.utils.queue.queueForExecution("debug",f)})}):c.legacyStartUI(b)})};e.prototype.startPlugin=function(d){var c=this;a.events.global.dispatch({eventName:"beforePluginRequest",methodName:this.methodName,params:d},d);var e=d.originalMethodName||this.methodName;a.log.logCall(e,d);a.reports.reportLoad(e,d);if(this.pluginType){d&&(e=b.plugins.getPluginInstance(d,this.injectionInfo))&&
e.dispose&&!d._allowMultipleInstances&&!d.newModal&&e.dispose();e=new this.pluginType(d,this.injectionInfo);b.plugins.setPluginInstance(d,this.injectionInfo,e);e.onDisposedEvent().add(function(){return b.plugins.removePluginInstance(d,c.injectionInfo)});e.start();if(e.containerID){var f=document.getElementById(e.containerID);f&&(f.gigyaPluginInstance=e)}d.getInstance&&d.getInstance(e)}else a.utils.functions.callFunction("gigya."+this.jsName+"."+this.methodName,[d,d,d])};e.prototype.loadPluginJS=function(d,
c){if(this.wasPluginJSLoaded(d))c&&c(!1);else{var e=!1,f=a._.getCdnResource("/js/"),g="gigya.services."+this.jsName,h=f+g+".min.js"+(d.lang?"?lang="+d.lang:""),f=f+"gigya.services.plugins.base.min.js?services="+g+(d.lang?"&lang="+d.lang:"");b.__pluginsCoreLoaded?g=h:(g=f,e=b.__pluginsCoreLoaded=!0,a.utils.queue.hold("pluginsJS","UI"));a.utils.script.load(g,null,function(){e&&a.utils.queue.release("pluginsJS","UI");c&&c(!0)},!0,void 0,[h,f])}};e.prototype.wasPluginJSLoaded=function(b){var c="gigya."+
this.jsName+"."+this.methodName,e="gigya.services."+this.jsName+".js";try{var f=eval(c),g=a.i18n[e][b.lang]}catch(h){return!1}return"undefined"!=typeof f&&"undefined"!=typeof g};e.prototype.setSourceData=function(a){a.source="socialize.showSimpleShareUI"==this.methodName?"socialize.showShareUI":a.originalMethodName||this.methodName;if(!a.sourceData&&g[this.methodName]){for(var b={},e,f=0;f<g[this.methodName].length;f++){var h=g[this.methodName][f];null!=a[h]&&(e=!0,b[h]=a[h])}e&&(a.sourceData=b)}a.pluginsStack||
(a.pluginsStack=[]);a.pluginsStack.push({source:this.methodName});a.lastSource=this.methodName};e.prototype.validateRequiredParams=function(b){for(var c=this.settings.requiredParams.split("|"),e=0;e<c.length;e++){var f=c[e];if(""!=f&&(null==b[f]||""==b[f]))return a.events.dispatchInvalidParamError(b,f),!1}return!0};e.prototype.setDefaultParams=function(a){var b=!a.containerID||a.isPopup,e;for(e in this.settings.defaultParams)null==a[e]&&(a[e]=b&&this.settings.defaultPopupParams[e]?this.settings.defaultPopupParams[e]:
this.settings.defaultParams[e]);if(b)for(e in this.settings.defaultPopupParams)a[e]||(a[e]=this.settings.defaultParams[e])};e.prototype.prepareParameters=function(b){for(var c in b)-1!=c.toLowerCase().indexOf("provider")&&"string"==typeof b[c]&&(b[c]=a._.providers.replaceProviderAliases(b[c]));b.lang||(b.lang=a.thisScript.lang.langCode);b.source?b.isPopup=!1:this.setSourceData(b)};e.prototype.legacyStartUI=function(b){var c=this,e=b.containerID;if(this.settings.ignoreContainerId)e=b.containerID="";
else if(null==b.containerID&&!this.settings.allowPopup||b.containerID&&!document.getElementById(b.containerID)){a.events.dispatchInvalidParamError(b,"containerID");return}var f=this.settings.allowPopup&&(!e||b.isPopup);f&&this.settings.useNewModal&&(b.useNewModal=!0);this.setDefaultParams(b);this.settings.allowPopup||f||a.utils.DOM.clearByID(e);this.validateRequiredParams(b)&&this.loadPluginJS(b,function(){var e=function(){c.prepareContainer(b,f,function(){c.startPlugin(b)})};a.utils.queue.queueForExecution("UI",
function(){0==b.waitForDebug?e():a.utils.queue.queueForExecution("debug",e)})})};e.prototype.prepareContainer=function(b,c,e){var f=this;if(document.body){var g=b.containerID,h;c&&(g=a.utils.DOM.getCenteredDivID(this.methodName),b.newModal&&(g+=(new Date).getTime()),b.containerID=g,b.isPopup=!0,document.getElementById(g)||(h=a.utils.DOM.createTopLevelDiv(g),h.style.position="absolute"));if(h=h||document.getElementById(g)){var m=h.Reqs?h.Reqs:h.Reqs=[],r=m.length+"@0@"+g;b.rid=r;m[m.length]={rid:r,
container:h,method:this.methodName,context:b.context,c:b,p:b,i:b,operation:this.methodName,isHTML:!0};if(h&&h.style){h.style.display="";h.style.visibility="";if(g=document.getElementById("gigya_ifr_"+g))g.style.display="",g.style.visibility="";null!=g&&(a.utils.DOM.setSize(g,b.width,b.height,c),g.style.visibility="visible");a.utils.DOM.setSize(h,b.width,b.height,c)}g=this.methodName.split(".").pop();h.setAttribute&&h.setAttribute("gigid",(b.source&&b.source!=g?b.source+"_":"")+g)}else a.events.dispatchInvalidParamError(b,
"containerID");e()}else window.setTimeout(function(){f.prepareContainer(b,c,e)},200)};return e}(b.BaseApi);b.UiApi=h})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(a){(function(a){function b(a,e){return a.instanceID?a.instanceID:a.isPopup?"gigya-modal-plugin-container-"+e.methodName:a.containerID?a.containerID:e.name}a.instances={};a.getPluginInstance=function(f,e){var d=b(f,e);return a.instances[d]};a.setPluginInstance=function(f,e,d,c){void 0===c&&(c=!1);e=b(f,e);if(!c){c=e;for(var l=2;a.instances[e];l++)e=c+l.toString()}f.instanceID=e;a.instances[e]=d};a.removePluginInstance=function(f,e){delete a.instances[b(f,e)];delete f.instanceID}})(a.plugins||
(a.plugins={}))})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.registerPlugin=function(b){a.utils.queue.queueForExecution("UI",b)};b.attachPlugin=function(b,f,e,d){f||(f="socialize");a[f]||(a[f]={});a[f].plugins||(a[f].plugins={});a[f].plugins[e]||(a[f].plugins[e]={instances:[]});var c=a[f].plugins[e];c[d]||(c[d]=function(a){a=new b(a,"gigya."+f+".plugins."+e+".instances["+c.instances.length+"]");c.instances.push(a)});if(b.StaticApi)for(var g in b.StaticApi)a.utils.functions.createAlias("gigya."+f+".plugins."+e+"."+g,
b[b.StaticApi[g]])}})(b.UI||(b.UI={}))})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){var h=function(){function b(a,d,c){this.methodName=a;this._versions=d;if(!this._versions||1>this._versions.length)throw Error(this.methodName+": required at least one valid version");if(c){if(this._defaultVersionIndex=this.findVersionIndexOrDefault(c),-1==this._defaultVersionIndex)throw Error(this.methodName+": default version is not defined as a version");}else this._defaultVersionIndex=0}b.prototype.callVersion=function(a,b,c){void 0===b&&(b={});void 0===c&&
(c=[b]);var f=this.findVersionIndexOrDefault(a);if(-1==f)throw Error("gigya plugin version doesn't exist");if(f=this.findSupportedVersion(f))this.invokeVersionMethod(f,b,c);else throw Error(a+": could not find supported version for this browser");};b.prototype.findSupportedVersion=function(a){for(var b=this._versions.length,c=0;c<b;++c){var f=this._versions[(a-c+b)%b];if(!f.isSupported||f.isSupported({directCall:0==c}))return f}};b.prototype.findVersionIndexOrDefault=function(b){var d=-1;b&&(d=a.utils.array.firstIndex(this._versions,
function(a){return a.versionName==b}));-1==d&&(d=void 0!==this._defaultVersionIndex?this._defaultVersionIndex:-1);return d};b.prototype.invokeVersionMethod=function(a,b,c){void 0===b&&(b={});void 0===c&&(c=[b]);var f;switch(typeof a.method){case "function":f=a.method;break;case "string":f=eval(a.method);b.selectedMethodName=a.method;break;default:throw Error(this.methodName+" "+a.versionName+": unsupported gigya-version method");}for(var g in a.additionalParams)b[g]=a.additionalParams[g];b.originalMethodName=
this.methodName;f.apply(this,c)};return b}();b.VersionSelector=h})(b.api||(b.api={}))})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.didChatAuthenticate=!1;b.init=function(){a.socialize.addEventHandlers({listenerType:"component"},{onLogin:function(){b.didChatAuthenticate=!1}});b.didChatAuthenticate=!1};b.beforeChatRequest=function(h,f){b.didChatAuthenticate?f():(b.didChatAuthenticate=!0,a.socialize.getUserInfo({signIDs:!0,callback:function(a){0==a.errorCode&&""!=a.user.UID&&""!=a.user.UIDSignature&&""!=a.user.signatureTimestamp&&(h.UID=a.user.UID,h.UIDSignature=a.user.UIDSignature,h.signatureTimestamp=
a.user.signatureTimestamp,h.loginTokenExp=a.user.loginTokenExp?a.user.loginTokenExp:0);f()}}))}})(b.chat||(b.chat={}))})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){b.defaultApiSchema="ctag|APIKey|cid|oauth_token|source|sourceData|usePost|refUID|fb_UID|fb_at|fb_exp|environment";b.defaultOauthSchema="ctag|temporary_account|authFlow|connectWithoutLogin|provider|redirectMethod|redirect_uri|pendingRegistration|lang|regSource|extraPermissions|sessionExpiration|forceAuthentication|includeiRank|includeAllIdentities|extraFields|enabledProviders|disabledProviders|signIDs|openIDUsername|openIDURL|openIDProviderLogo|openIDProviderName|finalizeRegistration|include|actionAttributes|profileAttributes|googlePlayAppID|bp_channel_url|loginIfExists|includeUserInfo|redirectURL|authCodeOnly|enablePopupLocation|invite|regToken|loginMode|apiDomain|conflictHandling|forcePermissions|signKeys";b.postBookmarkSchema=
"provider|URL|url|title|description|target|cid|APIKey|shortURLs|source|sourceData|providerKey|thumbnailURL|tags|userAction|[providerCapability=actions]UserAction|actionAttributes|facebookDialogType";b.loginMethods={"socialize.login":1,"socialize.addConnection":1,"socialize.notifyLogin":1,"socialize.linkAccounts":1,"accounts.login":1,"accounts.socialLogin":1,"accounts.linkAccounts":1,"accounts.register":1,"accounts.finalizeRegistration":1};var g=function(a){return"link"!==a.loginMode&&"reAuth"!==a.loginMode},
h=function(a,b){b()};b.logoutBehaviour={logoutBeforeServerResponse:!0,alwaysSendLogoutToServer:!1};b.logoutMethods={"socialize.logout":1,"accounts.logout":1,"socialize.deleteAccount":1,"socialize.unlinkAccounts":1};var f=function(b,e){a.partnerSettings.ssoKey&&(b.signIDs=!0);e()},e=function(){return!b.logoutBehaviour.alwaysSendLogoutToServer},d={preprocessor:a._.chat.beforeChatRequest};b.arApiList=[new b.ServerApi("socialize.login",b.defaultOauthSchema,!1,{oauth:!0},{preprocessor:h,clearSessionCondition:g,
forceHttps:!0}),new b.ServerApi("socialize.addConnection",b.defaultOauthSchema,!1,{oauth:!0},{forceHttps:!0}),new b.ServerApi("socialize.requestPermissions",b.defaultOauthSchema,!0,{oauth:!0,defaultParams:{forcePermissions:!0}}),new b.ServerApi("accounts.socialLogin",b.defaultOauthSchema,!1,{oauth:!0},{preprocessor:h,clearSessionCondition:g,forceHttps:!0}),new b.UiApi("showDebugUI","socialize.plugins.debug",{},{},"",{allowPopup:!0}),b.UiApi.createApi("showMyPhotoUI","accounts","profilePhoto.MyPhotoPlugin",
"accounts.plugins.profilePhoto"),b.UiApi.createApi("showRatingUI","comments","rating.RatingPlugin","comments.plugins.rating"),b.UiApi.createApi("runJsUnitTests","_","JsUtRunner.Jasmine.JasmineUtRunnerPlugin","_.plugins.jsUtRunner"),b.UiApi.createApi("loadBasePlugin","_","Mock.MockPlugin","_.plugins.mock"),new b.UiApi("showCommentsUI","comments.plugins.comments",{width:500},{},"",{apiName:"comments.showCommentsUI1"}),new b.UiApi("showCommentsUI","comments.plugins.comments2",{width:500},{},"",{apiName:"comments.showCommentsUI2"}),
b.UiApi.versionSelector("showCommentsUI","comments","2",[{versionName:"1",method:a.comments.showCommentsUI1,additionalParams:{ctag:"comments_v1"}},{versionName:"2",method:a.comments.showCommentsUI2,additionalParams:{ctag:"comments_v2"},isSupported:function(){return a.utils.browser.isModern()}}]),new b.UiApi("showShareUI","socialize.plugins.share",{width:520,height:320},{width:595,height:324},"userAction",{allowPopup:!0,preprocessor:function(c,e){var d=c.operationMode;d&&(d=d.toLowerCase().replace(/ /g,
""));c.containerID||(delete c.width,delete c.height);b.apiAdapter.isSessionValid(c,function(b){"simpleshare"==d||"autodetect"==d&&!b?a.socialize.showSimpleShareUI(c):e()})}}),b.UiApi.createApi("showMessageUI","_","messages.MessagesPlugin","_.plugins.messages"),new b.UiApi("showLoginUI_v1","socialize.plugins.login",{width:120,height:110},{width:280,height:220},"",{allowPopup:!0}),b.UiApi.createApi("showLoginUI_v2","socialize","login_v2.LoginPlugin","socialize.plugins.login_v2"),b.UiApi.versionSelector("showLoginUI",
"socialize","1",[{versionName:"1",method:a.socialize.showLoginUI_v1},{versionName:"2",method:a.socialize.showLoginUI_v2}]),new b.UiApi("showAddConnectionsUI_v1","socialize.plugins.login",{width:110,height:65},{width:250,height:200},"",{allowPopup:!0}),b.UiApi.createApi("showAddConnectionsUI_v2","socialize","login_v2.LoginPlugin","socialize.plugins.login_v2"),b.UiApi.versionSelector("showAddConnectionsUI","socialize","1",[{versionName:"1",method:a.socialize.showAddConnectionsUI_v1},{versionName:"2",
method:a.socialize.showAddConnectionsUI_v2}]),new b.UiApi("showFriendSelectorUI","socialize.plugins.friendSelector",{width:400,height:360},{},"",{allowPopup:!0}),new b.UiApi("showFeedUI","socialize.plugins.newsfeed",{width:304,height:265}),new b.UiApi("showChatUI","chat.plugins.chat",{width:300,height:450},{},"",{preprocessor:function(a,b){a.site&&(a.categoryID=a.site);a.stream&&(a.streamID=a.stream);a.skin&&(a.skinID=a.skin);a.streamID=a.streamID||0;b()}}),b.UiApi.createApi("showEditConnectionsUI",
"socialize","editConnections.EditConnectionPlugin","socialize.plugins.edit"),new b.UiApi("showShareBarUI","socialize.plugins.reactions",{shareCountCacheTimeout:3E5},{},"userAction|shareButtons"),new b.UiApi("showReactionsBarUI","socialize.plugins.reactions",{},{},"userAction|barID|reactions",{preprocessor:function(a,b){a.barID||(a.barID=a.itemID);b()}}),new b.UiApi("showMiniShareUI","socialize.plugins.minishare",{width:320,height:153},{},"",{allowPopup:!0}),new b.UiApi("showFollowBarUI","socialize.plugins.followbar",
{},{},"buttons"),new b.UiApi("showBookmarkUI","socialize.plugins.bookmark",{width:310,height:250},{width:310,height:310}),new b.UiApi("showSimpleShareUI","socialize.plugins.simpleShare",{width:280,height:175},{},"userAction",{allowPopup:!0,dontLoadPluginsCore:!0,waitForAPIQueue:!0}),new b.UiApi("showShareMobileUI","socialize.plugins.shareMobile",{},{},"userAction",{allowPopup:!0}),new b.UiApi("showUserStatusUI","gm.plugins.userStatus",{width:300,hidePoints:!1,hideActions:!1},{},"",{requireSession:!0}),
new b.UiApi("showAchievementsUI","gm.plugins.achievements",{width:300,height:100,excludeChallenges:"_default"}),new b.UiApi("showChallengeStatusUI","gm.plugins.achievements",{width:300,height:100,challenge:"_default"}),new b.UiApi("showLeaderboardUI","gm.plugins.leaderboard",{width:300},{},"",{preprocessor:function(a,b){a&&a.height&&(a.height=null);b()}}),new b.UiApi("showNotifications","gm.plugins.notifications",{},{},"",{preprocessor:function(b,e){var d=a.utils.localStorage.getObject("gmSettings");
d&&d.disableNotifications||(b.containerID="gigNotifications",document.getElementById(b.containerID)||(d=document.createElement("div"),d.id=b.containerID,d.style.position="absolute",d.style.left="-1000px",a.utils.DOM.appendToBody(d)),e())}}),new b.UiApi("showTfaUI","accounts.plugins.tfa",{width:325}),b.UiApi.createApi("showScreenSet","accounts","ScreenSet.ScreenSetPlugin","accounts.plugins.screenSet",void 0,["hideScreenSet","switchScreen"]),new b.ServerApi("socialize.getAvailableProviders","enabledProviders|disabledProviders|requiredCapabilities"),
new b.ServerApi("socialize.notifyLogin","siteUID|UIDTimestamp|UIDSig|UIDNonce|provider|authToken|tokenSecret|regSource|tokenExpiration|sessionHandle|sessionHandleExpiration|userInfo|providerSessions|sessionExpiration|authCode|includeAllIdentitiesincludeiRank|group|settings|extraFields|signIDs|newUser|actionAttributes|profileAttributes|bp_channel_url|signKeys",!1,void 0,{forceHttps:!0,clearSession:!0}),new b.ServerApi("socialize.shortenURL","URL"),new b.ServerApi("socialize.convertAction","userAction|[providerCapability=actions]UserAction|provider"),
new b.ServerApi("socialize.getReactionsCount","barID|buttonIDs|reportLoad"),new b.ServerApi("socialize.incrementReactionsCount","barID|buttonID|count|actionAttributes|profileAttributes"),new b.ServerApi("socialize.deleteAccount",void 0,!0),new b.ServerApi("socialize.delUserSettings","group|settings",!0),new b.ServerApi("socialize.getAlbums","type|enabledProviders|disabledProviders",!0),new b.ServerApi("socialize.getContacts","enabledProviders|disabledProviders",!0),new b.ServerApi("socialize.getFriendsInfo",
"enabledProviders|disabledProviders|detailLevel|UIDs|siteUsersOnly|requiredCapabilities|signIDs",!0),new b.ServerApi("socialize.getPhotos","enabledProviders|disabledProviders|albumIDs|tags",!0),new b.ServerApi("socialize.getRawData","provider|UID|fields|dataFormat|path",!0),new b.ServerApi("socialize.getSessionInfo","provider|paddingMode|encrypt|signIDs|encryptAll",!0),new b.ServerApi("socialize.getUserInfo","enabledProviders|disabledProviders|signIDs|includeiRank|includeAllIdentities|extraFields|group|settings|includeOpenidUID",
!0),new b.ServerApi("socialize.getUserSettings","group|settings|regToken",!0,void 0,{forceHttps:!0},"regToken"),new b.ServerApi("socialize.getPlaces","enabledProviders|disabledProviders|latitude|longitude|query|radius|unifyResults",!0),new b.ServerApi("socialize.checkin","enabledProviders|disabledProviders|placeID|comment|latitude|longitude|actionAttributes|profileAttributes",!0),new b.ServerApi("socialize.logout","signIDs|samlContext|sustainLogoutURLs",!0,{preprocessor:f,disableCache:!0},{requiresSession:e}),
new b.ServerApi("socialize.notifyRegistration","siteUID|UIDTimestamp|UIDSig",!0),new b.ServerApi("socialize.publishUserAction","userAction|[providerCapability=actions]UserAction|enabledProviders|disabledProviders|target|shortURLs|scope|privacy|feedID|userLocation|tags|actionAttributes|profileAttributes",!0),new b.ServerApi("socialize.removeConnection","provider|lastIdentityHandling|removeLoginID",!0),new b.ServerApi("socialize.sendNotification","recipients|body|subject|shortURLs|actionAttributes|profileAttributes",
!0),new b.ServerApi("socialize.setStatus","shortURLs|status|[providerCapability=status]Status|enabledProviders|disabledProviders|userLocation|actionAttributes|profileAttributes",!0),new b.ServerApi("socialize.setUID","siteUID|UIDTimestamp|UIDSig",!0),new b.ServerApi("socialize.setUserSettings","group|settings|regToken",!0,void 0,{forceHttps:!0},"regToken"),new b.ServerApi("socialize.unlinkAccounts",void 0,!0),new b.ServerApi("socialize.getFeed","feedID|startTS|endTS|groups|limit|includeUID"),new b.ServerApi("socialize.sendEmail",
"dontSendEmail|companyName|lang|emails|emailSubject|emailBody|linkBack|senderEmail|senderName|userMsg|shortURLs|userAction|[providerCapability=actions]UserAction|actionAttributes|profileAttributes|captchaTicket|lang",!1,void 0,{forceHttps:!0}),new b.ServerApi("socialize.facebookGraphOperation","graphPath|graphParams|authRequired|method|authType"),new b.ServerApi("socialize.getTopShares","age|tag|limit"),new b.ServerApi("socialize.notifySSOLogin","bp_channel_url"),new b.ServerApi("gm.getChallengeStatus",
"UID|includeChallenges|excludeChallenges|details|lang|actionAttributes|profileAttributes"),new b.ServerApi("gm.resetLevelStatus","challenges|actionAttributes|profileAttributes",!0),new b.ServerApi("gm.getTopUsers","challenge|totalCount|friendsCount|includeSelf|period|lang|actionAttributes|profileAttributes"),new b.ServerApi("gm.getChallengeConfig","UID|includeChallenges|excludeChallenges|lang|actionAttributes|profileAttributes|expandActions"),new b.ServerApi("gm.notifyAction","action|operation|challengeIDs|actionAttributes|profileAttributes",
!0),new b.ServerApi("comments.updateComment","categoryID|streamID|commentID|commentText|commentTitle|ratings|mediaItems|taggedUsers"),new b.ServerApi("comments.postComment","categoryID|streamID|parentID|guestName|guestEmail|commentText|anonymous|mediaItems|privacy|feedID|userAction|[providerCapability=actions]UserAction|scope|enabledProviders|disabledProviders|shortURLs|commentTitle|ratings|tags|taggedUsers|streamTags|actionAttributes|profileAttributes"),new b.ServerApi("comments.getComments","categoryID|streamID|includeSettings|start|startTS|threadLimit|sort|threaded|threadDepth|includeStreamInfo|includeOpenidUID|includeUID|includeReplies|tags|dataFormat|markupType|includeUserOptions|includeUserComments|includeRatingsDims|includeUserHighlighting|pinnedCommentID|lang"),
new b.ServerApi("comments.setStreamInfo","categoryID|streamID|streamTitle|streamURL|streamInfoSig|streamTags"),new b.ServerApi("comments.getTopStreams","categoryID|limit|maxStreamAge|includeLastComment|streamTag|minRatingsCount"),new b.ServerApi("comments.getTopRatedStreams","categoryID|limit|maxStreamAge|ratingClass|minRatingsCount|streamTag"),new b.ServerApi("comments.getStreamInfo","categoryID|streamID|streamIDs|includeLastComment|includeRatingsDims|includeRatingDetails"),new b.ServerApi("comments.flagComment",
"categoryID|streamID|commentID|actionAttributes|profileAttributes"),new b.ServerApi("comments.vote","categoryID|streamID|commentID|vote|actionAttributes|profileAttributes",!0),new b.ServerApi("comments.getUserVotes","categoryID|streamID",!0),new b.ServerApi("comments.getUserComments","categoryID|streamID|tag|senderUID|start|limit|sort|includeReplies|includeStreamInfo|includeUserHighlighting",!0),new b.ServerApi("comments.getFriendsComments","categoryID|streamID|start|limit|includeUID|sort|includeReplies|includeStreamInfo",
!0),new b.ServerApi("comments.getThread","categoryID|streamID|commentID|start|includeUID|limit|threadDepth|sort"),new b.ServerApi("comments.deleteComment","categoryID|streamID|commentID",!0),new b.ServerApi("comments.getRelatedUsers","categoryID|streamID|parentCommentID|usernamePrefix|limit"),new b.ServerApi("comments.analyzeMediaItem","categoryID|urls"),new b.ServerApi("comments.subscribe","categoryID|streamID|email|lang"),new b.ServerApi("comments.unsubscribe","categoryID|streamID|unsubscribeToken"),
new b.ServerApi("comments.setUserOptions","replyNotifications|notificationsEmail|notificationsLanguage",!0),new b.ServerApi("comments.getUserOptions","ServerApiKey",!0),new b.ServerApi("gcs.getUserData","type|fields",!0),new b.ServerApi("gcs.setUserData","data|type|updateBehavior",!0),new b.ServerApi("gcs.search","expTime|querySig|query"),new b.ServerApi("gcs.getSchema","schemaType"),new b.ServerApi("chat.getSettings","categoryID|streamID|skinID|UID|UIDSignature|signatureTimestamp|loginTokenExp",
!1,d),new b.ServerApi("chat.getMessages","categoryID|streamID|start|includeSettings|chatSignature|UID|UIDSignature|signatureTimestamp|loginTokenExp",!1,d),new b.ServerApi("chat.postMessage","categoryID|streamID|messageText|isPrivate|actionAttributes|profileAttributes|signatureTimestamp|loginTokenExp",!0,d),new b.ServerApi("chat.resetChat","categoryID|streamID|timestamp|chatSignature"),new b.ServerApi("chat.blockUser","categoryID|streamID|UID|chatSignature"),new b.ServerApi("chat.blockIP","categoryID|streamID|ip|chatSignature"),
new b.ServerApi("chat.deleteMessage","categoryID|streamID|messageId|chatSignature"),new b.ServerApi("accounts.login","loginID|password|sessionExpiration|targetEnv|regToken|include|actionAttributes|profileAttributes|includeUserInfo|includeDynamicSchema|bp_channel_url|captchaToken|captchaText|loginMode|signKeys",!1,void 0,{preprocessor:h,clearSessionCondition:g,forceHttps:!0,forcePost:!0}),new b.ServerApi("accounts.linkAccounts","loginID|password|sessionExpiration|targetEnv|include|regToken|includeUserInfo|bp_channel_url|signKeys",
!1,void 0,{forceHttps:!0,forcePost:!0}),new b.ServerApi("accounts.initRegistration","sdk",!1,void 0,{clearSession:!0}),new b.ServerApi("accounts.register","username|email|password|UID|regToken|siteUID|secretQuestion|secretAnswer|regSource|profile|data|captchaText|captchaToken|lang|hashedPassword|pwHashAlgorithm|skipVerification|finalizeRegistration|targetEnv|sessionExpiration|include|actionAttributes|profileAttributes|includeUserInfo|bp_channel_url|signKeys",!1,void 0,{forceHttps:!0,forcePost:!0}),
new b.ServerApi("accounts.finalizeRegistration","regToken|targetEnv|include|includeUserInfo|bp_channel_url|allowAccountsLinking|signKeys"),new b.ServerApi("accounts.captchaImage","regToken"),new b.ServerApi("accounts.importProfilePhoto","regToken|URL|publish"),new b.ServerApi("accounts.setProfilePhoto","regToken|publish|photoBytes"),new b.ServerApi("accounts.resetPassword","lang|loginID|passwordResetToken|secretAnswer|securityFields|newPassword|email",!1,void 0,{forceHttps:!0,forcePost:!0}),new b.ServerApi("accounts.isAvailableLoginID",
"loginID"),new b.ServerApi("accounts.resendVerificationCode","regToken|email"),new b.ServerApi("accounts.getCaptcha",""),new b.ServerApi("accounts.getPolicies","sections"),new b.ServerApi("accounts.getSchema","sections|schemaType"),new b.ServerApi("accounts.verifyLogin","include|extraProfileFields|targetEnv",!0),new b.ServerApi("accounts.getAccountInfo","include|extraProfileFields|regToken",!0,{},{},"regToken"),new b.ServerApi("accounts.setAccountInfo","profile|data|regToken|oldPassword|password|newPassword|addLoginEmails|removeLoginEmails|username|secretQuestion|secretAnswer|requirePasswordChange|conflictHandling|tfaStatus|rba",
!1,void 0,{forceHttps:!0,forcePost:!0},"regToken"),new b.ServerApi("accounts.logout","signIDs|samlContext|sustainLogoutURLs",!0,{preprocessor:f,disableCache:!0},{requiresSession:e}),new b.ServerApi("accounts.search","expTime|querySig|query"),new b.ServerApi("accounts.getScreenSets","screenSetIDs|include"),new b.ServerApi("accounts.getConflictingAccount","regToken|loginID"),new b.ServerApi("accounts.incrementCounters","counters",!0,{preprocessor:function(a,b){var e=a.actionCounterPath,d=a.counters;
if(e&&d)for(var f=0;f<d.length;f++){var g=d[f];"object"!=typeof g||g.path||(g.path=e)}b()}}),new b.ServerApi("accounts.getCounters","counters",!0),new b.ServerApi("accounts.tfa.getProviders","regToken",!0,{},{},"regToken"),new b.ServerApi("accounts.tfa.initTFA","provider|mode|regToken",!1,{},{forceHttps:!0}),new b.ServerApi("accounts.tfa.finalizeTFA","gigyaAssertion|providerAssertion|tempDevice|regToken",!0,{},{},"regToken"),new b.ServerApi("accounts.tfa.deactivateProvider","provider",!0),new b.ServerApi("accounts.tfa.unregisterDevice",
"allDevices",!0),new b.ServerApi("accounts.tfa.phone.getRegisteredPhoneNumbers","gigyaAssertion",!1,{},{forceHttps:!0}),new b.ServerApi("accounts.tfa.phone.removePhone","gigyaAssertion|phoneId",!1,{},{forceHttps:!0}),new b.ServerApi("accounts.tfa.phone.sendVerificationCode","gigyaAssertion|lang|phoneID|phone|method",!1,{},{forceHttps:!0}),new b.ServerApi("accounts.tfa.phone.completeVerification","gigyaAssertion|phvToken|code",!1,{},{forceHttps:!0}),new b.ServerApi("ds.store","type|data|oid|updateBehavior"),
new b.ServerApi("ds.get","type|data|oid|fields"),new b.ServerApi("ds.search","expTime|querySig|query"),new b.ServerApi("ds.getSchema",""),new b.ServerApi("ds.delete","type|oid|fields"),new b.ServerApi("ids.getAccountInfo","include|extraProfileFields",!0),new b.ServerApi("ids.setAccountInfo","profile|data|oldPassword|password|newPassword|addLoginEmails|removeLoginEmails|username|secretQuestion|secretAnswer|requirePasswordChange",!1,void 0,{forceHttps:!0,forcePost:!0}),new b.ServerApi("ids.search",
"expTime|querySig|query"),new b.ServerApi("gscounters.sendReport","reports|noAuth")];a.utils.functions.createAlias("gigya.socialize.showChatUI",a.chat.showChatUI);a.utils.functions.createAlias("gigya.socialize.showCommentsUI",a.comments.showCommentsUI);a.utils.functions.createAlias("gigya.socialize.showRatingUI",a.comments.showRatingUI);a.utils.functions.createAlias("gigya.services.socialize",a.socialize);a.utils.functions.createAlias("gigya.services.gcs",a.gcs);a.utils.functions.createAlias("gigya.services.gm",
a.gm);a.utils.functions.createAlias("gigya.services.comments",a.comments);a.utils.functions.createAlias("gigya.services.accounts",a.accounts);a.utils.functions.createAlias("gigya.socialize.connect",a.socialize.addConnection);a.utils.functions.createAlias("gigya.socialize.disconnect",a.socialize.removeConnection);a.utils.functions.createAlias("gigya.socialize.linkAccounts",a.socialize.setUID);a.utils.functions.createAlias("gigya.socialize.showConnectUI",a.socialize.showAddConnectionsUI);a.utils.functions.createAlias("gigya.socialize.showNewsfeedUI",
a.socialize.showFeedUI);a.utils.functions.createAlias("gigya.showDebugUI",a.socialize.showDebugUI)})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){a.socialize.addEventHandlers=function(){for(var b=[],d=0;d<arguments.length;d++)b[d-0]=arguments[d];var b=a.utils.object.merge([a.thisScript.globalConf,b]),d=b.namespace?b.namespace:"socialize",c;for(c in b)0==c.indexOf("on")&&a.events.global.add(c,b[c],b.listenerType,b.context,d,b);"function"==typeof b.callback&&b.callback({status:"OK",statusMessage:"",errorCode:0,errorMessage:"",operation:"addEventHandlers",context:b.context})};a.accounts.addEventHandlers=function(){for(var b=
[],d=0;d<arguments.length;d++)b[d-0]=arguments[d];b=a.utils.object.merge([b,{namespace:"accounts"}]);a.socialize.addEventHandlers(b)};a.socialize.isLoggedIn=function(){var b=a.utils.object.merge([a.thisScript.globalConf,arguments]);a.socialize.getUserInfo(b,{callback:function(d){var c=d.user,c={loggedIn:c?a.utils.validation.isExplicitTrue(c.isLoggedIn):!1};a.utils.object.extractProperties(d,c,"status|statusMessage|callId|errorCode|errorMessage|errorDetails|context");b.callback&&b.callback(c)}})};
a.socialize.waitForService=function(){var b=a.utils.object.merge([a.thisScript.globalConf,arguments]),d=b.service;if(d){var d=d.toLowerCase(),c=b.callback;if("fbconnect"==d||"facebook"==d)a.external.facebook.isLoaded()?c({context:b.context}):a.socialize.addEventHandlers({listenerType:"component"},{onFacebookLoaded:c,context:b.context});"googleplus"==d&&(a.external.googlePlus.isLoaded()?c({context:b.context}):a.socialize.addEventHandlers({listenerType:"component"},{onGooglePlusLoaded:c,context:b.context}))}};
var g={facebook:{w:640,h:370},twitter:{w:880,h:585},messenger:{w:710,h:905},linkedin:{w:560,h:500},yahoobookmarks:{w:840,h:975},digg:{w:1010,h:1045},delicious:{w:890,h:905},googlebookmarks:{w:710,h:905},mixi:{w:640,h:470},googleplus:{w:496,h:420}};a.socialize.postBookmark=function(){var e=a.utils.object.merge([a.thisScript.globalConf,arguments]);e.APIKey||(e.APIKey=a.thisScript.APIKey);var d={};a.utils.object.extractProperties([e],d,b.postBookmarkSchema);d.sdk="js_"+a.build.version;if(!d.URL&&!d.url&&
d.userAction&&!d.userAction.linkBack)for(var c=document.getElementsByTagName("meta"),f=0;f<c.length;f++)if("og:url"==c[f].getAttribute("property")&&c[f].getAttribute("content")){d.URL=c[f].getAttribute("content");break}d.URL||d.url||!d.userAction||d.userAction.linkBack||(d.URL=document.location.href);delete d.context;d.provider||(d.provider="");d.providerKey||"facebook"==d.provider.toLowerCase()&&(d.providerKey=a.external.opengraph.getMetaTag("fb:app_id"));a._.apiAdapter.getGmidTicket(function(b){b&&
(d.gmidTicket=b);b=a.utils.keyValue.serialize(d);var c=g[d.provider.toLowerCase()],f=e.enablePopupLocation?"location=1,toolbar=1":null;c&&c.w&&c.h&&(f=(e.enablePopupLocation?"location=1,toolbar=1,":"toolbar=0,")+"menubar=0,resizable=1,scrollbars=1,width="+c.w+",height="+c.h);a.log.logCall("postBookmark",d);a.utils.win.open(a.utils.stringUtils.format(a.partnerSettings.customAPIDomainPrefix?"https://{0}/gs/bookmark.aspx?{1}":"https://socialize.{0}/gs/bookmark.aspx?{1}",a.partnerSettings.plugins.apiDomain,
b),"gs_bookmark_"+d.provider,f)})};a.socialize.refreshUI=function(){var e=a.utils.object.merge([a.thisScript.globalConf,arguments]),d=e.callback;a.socialize.getUserInfo(e,{callback:function(c){var f={eventName:"login",isInternal:!0};e.provider&&(f.provider=e.provider);b.addUserInfoToEvent(c,f,!0);e.context&&(f.context=e.context);a.events.global.dispatch(f);"function"==typeof d&&d(c)}})};var h={"digg.com":"digg","stumbleupon.com":"stumbleupon","delicious.com":"delicious","technorati.com":"technorati",
"t.co":"twitter","plus.url.google.com":"googlePlus","facebook.com":"facebook","linkedin.com":"linkedIn","pinterest.com":"pinterest","mixi.jp":"mixi","b.hatena.ne.jp":"hatena","line.me":"line"},f;a.socialize.trackReferrals=function(){var e=a.utils.object.merge([a.thisScript.globalConf,arguments]),d={eventName:"linkback",CID:e.cid},c={},g={};-1!=document.location.href.indexOf("#")&&(g=a.utils.keyValue.deserialize(document.location.href.split("#")[1]));-1!=document.location.href.indexOf("?")&&(c=a.utils.keyValue.deserialize(document.location.href.split("?")[1].split("#")[0]));
a.socialize.updateRefUID(e.APIKey,g,c);var p=null!=g._gus||null!=c._gus;p&&(d.CID=g._gucid||c._gucid,d.shortCode=g._gsc||c._gsc,d.provider=g._gup||c._gup);if(!f){var q,g={url:document.location.href,ref:document.referrer};c.fb_ref?(q=a.utils.keyValue.deserialize(c.fb_ref,":"),g.uuid=q.uu,g.sn=q.p,q=q.s):document.referrer&&-1!=document.referrer.indexOf("://")&&(c=document.referrer.split("://")[1].split("/")[0],0==c.indexOf("www.")&&(c=c.split("www.")[1]),h[c]&&(d.provider=g.sn=h[c]));g.sn||document.referrer&&
(-1!=document.referrer.indexOf("http://soc.li")||-1!=document.referrer.indexOf("https://shr.gs"))||(c=document.location.href.split("#guid="),1<c.length&&(c=c[1].split("#")[0].split("&")[0],c!=b.apiAdapter.getTokenParam(e.APIKey,"UUID")&&(g.sn="AddressBarShares",g.uuid=c,"_"==c&&delete g.uuid,document.location.replace("#"),a.reports.trackAddressBarShares(),g.url=document.location.href.split("#")[0])));g.uuid&&a.utils.cookie.set("_gigRefUid_"+e.APIKey,g.uuid);g.sn&&!p&&a.reports.report("linkback",e.APIKey,
e.cid,q,null,g);(g.sn||p)&&a.events.global.dispatch(a.utils.object.removeUndefined(d));f=!0}"function"==typeof e.callback&&e.callback({status:"OK",statusMessage:"",operation:"trackReferrals",context:e.context,errorMessage:"",errorCode:0})};a.socialize.updateRefUID=function(b,d,c){b||(b=a.thisScript.globalConf.APIKey);d||(d={},-1!=document.location.href.indexOf("#")&&(d=a.utils.keyValue.deserialize(document.location.href.split("#")[1])));c||(c={},-1!=document.location.href.indexOf("?")&&(c=a.utils.keyValue.deserialize(document.location.href.split("?")[1].split("#")[0])));
d.guid&&"_"!=d.guid&&a.utils.cookie.set("_gigRefUid_"+b,d.guid);(d=d._giguuid||c._giguuid)&&a.utils.cookie.set("_gigRefUid_"+b,d)};a.socialize.hideUI=function(){var b=a.utils.object.merge([a.thisScript.globalConf,arguments]);"function"==typeof b.callback&&b.callback({status:"OK",statusMessage:"",operation:"hideUI",context:b.context,errorMessage:"",errorCode:0})};a.gcs.submitUserForm=function(){var b={},d=a.utils.object.merge([a.thisScript.globalConf,arguments]),c=document.getElementById(d.form);if(!c){var f=
document.getElementsByName(d.form);f&&0<f.length&&(d.form=f[0])}for(f=0;f<c.elements.length;f++){var g=c.elements[f];if(g.name){for(var h=g.name.split("."),k=b,m=0;m<h.length-1;m++){var r=h[m];k[r]||(k[r]={});k=k[r]}k[h[h.length-1]]=g.value}}d.data=b;a.gcs.setUserData(d)};a.socialize.getProviderShareCounts=function(){var b=a.utils.object.merge([a.thisScript.globalConf,arguments]);a.utils.script.load(a._.getCdnResource("/js/gigya.services.socialize.plugins.shareCounts.min.js"),null,function(){a.socialize.plugins.shareCounts.getProviderShareCounts(b)},
!0)};a.utils.functions.createAlias("gigya.setSSOToken",function(){for(var b=[],d=0;d<arguments.length;d++)b[d-0]=arguments[d];var b=a.utils.object.merge([a.thisScript.globalConf,b]),d=b.redirectURL||document.location.href,c=null!=a.partnerSettings.ssoKey,f="1"!=a.utils.localStorage.getItem("_gig_3pc_enabled"),g=a.utils.JSON.deserialize(a.utils.localStorage.getItem("_gig_ssoToken"))||{},h=g.ssoToken,k=(new Date).getTime();g.exp<k&&a.thisScript.globalConf.enableSSOToken&&c&&f&&null!=h?a.utils.HTTP.redirect("https://socialize."+
(a.partnerSettings.plugins.originalApiDomain||a.partnerSettings.plugins.apiDomain)+"/gs/SSOGateway.aspx",[{apiKey:b.APIKey,redirectURL:d,ssoToken:h}],"GET","_top"):a.utils.HTTP.redirect(d,[{}],"GET","_top")})})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.initSSO=function(b){b=a.utils.URL.addParamsToURL(a.samlConfig.proxyPageURL,a.utils.object.merge([{mode:"initSSO"},b]));window.location.href=b};b.continueSSO=function(){var b=a.utils.URL.addParamsToURL(a.samlConfig.proxyPageURL,{mode:"afterLogin"});window.location.href=b}})(b.saml||(b.saml={}))})(a.fidm||(a.fidm={}))})(gigya||(gigya={}));(function(a){a=a._||(a._={});a=a.apiAdapters||(a.apiAdapters={});a.a})(gigya||(gigya={}));
(function(a){(function(b){(function(b){function h(){if("undefined"!=typeof FB){var e=function(c){b.initializedTime=new Date;b.isConnected="connected"==c.status;b.isLoggedIn="unknown"!=c.status;a.events.global.dispatch({eventName:"FBCRefreshed"})};a.providersConfig.facebook.appID&&FB&&FB.getLoginStatus&&FB.getLoginStatus(e,!0)}}function f(){for(var a=e,b=0;b<a.length;b++)a[b]();e=[]}var e=[];b.initializedTime;b.isLoggedIn=!1;b.isConnected=!1;b.isLoaded=function(){return null!=b.initializedTime};b.load=
function(e){if(!b.initializedTime){b.initializedTime=null;window.setInterval(function(){a.external.facebook.refreshSession()},27E5);window.fbAsyncInit=function(){var c=a.utils.object.clone(a.thisScript.globalConf.facebookInitParams);c||(c={});a.providersConfig.facebook?(c.appId=a.providersConfig.facebook.appID,c.version=a.providersConfig.facebook.version):c.version="v1.0";c.status=!1;c.cookie=!0;c.xfbml=!0;c.oauth=!0;FB.init(c);1!=e?FB.getLoginStatus(function(c){b.initializedTime=new Date;b.isConnected=
"connected"==c.status;b.isLoggedIn="unknown"!=c.status;a.events.global.dispatch({eventName:"facebookLoaded",isLoggedIn:b.isLoggedIn,isConnected:b.isConnected});a.socialize.addEventHandlers({listenerType:"component"},{listenerDescription:"listener for updating Facebook Connect session",onLogin:function(){h()},onConnect:function(){h()},onLogout:function(){h()}})},!0):(b.initializedTime=new Date,a.events.global.dispatch({eventName:"facebookLoaded",isLoggedIn:b.isLoggedIn,isConnected:b.isConnected}))};
var c=document.createElement("div");c.id="fb-root";a.utils.DOM.appendToBody(c);a.utils.script.load(document.location.protocol+"//connect.facebook.net/"+a.thisScript.lang.full.replace("-","_")+"/sdk.js",null,function(){"none"==document.documentElement.style.display&&(document.documentElement.style.display="")},!0)}};b.refreshSession=h;b.retryPending=f;b.runWhenLoaded=function(a){e.push(a)};b.getParams=function(){var a={};if("undefined"!=typeof FB&&FB.getAuthResponse)try{var b=FB.getAuthResponse();
b&&(null!=b.userID&&(a.fb_UID=b.userID),null!=b.accessToken&&(a.fb_at=b.accessToken),null!=b.expiresIn&&(a.fb_exp=b.expiresIn))}catch(e){}return a};b.autoLogin=function(){a.socialize.waitForService({service:"facebook",callback:function(){a._.apiAdapter.isSessionValid(a.thisScript.globalConf,function(b){var c=a.external.facebook.getParams();!b&&c&&c.fb_at&&!a._.autoLoginInProgress&&(a._.autoLoginInProgress=!0,a.socialize.notifyLogin({providerSessions:{facebook:{authToken:c.fb_at,tokenExpiresIn:c.fb_exp}}}))})}})};
a.events.global.add("facebookLoaded",f,"component");a.events.global.add("onFBCRefreshed",f,"component")})(b.facebook||(b.facebook={}))})(a.external||(a.external={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b.initializedTime;b.isLoaded=function(){return null!=b.initializedTime};b.load=function(){var h=this;if(!b.initializedTime&&a.providersConfig.googlePlus){b.initializedTime=null;var f=document.createElement("script");f.type="text/javascript";f.async=!0;window.__gigya_handleClientLoad=function(){return h.handleClientLoad()};f.src="https://apis.google.com/js/client.js?onload=__gigya_handleClientLoad";var e=document.getElementsByTagName("script")[0];e.parentNode.insertBefore(f,
e)}};b.handleClientLoad=function(){try{delete window.__gigya_handleClientLoad}catch(h){window.__gigya_handleClientLoad=void 0}b.initializedTime=new Date;a.events.global.dispatch({eventName:"googlePlusLoaded"})};b.refreshSession=function(){};b.autoLogin=function(){a.socialize.waitForService({service:"googlePlus",callback:function(){a._.apiAdapter.isSessionValid(a.thisScript.globalConf,function(b){b||gapi.auth.authorize({client_id:a.providersConfig.googlePlus.clientId,scope:a.providersConfig.googlePlus.scopes,
immediate:!0,response_type:"code"},function(b){b&&b.code&&!a._.autoLoginInProgress&&(a._.autoLoginInProgress=!0,a.socialize.notifyLogin({providerSessions:{googlePlus:{code:b.code}}}))})})}})}})(b.googlePlus||(b.googlePlus={}))})(a.external||(a.external={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(b){b._ready=null;b.executeOnInit=function(b,f){b&&(f||(f=2E3),a.external.backplane.isLoaded()?a.external.backplane.getChannelId()||a.external.backplane._ready?(a.external.backplane._ready=!0,b()):(window.setTimeout(function(){a.external.backplane._ready||(a.external.backplane._ready=!0,b())},f),Backplane(function(){a.external.backplane._ready=!0;b()})):b())};b.isLoaded=function(){return"undefined"!=typeof Backplane};b.getChannelId=function(){if(a.external.backplane.isLoaded())return Backplane.getChannelID()};
b.resetChannel=function(){a.external.backplane.isLoaded()&&Backplane.resetCookieChannel()};a.events.global.add("logout",a.external.backplane.resetChannel)})(b.backplane||(b.backplane={}))})(a.external||(a.external={}))})(gigya||(gigya={}));
(function(a){(function(a){(function(a){a.getMetaTag=function(a){for(var b=document.getElementsByTagName("meta"),e=0;e<b.length;e++)if(b[e].getAttribute("property")==a&&b[e].getAttribute("content"))return b[e].getAttribute("content")}})(a.opengraph||(a.opengraph={}))})(a.external||(a.external={}))})(gigya||(gigya={}));
(function(a){(function(b){(function(a){a[a.LocalStorageListener=0]="LocalStorageListener";a[a.PostMessage=1]="PostMessage";a[a.Flash=2]="Flash"})(b.MessagingMethod||(b.MessagingMethod={}));b.checkCompleteRegistration=function(b,h,f){var e,d;if(206005==b.errorCode)a.accounts.finalizeRegistration({regToken:b.regToken,callback:function(a){f(a)}});else if(!h.dontHandleScreenSet&&((b.regToken||h.regToken)&&(200010==b.errorCode||403043==b.errorCode)||206001==b.errorCode||206002==b.errorCode||206003==b.errorCode||
403101==b.errorCode||403102==b.errorCode||403110==b.errorCode||403100==b.errorCode)){var c;403110==b.errorCode&&(c=d=!0);h.defaultMobileRegScreenSet&&a.localInfo.isMobile?e=h.defaultMobileRegScreenSet:h.defaultRegScreenSet&&(e=h.defaultRegScreenSet)}e?a.accounts.showScreenSet({newModal:c,initialResponse:b,screenSet:e,onHide:function(a){"finished"===a.reason&&a.user?f({errorCode:0,userInfo:a.user},!0,d):f(b)}}):f(b)};b.getGigyaSettings=function(b){var h=a.utils.localStorage.getItem("gigyaSettings");
try{h=a.utils.JSON.deserialize(h)}catch(f){h={}}h||(h={});return a.utils.JSON.serialize(h[b])};b.setGigyaSettings=function(b,h){var f=a.utils.localStorage.getItem("gigyaSettings");try{f=a.utils.JSON.deserialize(f)}catch(e){f={}}f||(f={});f[b]||(f[b]={});for(var d in h)f[b][d]=h[d];a.utils.localStorage.setItem("gigyaSettings",a.utils.JSON.serialize(f))};b.delGigyaSettings=function(b,h){if(b){var f=a.utils.localStorage.getItem("gigyaSettings");f&&(f=a.utils.JSON.deserialize(f),delete f[b],a.utils.localStorage.setItem("gigyaSettings",
a.utils.JSON.serialize(f)))}else a.utils.localStorage.removeItem("gigyaSettings")};b.handleSpecialFields=function(g){var h=a.socialize.Collection,f=function(a,e){for(var d=[],f=0,g=a[f];g;)d.push(new e(g)),d[f].identities&&b.convertIdentitiesArrayToObject(d[f]),g=a[++f];return d};g.photos&&(g.photos=new h(g.photos,"photoID"));g.albums&&(g.albums=new h(g.albums,"albumID"));g.contacts&&(g.contacts=new h(f(g.contacts,a.socialize.Contact),"email"));g.friend&&(g.friend=new h(f(g.friend,a.socialize.Friend),
"UID"));g.user&&(g.user=new a.socialize.User(g.user));if(g.friends&&g.friends instanceof Array){for(var e=[],d=0;d<g.friends.length;d++)e.push(g.friends[d].UID);g.UIDs=e.join(",");g.friends=new h(f(g.friends,a.socialize.Friend),"UID")}};b.convertIdentitiesArrayToObject=function(b){if(null==b.identities)b.identities={};else if(b.identities.constructor==Array){var h=b.identities;b.identities={};for(var f=0;f<h.length;f++)b.identities[h[f].provider]=new a.socialize.Identity(h[f])}};b.addUserInfoToEvent=
function(b,h,f,e){e=b.user||b.userInfo;null==h&&(h={});null!=e&&(h.user=a.utils.object.clone(e),null!=b.isLoggedIn&&(h.user.isLoggedIn=b.isLoggedIn),null!=b.isSiteUID&&(h.user.isSiteUID=b.isSiteUID),null!=b.iRank&&(h.user.iRank=b.iRank));f&&(a.utils.object.extractProperties(b,h,"signature|UIDSig|timestamp|UIDSignature|signatureTimestamp|UID|signKeysUIDSignature"),null!=h.user&&(h.UID=e.UID,h.isSiteUID=e.isSiteUID));return h};b.sendEmailNative=function(b){var h=b.userAction||{},f=h.linkBack||"";document.location.href=
"mailto:?to=&subject="+a.utils.URL.URLEncode(h.title||"")+"&body="+a.utils.URL.URLEncode(f);a.socialize.sendEmail(b,{dontSendEmail:!0})};b.getPageBaseDomain=function(g,h){void 0===g&&(g=a.localInfo.pageDomain);void 0===h&&(h=a.partnerSettings.baseDomains);if(h){var f=b.Uri.parse(g);if(f)for(var e=h.split(","),d=0;d<e.length;d++){var c=a.utils.stringUtils.replaceAll(e[d],"*",""),c=b.Uri.parse(c);if(f.isIn(c))return c.isForSubDomains()?f.domain:c.domain}}return null}})(a._||(a._={}))})(gigya||(gigya=
{}));
(function(a){(function(b){function g(){a.utils.script.load(a._.getCdnResource("/js/gigya.services.socialize.plugins.log.min.js"),null,function(){a.log.showConfig()},!0)}b.CONSOLE_LOG_LEVELS=["debug","info","log","warn","error"];b.selectedConsoleLogLevels=[];b._log=[];b.enable=function(){a.utils.cookie.set("_gig_dbgConsole_log","1",null)};b.disable=function(){a.utils.cookie.set("_gig_dbgConsole_log","0",null)};b._isEnabled=function(){var g=a.utils.cookie.get("_gig_dbgConsole_log");return"undefined"!==typeof g&&
null!=g?"1"==g:0<b.selectedConsoleLogLevels.length};b.addLog=function(g,f,e){void 0===e&&(e=!1);if(a.log._isEnabled()||e){var d=g;f=a.utils.object.clone(f,!0,!1,4,null,!0);null!=f&&(d+=":"+("object"==typeof f?"\n":"")+a.utils.JSON.serialize(f,!0,!0));e&&"object"==typeof console&&console.log&&console.log(d);a.log._isEnabled()&&(b._log.push(d),null!=document.getElementById("gigya_log")&&a.log.show&&a.log.show(),g=-1!=a.utils.array.indexOf(a.log.CONSOLE_LOG_LEVELS,g)?g:"log",a._.apiAdapter.onJSLog(g,
d))}};b.logCall=function(b,f,e){e||(e=f.lastSource);a.log.addLog("Calling "+b+(e&&e!=b?" for "+e:"")+(f.source&&e!=f.source?" initiated from "+f.source:"")+" with these params",f)};b.debug=g;b.showLog=function(){a.utils.script.load(a._.getCdnResource("/js/gigya.services.socialize.plugins.log.min.js"),null,function(){a.log.show()},!0)};b.show=function(){};b.showConfig=function(){};a.utils.functions.createAlias("gigya.debug",g)})(a.log||(a.log={}))})(gigya||(gigya={}));
var defaultObjects={},defaultObjectsDef={User:"personwithuid+isLoggedIn|false,isConnected|false,isSiteUser|false,identities|{},providers|[],timestamp,UIDSig,UIDSignature,signatureTimestamp,loginProvider,loginProviderUID,capabilities|{}",Friend:"personwithuid+timestamp,friendshipSig,friendshipSignature,signatureTimestamp,timestamp,isSiteUser|false,identities|{}",Identity:"person+isExpiredSession|false,allowsLogin|false,providerUID,provider,isLoginIdentity|false,missingPermissions",Contact:"provider,firstName,lastName,nickname,email,photoURL",
person:"nickname,photoURL,thumbnailURL,birthDay|0,birthMonth|0,birthYear|0,gender,email,proxiedEmail,country,state,city,zip,firstName,lastName,profileURL,age|0",personwithuid:"person+UID,isSiteUID|false",UserAction:"actorUID,actorNickname,actionName,date|new Date(),targets|[],images|[],actionData1,actionData2,iconURL,title,linkBack,userMessage,description,actionLinks|[],mediaItems|[],subtitle"},createDefaultObject=function(a){var b={};a=defaultObjectsDef[a];-1!=a.indexOf("+")&&(b=createDefaultObject(a.split("+")[0]),
a=a.split("+")[1]);a=a.split(",");for(var g=0;g<a.length;g++){var h="",f=a[g].split("|");if(1<f.length)try{h=gigya.utils.JSON.deserialize(f[1])}catch(e){}b[f[0]]=h||""}return b},_createConstructor=function(a){return function(b){var g=defaultObjects[a],h;for(h in g)this[h]=gigya.utils.object.clone(g[h]);if("object"==typeof b)for(h in b)"function"!=typeof b[h]&&(this[h]=gigya.utils.object.clone(b[h]))}},def;
for(def in defaultObjectsDef)defaultObjects[def]=createDefaultObject(def),gigya.socialize[def]=_createConstructor(def);gigya.socialize.Collection=function(a,b){this.arr=a;this._key=b?b:""};
gigya.socialize.Collection.prototype={asArray:function(){return this.arr},each:function(a){for(var b=0,g=this.arr[b];g;)a(g,b),b++,g=this.arr[b]},getById:function(a){"undefined"==typeof this._hash&&this._buildHash();return(this._hash?this._hash:this.arr)[a]},getSize:function(){return this.arr.length},_buildHash:function(){var a=this._hash={},b=this._key;this.each(function(g,h){a["function"==typeof g[b]?g[b]():g[b]]=g})}};
gigya.socialize.UserAction.prototype={clone:function(){return new gigya.socialize.UserAction(gigya.utils.object.clone(this,!0,!0))},getTemplate:function(){return this.titleTemplate},setTemplate:function(a){this.titleTemplate=a},getActor:function(a){return{UID:this.actorUID,nickname:this.actorNickname}},setActionName:function(a){this.actionName=a;return this},getActionName:function(a){return this.actionName},getTemplateFields:function(){var a=[],b;for(b in this.templateFields)a.push(this.templateFields[b]);
return new gigya.socialize.Collection(a,"fieldName")},setTemplateField:function(a,b,g){this.templateFields[a]={fieldName:a,text:b,href:g};return this},getTemplateField:function(a){return this.templateFields[a]?this.templateFields[a]:null},addTarget:function(a){if("object"==typeof a)return this.targets.push({UID:a.UID,nickname:a.nickname?a.nickname:""}),this;if("string"==typeof a)return this.targets.push({UID:a,nickname:""}),this},addActionLink:function(a,b){this.actionLinks.push({text:a,href:b?b:
""});return this},addMediaItem:function(a){this.mediaItems.push(a);return this},setTitle:function(a){a&&(this.title=a);return this},setLinkBack:function(a){a&&a.toString&&(a=a.toString());a&&(this.linkBack=a);return this},setUserMessage:function(a){this.userMessage=a?a:"";return this},setDescription:function(a){this.description=a?a:"";return this},addImage:function(a,b){this.addMediaItem({type:"image",src:a,href:b})},getImages:function(){return new gigya.socialize.Collection(this.images,"")},getTargets:function(){return new gigya.socialize.Collection(this.targets,
"UID")},setIconURL:function(a){this.iconURL=a;return this},getIconURL:function(){return this.iconURL},getDate:function(){return this.date},setActionData1:function(a){this.actionData1=a;return this},getActionData1:function(a){return this.actionData1},setActionData2:function(a){this.actionData2=a;return this},getActionData2:function(a){return this.actionData2},setSubtitle:function(a){this.subtitle=a;return this},getSubtitle:function(){return this.subtitle}};
(function(a){(function(b){(function(g){function h(a,b){void 0===b&&(b=g.arProviders);for(var c=0;c<b.length;c++)if(b[c].name.toLowerCase()==a.toLowerCase())return b[c]}function f(a){if(null!=a){a=a.split(",");for(var c=0;c<a.length;c++){var e=a[c].replace(/^\s+|\s+$/g,"");b.providers._aliases[e]&&(a[c]=b.providers._aliases[e])}return a.join(",")}}function e(a,b){void 0===b&&(b=g.arProviders);for(var c=0;c<b.length;c++)if(b[c].ID==a)return b[c]}function d(a,b,c){void 0===b&&(b="");void 0===c&&(c=g.arProviders);
b=b.toLowerCase();b=b.split(" ").join("").split(".").join("").toLowerCase().split(",");b=q(b,c);for(c=0;c<b.length;c++)for(var e=0;e<a.length;e++){var d=a[e];(d=d.name||d.toString())&&(d=d.toLowerCase());d==b[c]&&a.splice(e,1)}return a}function c(a,b){null==b&&(b=[]);for(var c=[],e=0;e<a.length;e++){for(var d=a[e],f=!0,g=0;g<b.length;g++){for(var h=!1,l=0;l<d.arDefaultCapabilities.length;l++)if(d.arDefaultCapabilities[l].toLowerCase()==b[g].toLowerCase()){h=!0;break}if(!h){f=!1;break}}f&&c.push(d)}return c}
function l(){return g.arProviders.concat()}function p(b,c){void 0===c&&(c=g.arProviders);b=(""+b).split(" ").join("").split(".").join("").toLowerCase();b=f(b);for(var e=(""+b).split(","),e=q(e,c),d=[],l=0;l<e.length;l++){var k=h(e[l],c);null!=k&&-1==a.utils.array.indexOf(d,k)&&d.push(k)}return d}function q(a,b){b||(b=g.arProviders);for(var c=[],e=0;e<a.length;e++)if("*"==a[e])for(var d=0;d<b.length;d++){for(var f=!1,h=0;h<a.length;h++)a[h].toLowerCase()==b[d].name.toLowerCase()&&(f=!0);f||b[d].explicitOnly||
c.push(b[d].name)}else c.push(a[e]);return c}g._aliases={};var k=function(){function a(b,c,e,d,f,h,l){this.ID=b;this.displayName=c;this.width=e;this.height=d;this.explicitOnly=h;this.aliases=l;this.windowOptions="menubar=0,toolbar=0,resizable=1,scrollbars=1,width="+e+",height="+d;this.arDefaultCapabilities=f.split(",");this.name=c.toLowerCase().split(" ").join("").split("!").join("").split(".").join("").split("+").join("plus");if(l)for(g._aliases||(g._aliases={}),b=l.split("|"),c=0;c<b.length;c++)g._aliases[b[c]]=
this.name;switch(this.name){case "messenger":this.displayName="Microsoft";break;case "customopenid":this.displayName="OpenID";break;case "paypaloauth":this.displayName="PayPal"}}a.prototype.toString=function(){return this.name};return a}();g.Provider=k;g.arProviders=[new k(64,"Facebook",650,400,"login,friends,places,status,actions,photos,offlineaccess,proxiedemail,checkins,facebookactions"),new k(9012,"Twitter",800,440,"login,friends,notifications,actions,status,places,checkins"),new k(72,"Google+",
560,600,"login,friends,contacts",!1,"google|googleplus"),new k(9042,"LinkedIn",865,450,"login,friends,status,actions,notifications"),new k(9803,"Yahoo",500,567,"login,friends,contacts,notifications"),new k(1047,"Messenger",380,540,"login",!1,"messenger|microsoft"),new k(9832,"Instagram",440,420,"login,photos"),new k(9222,"Odnoklassniki",888,425,"login"),new k(9003,"Digg",730,590,"login",!0),new k(9007,"FourSquare",1E3,650,"login,friends,places,checkins"),new k(8191,"Renren",450,350,"login,friends,status,actions"),
new k(8203,"QQ",570,460,"login"),new k(9821,"Sina",640,380,"login,status,actions"),new k(4228,"Mixi",1E3,720,"login,friends,actions,photos",!0),new k(9830,"Yahoo! JAPAN",980,700,"login",!0),new k(8205,"Spiceworks",640,380,"login",!0),new k(8190,"Kaixin",610,510,"login,friends"),new k(9041,"VKontakte",610,510,"login,friends,photos,status,actions"),new k(9800,"AOL",530,720,"login"),new k(4096,"WordPress",700,540,"login"),new k(256,"Blogger",760,400,"login"),new k(16,"LiveJournal",670,360,"login"),new k(1043,
"VeriSign",940,500,"login"),new k(1024,"Typepad",730,590,"login"),new k(4120,"OpenID",730,590,"login"),new k(4218,"Netlog",730,590,"login",!0),new k(4222,"SignOn",870,900,"login",!0),new k(4224,"Orange France",730,590,"login",!0),new k(5002,"Livedoor",970,700,"login",!0),new k(8202,"VZnet",610,510,"login"),new k(9216,"Skyrock",610,510,"login,friends,status",!0),new k(5004,"Fox News",730,590,"login",!0),new k(1051,"PayPal",400,550,"login",!0),new k(9058,"Amazon",785,510,"login",!0),new k(9219,"Xing",
785,510,"login,friends",!0),new k(8206,"WeChat",730,590,"login",!1,"wechat|weixin"),new k(4121,"Custom OpenID",730,590,"login",!0),new k(4122,"Custom SAML",730,590,"login",!0),new k(6002,"Site",730,590,"",!0),new k(1052,"PayPalOAuth",730,590,"login",!0),new k(8207,"Line",730,590,"login")];g.getProviderByName=h;g.replaceProviderAliases=f;g.getProviderById=e;g.hideProvidersByName=d;g.getProvidersForRequiredCapabilities=c;g.getAllProviders=l;g.getProvidersByName=p;g.replaceWildcard=q;a.utils.functions.createAlias("gigya.socialize.getAllProviders",
l);a.utils.functions.createAlias("gigya.socialize.replaceProviderAliases",f);a.utils.functions.createAlias("gigya.socialize.getProvidersByName",p);a.utils.functions.createAlias("gigya.socialize._getProviderByName",h);a.utils.functions.createAlias("gigya.socialize.hideProvidersByName",d);a.utils.functions.createAlias("gigya.socialize._getProviderByID",e);a.utils.functions.createAlias("gigya.socialize.getProvidersForRequiredCapabilities",c)})(b.providers||(b.providers={}))})(a._||(a._={}))})(gigya||
(gigya={}));
(function(a){(function(b){function g(){for(;b.queue&&0<b.queue.length;){var f=a.utils.object.clone(b.queue.splice(0,5),!0,!0);a.gscounters.sendReport({reports:f,noAuth:!h(f)})}}function h(a){for(var b=0;b<a.length;b++){var d=a[b];if("loadc"!==d.name&&"load"!==d.name||"loadc"===d.name&&d.reportData&&d.reportData.actionCounterPath)return!0}return!1}b.queue;b.trackAddressBarShares=function(){if(a.thisScript.globalConf.trackAddressBarShares){var b=a._.apiAdapter.getTokenParam(a.thisScript.APIKey,"UUID"),
e=document.location.href.split("#");1!=e.length&&""!=e[1]||document.location.replace("#guid="+(b?b:"_"))}};b.report=function(f,e,d,c,g,p,q){void 0===p&&(p={});void 0===q&&(q=!1);f=a.utils.object.removeUndefined({name:f,time:(new Date).getTime().toString(),source:c,sourceData:g,reportData:p,cid:d});q?(q=[f],a.gscounters.sendReport({reports:q,noAuth:!h(q)})):(b.queue||(b.queue=[]),b.queue.push(f))};b.init=function(){setInterval(g,5E3)};b.reportLoad=function(a,b){if(!b._reportedLoad){b._reportedLoad=
!0;var d="load";"gigya.socialize.plugins.reactions.showReactionsBarUI"!=a&&("gigya.socialize.plugins.simpleshare.showSimpleShareUI"==a&&(d="loadSimple"),this.report(d,b.APIKey,b.cid,b.source,b.sourceData))}}})(a.reports||(a.reports={}))})(gigya||(gigya={}));
(function(a){(function(b){var g=function(){function g(b,e){void 0===e&&(e=!0);this.params=b;this._logger=a.log;this._eventDispatcher=function(b,e){return a.events.dispatchForWidget(b,e)};this._errorDispatcher=a.events;this._globalEventsManager=a.events.global;this._isDisposed=!1;this._eventWrappers={};this._globalEventHandlers={};this._id=++g.instanceCounter;this.params=b?a.utils.object.clone(b):{};e&&this.validateParams();for(var d in b)this[d]&&(this[d]=b[d])}g.prototype.onErrorEvent=function(){return this.getEvent("onError")};
g.prototype.onDisposedEvent=function(){return this.getEvent("onDisposed")};g.prototype.getType=function(){return this.constructor.name||this.getFunctionName(this.constructor)};g.prototype.getFunctionName=function(a){a=a.toString();a=a.substr(9);return a=a.substr(0,a.indexOf("("))};g.prototype.getConfig=function(){this.error(g.NOT_IMPLEMENTED_ERROR,400096);return{}};g.prototype.toString=function(){return this.getType()+" "+this.id()};g.prototype.id=function(){return this._id};g.prototype.warn=function(a,
b){var d=this.id()+" "+this.getType()+" - "+a;this._logger.addLog(d,b,!0)};g.prototype.error=function(a,b,d){void 0===b&&(b=300001);b={errorMessage:a,errorCode:b,errorDetails:this.id(),info:d};this.warn(a,b);this.dispatchEvent("error",b)};g.prototype.validateParams=function(b){b||(b=this.getConfig().requiredParams||[]);this.getConfig().defaultParams&&(this.params=a.utils.object.merge([this.getConfig().defaultParams,this.params]));var e=[];if(0<b.length)for(var d in b)if(b.hasOwnProperty(d)){var c=
b[d];this.params[c]||e.push(c)}return 0<e.length?(this.dispatchInvalidParamError(e[0]),!1):!0};g.prototype.dispatchEvent=function(a,b){void 0===b&&(b={});b.eventName=a;return this._eventDispatcher(b,this.params)};g.prototype.dispatchErrorFromResponse=function(a){this._errorDispatcher.dispatchErrorFromResponse(this.params,a)};g.prototype.dispatchInvalidParamError=function(a){this._errorDispatcher.dispatchInvalidParamError(this.params,a)};g.prototype.getEvent=function(a){this._eventWrappers[a]||(this.params[a]?
this.params[a]instanceof Array||(this.params[a]=[this.params[a]]):this.params[a]=[],this._eventWrappers[a]=new b.EventWrapper(this.params[a]));return this._eventWrappers[a]};g.prototype.addGlobalEventHandlers=function(a){for(var b in a)a.hasOwnProperty(b)&&this.addGlobalEventHandler(b,a[b])};g.prototype.addGlobalEventHandler=function(a,b,d,c){void 0===d&&(d=null);void 0===c&&(c="socialize");this._globalEventHandlers[a]||(this._globalEventHandlers[a]=[]);b=this._globalEventsManager.add(a,b,"component",
d,c,this.params);this._globalEventHandlers[a].push(b)};g.prototype.removeGlobalEventHandlers=function(a){for(var b in a)a.hasOwnProperty(b)&&this.removeGlobalEventHandler(b,a[b])};g.prototype.removeGlobalEventHandler=function(b,e,d,c){void 0===d&&(d=null);void 0===c&&(c="socialize");if(b=this._globalEventHandlers[b])d=a.utils.array.firstIndex(b,function(a){return a.handler==e}),-1<d&&(c=b[d],this._globalEventsManager.remove(c.fullEventName,c),b.splice(d,1))};g.prototype.prepareCallback=function(a){var b=
this;return function(){for(var d=[],c=0;c<arguments.length;c++)d[c-0]=arguments[c];if(!b._isDisposed)return a.apply(this,d)}};g.prototype.dispose=function(){for(var a in this._globalEventHandlers)for(var b in this._globalEventHandlers[a]){var d=this._globalEventHandlers[a][b];this._globalEventsManager.remove(d.fullEventName,d)}this._globalEventHandlers={};this._eventWrappers={};this.params={};this._isDisposed=!0};g.instanceCounter=0;g.NOT_IMPLEMENTED_ERROR="Abstract method not implemented";return g}();
b.BaseObject=g})(a._||(a._={}))})(gigya||(gigya={}));(function(a){a=a._||(a._={});a=a.DeviceTypes||(a.DeviceTypes={});a[a._undefined=0]="_undefined";a[a.desktop=1]="desktop";a[a.mobile=2]="mobile";a[a.auto=3]="auto"})(gigya||(gigya={}));
(function(a){(function(a){var g=function(){function a(b){void 0===b&&(b=[]);this._handlers=b}a.prototype.add=function(a){this._handlers.push(a)};a.prototype.remove=function(a){a=this._handlers.indexOf(a);-1<a&&this._handlers.splice(a,1)};return a}();a.EventWrapper=g})(a._||(a._={}))})(gigya||(gigya={}));
(function(a){a.build||(a.build={version:"",time:""});a.providersConfig||(a.providersConfig={});a.isGigya||(a.isGigya=!0);a.partnerSettings||(a.partnerSettings={authMode:"cookie",baseDomains:"",plugins:{apiDomain:"us1.gigya.com"}});a.thisScript;var b;(function(a){a.autoLoginInProgress})(b=a._||(a._={}));var g;(function(g){function f(){if(a.abTesting)for(var b in a.abTesting)if("optimizely"===b){var c=a.abTesting[b];if(c.serviceParams&&c.serviceParams.hasOwnProperty("apiKey")){var d=window.location.pathname,
e=!1;if(c.disabledPaths)for(var f=0;f<c.disabledPaths.length;f++)if(-1<c.disabledPaths[f].indexOf(d)){e=!0;break}if(!e)for(f=0;f<c.enabledPaths.length;f++)-1<d.indexOf(c.enabledPaths[f])&&a.utils.script.load("//cdn.optimizely.com/js/"+c.serviceParams.apiKey+".js")}}}function e(){function b(d){var e=c[d];c[d]=function(){for(var b=[],f=0;f<arguments.length;f++)b[f-0]=arguments[f];b=Array.prototype.slice.apply(b);f=b[0];f="object"===typeof f&&null!=f&&f.hasOwnProperty("message")?f:{message:f};a.log.addLog(d,
f,!1);e&&(e.apply?e.apply(c,b):e(b.join(" ")))}}var c=window.console;c||(c={});var d=a.utils.array.getArrayFromString(a.thisScript.globalConf.consoleLogLevel,",");if(0!=d.length){var e=a.log.CONSOLE_LOG_LEVELS;-1==a.utils.array.indexOf(d,"*")&&(e=a.utils.array.intersect(d,e));a.log.selectedConsoleLogLevels=e;a.utils.array.forEach(e,function(a){return b(a)})}}function d(b){"1"==a.utils.cookie.get("gig_debug")?a.socialize.showDebugUI({ignoreApiQueue:!0,waitForDebug:!1,onLoad:b}):b()}function c(){a.utils.functions.invokeOnPageLoad(function(){"undefined"!=
typeof window.gigya_omniture_conf&&a.utils.script.load(a._.getCdnResource("/js/GenesisExchange_Gigya.min.js"))})}function l(a){a||(a="en-US");a=a.replace("_","-").toLowerCase();var b=a.split("-"),c=b[0],b=1<b.length?b[1]:c,b=b.toUpperCase();switch(a){case "es-mx":b="ES";break;case "pt-br":case "zh-cn":case "zh-hk":case "zh-tw":case "te-st":case "fr-inf":case "de-inf":case "es-inf":case "nl-inf":break;default:a=c}return{full:c+"-"+b,langCode:a,countryCode:b}}function p(b){for(var c=document.getElementsByTagName("script"),
d,e=c.length-1;0<=e;e--){var f=c[e],g=f.src.toLowerCase();if(""!=g&&(-1<g.indexOf("//cdn.gigya.com")||-1<g.indexOf("//cdns.gigya.com")||-1<g.indexOf("?apikey="))&&(-1<g.indexOf("gigya.js")||-1<g.indexOf("socialize.js")||-1<g.indexOf("socialize2.js")||-1<g.indexOf("gsjssdk.js"))){d=f;break}}if(d&&!window.__gig_hidescript){var c=d.src.split("/"),e=a.utils.URL.getParamsFromURL(d.src,!0)||{},h;if(""!=d.innerHTML.replace(/^\s+|\s+$/g,""))try{h=a.utils.JSON.deserialize(d.innerHTML),"object"!=typeof h&&
(h={})}catch(k){alert("Gigya global configuration object parse error")}a.thisScript={scriptElement:d,protocol:a.localInfo.protocol,baseDomain:c[2],APIKey:e.apikey,lang:l(e.lang||(h?h.lang:null)),globalConf:a.utils.object.merge([a.partnerSettings.plugins||{},h||{},window.__gigyaConf||{}]),URLParams:e};!a.thisScript.APIKey&&"object"==typeof console&&console.warn?console.warn("**** WARNING - Loading socialize.js without an APIKey parameter is unsupported and may result in an unexpected behavior. ****"):
a.thisScript.globalConf.APIKey=a.thisScript.APIKey;a.thisScript.globalConf.lang=a.thisScript.lang.langCode;b()}else 10>n?(n++,window.setTimeout(function(){p(b)},200)):(a.thisScript={scriptElement:null,protocol:a.localInfo.protocol,baseDomain:"https"==a.localInfo.protocol?"https://cdns.gigya.com":"http://cdn.gigya.com",APIKey:"",lang:l(""),globalConf:{},URLParams:{}},b())}function q(c){var f="web",g=window.__gigAPIAdapterSettings,h=a.localInfo.supportsLocalStorage,l="__gigAPIAdapterSettings_"+a.thisScript.APIKey+
"_"+a.build.version;if(g&&"mobile"==g.getAdapterName()&&g.getAPIKey()==a.thisScript.APIKey)f="mobile",h&&(h={apiKey:g.getAPIKey?g.getAPIKey():null,adapterName:g.getAdapterName?g.getAdapterName():null,features:g.getFeatures?g.getFeatures():null,settings:g.getSettings?g.getSettings():null},a.utils.localStorage.setItem(l,a.utils.JSON.serialize(h)));else if(h){var k=a.utils.JSON.deserialize(a.utils.localStorage.getItem(l));k&&"mobile"==k.adapterName&&(f="mobile",g={},k.apiKey&&(g.getAPIKey=function(){return k.apiKey}),
k.adapterName&&(g.getAdapterName=function(){return k.adapterName}),k.features&&(g.getFeatures=function(){return k.features}),k.settings&&(g.getSettings=function(){return k.settings}))}b.apiAdapter=b.apiAdapters[f].newApiAdapter(g);a.utils.functions.createAlias("gigya.auth.loginToken.getTokenParam",b.apiAdapter.getTokenParam);e();d(function(){b.apiAdapter.init(c)})}function k(){var c=a.utils.URL.getParamsFromURL(document.location.href);c.errorCode&&c.regToken&&b.checkCompleteRegistration(c,a.thisScript.globalConf,
function(){})}function m(){var c=a.localInfo,d;c.isIE11&&!window.indexedDB?(d=b.MessagingMethod.Flash,a.thisScript.globalConf.legacyCrossSiteMethod="localConnection"):d=c.isIOSChrome?b.MessagingMethod.LocalStorageListener:c.supportsPostMessage?b.MessagingMethod.PostMessage:b.MessagingMethod.Flash;c.messagingMethod=d}function r(){a.utils.queue.queueForExecution("API",function(){a.utils.functions.invokeOnPageLoad(function(){a.providersConfig.facebook&&a.external.facebook.load(!1);a.providersConfig.googlePlus&&
a.external.googlePlus.load()})})}var n=0;(function(){if(window._isAPIProxy)b.apiAdapters.web.APIProxy.init();else{a.utils.queue.hold("bootstrap","API");a.partnerSettings.baseDomain=a._.getPageBaseDomain()||document.location.hostname;a.partnerSettings.plugins.originalApiDomain=a.partnerSettings.plugins.apiDomain;var d=a.partnerSettings.plugins,e;e=a.partnerSettings.customAPIDomainPrefix?a.partnerSettings.customAPIDomainPrefix+"."+a.partnerSettings.baseDomain:a.partnerSettings.plugins.apiDomain;d.apiDomain=
e;(a.localInfo.isIE6||a.localInfo.isIE7||a.localInfo.isIE8)&&"undefined"!=typeof console&&"undefined"!=typeof console.log&&console.log("Gigya: It looks like you're using an old version of Internet Explorer. This browser is not supported. Please upgrade to a newer version of IE.");a.reports.init();p(function(){m();a.thisScript.globalConf.customEventMap&&a.events.addMap(a.thisScript.globalConf.customEventMap);q(function(){a.utils.queue.release("bootstrap","API");r();a._.chat.init();a.thisScript.globalConf.autoLogin&&
(a.external.facebook.autoLogin(),a.external.googlePlus.autoLogin());k();a.reports.trackAddressBarShares();a.utils.functions.invokeOnPageLoad(function(){return window.setTimeout(a.socialize.trackReferrals,1E3)})});c();f();"function"==typeof onGigyaServiceReady&&onGigyaServiceReady("socialize");var b={sref:document.referrer};a.thisScript.globalConf.actionCounterPath&&(b.actionCounterPath=a.thisScript.globalConf.actionCounterPath);a.reports.report("loadc",a.thisScript.APIKey,null,null,null,b)})}})()})(g||
(g={}))})(gigya||(gigya={}));
} else if (typeof console == 'object' && console.warn) {
console.warn('**** Socialize.js loaded twice ****');
}
|
// Read the Docs
// http://readthedocs.org/
// Searching as the user types.
(function(){
// Save a reference to the global object.
var root = this;
// Global Search object on which public functions can be added
var Search;
Search = root.Search = {};
// for instituting a delay between keypresses and searches
var timer = null;
var delay = 250;
var lastQuery = null;
var useApi = false;
// Check if the browser supports history manipulation so
// we can change the URL upon instant searches
var replaceStateSupported = (typeof history.replaceState === "function");
// queue of current requests
var xhr = [];
var $input, $button, $results, $title, $selected_facets = null;
function init() {
$input = $('#id_site_search_2');
$button = $('#id_search_button');
$results = $("#id_search_result");
$title = $("#id_search_title");
$selected_facets = $("#id_selected_facets");
// minimum requirements for this script to kick in...
if(!$input.length || !$results.length) {
return false;
} else {
lastQuery = queryString()
bind();
}
}
Search.init = init;
// Setup the bindings for clicking search or keypresses
function bind() {
// Set a delay so not _every_ keystroke sends a search
$input.keyup(function(ev) {
// Don't do anything unless the query has changed
if(lastQuery == queryString()) {
return;
}
if(timer) {
clearTimeout(timer);
}
timer = setTimeout("Search.run()", delay);
});
$button.click(Search.run);
}
// Abort all existing XHR requests, since a new search is starting
function abortCurrentXHR() {
var request = xhr.pop();
while(request) {
request.abort();
request = xhr.pop();
}
}
// Replace the search results HTML with `html` (string)
function replaceResults(html) {
$results.empty();
$results.append(html);
$title.html(getTitle());
$results.show();
}
// Construct the results HTML
// TODO: Use a template!
function buildHTML(results) {
var html = [];
for (var i=0; i<results.length; i++) {
html.push([
'<li class="module-item">',
'<p class="module-item-title">',
'File: <a href="', results[i].absolute_url,
'?highlight=', $("#id_site_search_2").val(), '">',
results[i].project.name,
" - ", results[i].name, "</a>",
"</p>",
"<p>", results[i].text, "</p>",
"</li>"].join('')
);
}
return html.join('');
}
// Pop the last search off the queue and render the `results`
function onResultsReceived(results) {
// remove the request from the queue
xhr.pop();
lastQuery = queryString()
replaceResults(buildHTML(results));
replaceState();
$("#id_remove_facets").attr('href', removeFacetsUrl());
}
// Replace the URL with the one corresponding to the current search
function replaceState() {
if(!replaceStateSupported) {
return;
}
var url = "/search/project/?" + queryString();
var title = getTitle() + ' | Read the Docs';
window.history.replaceState({}, title, url);
}
// Page title
function getTitle() {
return "Results for " + $("#id_site_search_2").val();
}
// Params used in the search
function getSearchData() {
var data = {
q: getKeywords(),
}
var selected_facets = $selected_facets.val() || ''
if(selected_facets) {
data['selected_facets'] = selected_facets;
}
return data;
}
// e.g. q=my+search&selected_facets=project_exact:Read%20The%20Docs
function queryString() {
return jQuery.param(getSearchData());
}
// The active query value
function getKeywords() {
return $input.val()
}
// Url for the current query with any facet filters removed
function removeFacetsUrl() {
return '?' + jQuery.param({q: getKeywords()});
}
// Perform the ajax request to get the search results from the API
function run(ev) {
if(ev) {
ev.preventDefault();
}
abortCurrentXHR();
// Don't do anything if there is no query
if(getKeywords() == '') {
$results.empty();
$results.hide();
$title.html("No search term entered");
return;
}
var data = getSearchData();
if(useApi) {
apiSearch(data);
} else {
htmlSearch(data);
}
}
Search.run = run;
// TODO: The api search is incomplete. It doesn't take into account
// facets nor pagination. It's a partial implemenation.
function apiSearch(data) {
xhr.push(jQuery.ajax({
type: 'GET',
url: "/api/v1/file/search/",
data: data,
dataType: 'jsonp',
success: function(res, text, xhqr) {
onResultsReceived(res.objects);
}
}));
}
// Alternative search implementation not using the API.
function htmlSearch(data) {
xhr.push(jQuery.ajax({
type: 'GET',
url: "/search/project/",
data: data,
success: function(res, text, xhqr) {
onHtmlReceived(res);
}
}));
}
// Alternative implementation not using the API. Receives
// the full HTML including title, pagination, facets, etc.
function onHtmlReceived(html) {
xhr.pop(); // remove the request from the queue
lastQuery = queryString()
$("#search_module").replaceWith(html);
replaceState();
}
}).call(this);
|
import * as types from './actionTypes';
export function addNote(newNote) {
return { type: types.ADD_NOTE, newNote };
}
export function deleteNote(id) {
return { type: types.DELETE_NOTE, id };
}
export function updateNote(updatedNote) {
return { type: types.UPDATE_NOTE, updatedNote };
}
export function getNotes(notes) {
return { type: types.GET_NOTES, notes };
}
export function selectNote(id) {
return { type: types.SELECT_NOTE, id };
}
export function login(userEmail, accessToken) {
return { type: types.LOGIN, userEmail, accessToken };
}
export function logout() {
return { type: types.LOGOUT };
}
export function saveAccessToken(userEmail, accessToken) {
return { type: types.SAVE_ACCESS_TOKEN, userEmail, accessToken };
}
export function authFail(userEmail) {
return { type: types.AUTH_FAIL, userEmail };
}
|
(function (module) {
'use strict';
module.service("Dialog", dialogService);
module.constant("dialogMap", dialogMap());
function dialogMap() {
return {
'product-details': {
controller: 'ProductDetailsController',
templateUrl: '/views/widgets/product-details.html'
},
'category-details': {
controller: 'CategoryDetailsController',
templateUrl: '/views/widgets/category-details.html'
}
};
}
dialogService.$inject = ['$rootScope', '$modal', 'dialogMap'];
function dialogService($rootScope, $modal, dialogMap) {
return {
open: function (id, data, options) {
var dialogContext = dialogMap[id];
var scope = ng.extend($rootScope.$new(), {options: options});
return $modal.open({
templateUrl: dialogContext.templateUrl,
controller: dialogContext.controller,
scope: scope,
resolve: {
data: function () {
return ng.copy(data);
}
}
}).result;
}
};
}
})(ng.module('korann.modal', [])); |
"use strict";
const ID = require("./ID.js");
class Finger{
constructor(node, index){
this.node = node;
this.start = node.id.add(ID.powerOfTwoBuffer(index));
}
}
module.exports = Finger; |
var $$ = React.createElement;
var Substance = require("substance");
var Scrollbar = require("./scrollbar");
var _ = require("substance/helpers");
var PanelMixin = require("./panel_mixin");
var ContentPanelMixin = _.extend({}, PanelMixin, {
contextTypes: {
app: React.PropTypes.object.isRequired,
componentFactory: React.PropTypes.object.isRequired,
},
// Since component gets rendered multiple times we need to update
// the scrollbar and reattach the scroll event
componentDidMount: function() {
var app = this.context.app;
this.updateScrollbar();
$(window).on('resize', this.updateScrollbar);
var doc = app.doc;
doc.connect(this, {
'document:changed': this.onDocumentChange
});
},
componentWillUnmount: function() {
var app = this.context.app
var doc = app.doc;
doc.disconnect(this);
$(window).off('resize');
},
onDocumentChange: function() {
setTimeout(function() {
this.updateScrollbar();
}.bind(this), 0);
},
componentDidUpdate: function() {
this.updateScrollbar();
},
updateScrollbar: function() {
var scrollbar = this.refs.scrollbar;
var panelContentEl = this.refs.panelContent.getDOMNode();
// We need to await next repaint, otherwise dimensions will be wrong
Substance.delay(function() {
scrollbar.update(panelContentEl);
},0);
// (Re)-Bind scroll event on new panelContentEl
$(panelContentEl).off('scroll');
$(panelContentEl).on('scroll', this._onScroll);
},
_onScroll: function(e) {
var panelContentEl = this.refs.panelContent.getDOMNode();
this.refs.scrollbar.update(panelContentEl);
},
// Rendering
// -----------------
getContentEditor: function() {
var app = this.context.app;
var doc = app.doc;
var componentFactory = this.context.componentFactory;
var ContainerClass = componentFactory.get("container");
return $$(ContainerClass, {
doc: doc,
node: doc.get("content"),
ref: "contentEditor"
});
},
render: function() {
var app = this.context.app;
return $$("div", {className: "panel content-panel-component"}, // usually absolutely positioned
$$(Scrollbar, {
id: "content-scrollbar",
contextId: app.state.contextId,
highlights: app.getHighlightedNodes.bind(app),
ref: "scrollbar"
}),
$$('div', {className: "panel-content", ref: "panelContent"}, // requires absolute positioning, overflow=auto
this.getContentEditor()
)
);
}
});
var ContentPanel = React.createClass({
mixins: [ContentPanelMixin],
displayName: "ContentPanel",
});
module.exports = ContentPanel; |
'use strict';
/* jshint maxstatements: 30 */
var chai = require('chai');
var should = chai.should();
var expect = chai.expect;
var bitcore = require('..');
var PublicKey = bitcore.PublicKey;
var Address = bitcore.Address;
var Script = bitcore.Script;
var Networks = bitcore.Networks;
var validbase58 = require('./data/bitcoind/base58_keys_valid.json');
var invalidbase58 = require('./data/bitcoind/base58_keys_invalid.json');
describe('Address', function() {
var pubkeyhash = Buffer.from('4a0529a63fcc33e4f51688311b89b97371b5c76c', 'hex');
var buf = Buffer.concat([Buffer.from([30]), pubkeyhash]);
var str = 'DBtUjAUFWHqS1y8CgetQtPW6YKDhffyFT4';
it('can\'t build without data', function() {
(function() {
return new Address();
}).should.throw('First argument is required, please include address data.');
});
it('should throw an error because of bad network param', function() {
(function() {
return new Address(PKHLivenet[0], 'main', 'pubkeyhash');
}).should.throw('Second argument must be "livenet" or "testnet".');
});
it('should throw an error because of bad type param', function() {
(function() {
return new Address(PKHLivenet[0], 'livenet', 'pubkey');
}).should.throw('Third argument must be "pubkeyhash" or "scripthash"');
});
describe('bitcoind compliance', function() {
validbase58.map(function(d) {
if (!d[2].isPrivkey) {
it('should describe address ' + d[0] + ' as valid', function() {
var type;
if (d[2].addrType === 'script') {
type = 'scripthash';
} else if (d[2].addrType === 'pubkey') {
type = 'pubkeyhash';
}
var network = 'livenet';
if (d[2].isTestnet) {
network = 'testnet';
}
return new Address(d[0], network, type);
});
}
});
invalidbase58.map(function(d) {
it('should describe input ' + d[0].slice(0, 10) + '... as invalid', function() {
expect(function() {
return new Address(d[0]);
}).to.throw(Error);
});
});
});
// livenet valid
var PKHLivenet = [
'D77Z1nmgSZxJTmtN65n2MVF9yvLSB4MpiC',
'DGYdw7jC17b9SappjsrAsaghhDTS8sV5Mx',
'DExWunrSkF2P9NAzW4JpEeC38uC3z36cCk',
'DMYFDsuFamS4kogsiqxQRXK9diCfmJzNLh',
' DQJXChtyuN3aiU3W6pG4mgnykisHH5hqst \t\n'
];
// livenet p2sh
var P2SHLivenet = [
'A7HRQk3GFCW2QasvdZxXuYj8kkQK5QrYLs',
'A3RHoAQLPDSuBewbuvt5NMqEKasqs9ty3C',
'A3YUuiZjn3FzW2i6KqFVgHaN5r5fjvwEJ1',
'AFVkW8WgPP2rsTdAeyogFK9k8gXJ1LZwrb',
'A2CUbyEtqGUjngAjxpGmM5Nwhrz72gh23v',
'\t \AD21pKoCWcrqrUW4oRv5xUaGwCfXhiyx6y \r'
];
// testnet p2sh
var P2SHTestnet = [
'2MsvyG12kxxipe276Au4zKqvd2xdrBuHWb3',
'2MvY1BBau2C6jRC1hNX5LmviLrpvVG386TM',
'2N22vuiMGhfqD77vPqsXPiALBfn6oUTtFtH',
'2N1Gz97rN7P6VCj9xf64wWFqQZgpUng1mM3'
];
//livenet bad checksums
var badChecksums = [
'461QQ2sYWxU7H2PV4oBwJGNch8XVTYYbZxU',
'461QQ2sYWxASd2PV4oBwJGNch8XVTYYbZxU',
'DRjyUS2uuieEPkhZNdQz8hE5YycxVEqSXA', ///////
];
//livenet non-base58
var nonBase58 = [
'15vkcKf7g#23wLAnZLmb$uMiiVDc3nq4a2',
'1A601ttWnUq1SEQLMr4ttDh24wcbj4w2TT',
'1BpbpfLdY7oBS9gK7aIXgvMgr1DpvNH3B2',
'1Jz2yCRdOST1p2gUqFB5wsSQfdmEJaffg7'
];
//testnet valid
var PKHTestnet = [
'ngbSgr1dhCqsLg6Z5tpsaCspwrH72x2Zk3',
'ngao4q8auS6YuDKYPkzjt7zKYYT8LzkGZS',
'nbo7vyCuiMxiYW4thwwuaTHQdCoqinmzJz',
'nagGnGDKWYpvnphf9rgo3xtQhAxiEM1QGD'
];
describe('validation', function() {
it('getValidationError detects network mismatchs', function() {
var error = Address.getValidationError('D77Z1nmgSZxJTmtN65n2MVF9yvLSB4MpiC', 'testnet');
should.exist(error);
});
it('isValid returns true on a valid address', function() {
var valid = Address.isValid('D77Z1nmgSZxJTmtN65n2MVF9yvLSB4MpiC', 'livenet');
valid.should.equal(true);
});
it('isValid returns false on network mismatch', function() {
var valid = Address.isValid('D77Z1nmgSZxJTmtN65n2MVF9yvLSB4MpiC', 'testnet');
valid.should.equal(false);
});
it('validates correctly the P2PKH test vector', function() {
for (var i = 0; i < PKHLivenet.length; i++) {
var error = Address.getValidationError(PKHLivenet[i]);
should.not.exist(error);
}
});
it('validates correctly the P2SH test vector', function() {
for (var i = 0; i < P2SHLivenet.length; i++) {
var error = Address.getValidationError(P2SHLivenet[i]);
should.not.exist(error);
}
});
it('validates correctly the P2SH testnet test vector', function() {
for (var i = 0; i < P2SHTestnet.length; i++) {
var error = Address.getValidationError(P2SHTestnet[i], 'testnet');
should.not.exist(error);
}
});
it('rejects correctly the P2PKH livenet test vector with "testnet" parameter', function() {
for (var i = 0; i < PKHLivenet.length; i++) {
var error = Address.getValidationError(PKHLivenet[i], 'testnet');
should.exist(error);
}
});
it('validates correctly the P2PKH livenet test vector with "livenet" parameter', function() {
for (var i = 0; i < PKHLivenet.length; i++) {
var error = Address.getValidationError(PKHLivenet[i], 'livenet');
should.not.exist(error);
}
});
it('should not validate if checksum is invalid', function() {
for (var i = 0; i < badChecksums.length; i++) {
var error = Address.getValidationError(badChecksums[i], 'livenet', 'pubkeyhash');
should.exist(error);
error.message.should.equal('Checksum mismatch');
}
});
it('should not validate on a network mismatch', function() {
var error, i;
for (i = 0; i < PKHLivenet.length; i++) {
error = Address.getValidationError(PKHLivenet[i], 'testnet', 'pubkeyhash');
should.exist(error);
error.message.should.equal('Address has mismatched network type.');
}
for (i = 0; i < PKHTestnet.length; i++) {
error = Address.getValidationError(PKHTestnet[i], 'livenet', 'pubkeyhash');
should.exist(error);
error.message.should.equal('Address has mismatched network type.');
}
});
it('should not validate on a type mismatch', function() {
for (var i = 0; i < PKHLivenet.length; i++) {
var error = Address.getValidationError(PKHLivenet[i], 'livenet', 'scripthash');
should.exist(error);
error.message.should.equal('Address has mismatched type.');
}
});
it('should not validate on non-base58 characters', function() {
for (var i = 0; i < nonBase58.length; i++) {
var error = Address.getValidationError(nonBase58[i], 'livenet', 'pubkeyhash');
should.exist(error);
error.message.should.equal('Non-base58 character');
}
});
it('testnet addresses are validated correctly', function() {
for (var i = 0; i < PKHTestnet.length; i++) {
var error = Address.getValidationError(PKHTestnet[i], 'testnet');
should.not.exist(error);
}
});
it('addresses with whitespace are validated correctly', function() {
var ws = ' \r \t \n DD4KSSuBJqcjuTcvUg1CgUKeurPUFeEZkE \t \n \r';
var error = Address.getValidationError(ws);
should.not.exist(error);
Address.fromString(ws).toString().should.equal('DD4KSSuBJqcjuTcvUg1CgUKeurPUFeEZkE');
});
});
describe('instantiation', function() {
it('can be instantiated from another address', function() {
var address = Address.fromBuffer(buf);
var address2 = new Address({
hashBuffer: address.hashBuffer,
network: address.network,
type: address.type
});
address.toString().should.equal(address2.toString());
});
});
describe('encodings', function() {
it('should make an address from a buffer', function() {
Address.fromBuffer(buf).toString().should.equal(str);
new Address(buf).toString().should.equal(str);
new Address(buf).toString().should.equal(str);
});
it('should make an address from a string', function() {
Address.fromString(str).toString().should.equal(str);
new Address(str).toString().should.equal(str);
});
it('should make an address using a non-string network', function() {
Address.fromString(str, Networks.livenet).toString().should.equal(str);
});
it('should error because of unrecognized data format', function() {
(function() {
return new Address(new Error());
}).should.throw(bitcore.errors.InvalidArgument);
});
it('should error because of incorrect format for pubkey hash', function() {
(function() {
return new Address.fromPublicKeyHash('notahash');
}).should.throw('Address supplied is not a buffer.');
});
it('should error because of incorrect format for script hash', function() {
(function() {
return new Address.fromScriptHash('notascript');
}).should.throw('Address supplied is not a buffer.');
});
it('should error because of incorrect type for transform buffer', function() {
(function() {
return Address._transformBuffer('notabuffer');
}).should.throw('Address supplied is not a buffer.');
});
it('should error because of incorrect length buffer for transform buffer', function() {
(function() {
return Address._transformBuffer(new Buffer(20));
}).should.throw('Address buffers must be exactly 21 bytes.');
});
it('should error because of incorrect type for pubkey transform', function() {
(function() {
return Address._transformPublicKey(new Buffer(20));
}).should.throw('Address must be an instance of PublicKey.');
});
it('should error because of incorrect type for script transform', function() {
(function() {
return Address._transformScript(new Buffer(20));
}).should.throw('Invalid Argument: script must be a Script instance');
});
it('should error because of incorrect type for string transform', function() {
(function() {
return Address._transformString(new Buffer(20));
}).should.throw('data parameter supplied is not a string.');
});
it('should make an address from a pubkey hash buffer', function() {
var hash = pubkeyhash; //use the same hash
var a = Address.fromPublicKeyHash(hash, 'livenet');
a.network.should.equal(Networks.livenet);
a.toString().should.equal(str);
var b = Address.fromPublicKeyHash(hash, 'testnet');
b.network.should.equal(Networks.testnet);
b.type.should.equal('pubkeyhash');
new Address(hash, 'livenet').toString().should.equal(str);
});
it('should make an address using the default network', function() {
var hash = pubkeyhash; //use the same hash
var network = Networks.defaultNetwork;
Networks.defaultNetwork = Networks.livenet;
var a = Address.fromPublicKeyHash(hash);
a.network.should.equal(Networks.livenet);
// change the default
Networks.defaultNetwork = Networks.testnet;
var b = Address.fromPublicKeyHash(hash);
b.network.should.equal(Networks.testnet);
// restore the default
Networks.defaultNetwork = network;
});
it('should throw an error for invalid length hashBuffer', function() {
(function() {
return Address.fromPublicKeyHash(buf);
}).should.throw('Address hashbuffers must be exactly 20 bytes.');
});
it('should make this address from a compressed pubkey', function() {
var pubkey = new PublicKey('02789418bb8aee5a63471c09d3402b9d06a1c3d7975635a4a5258e89dff3547079');
var address = Address.fromPublicKey(pubkey, 'livenet');
address.toString().should.equal('DKLLdArnsyhkuPhxDbWYEBgLpQDLerRNrZ');
});
it('should use the default network for pubkey', function() {
var pubkey = new PublicKey('02789418bb8aee5a63471c09d3402b9d06a1c3d7975635a4a5258e89dff3547079');
var address = Address.fromPublicKey(pubkey);
address.network.should.equal(Networks.defaultNetwork);
});
it('should make this address from an uncompressed pubkey', function() {
var pubkey = new PublicKey('0450A38BD7F0AC212FEBA77354A9B036A32E0F7C81FC4E0C5ADCA7C549C4505D2522458C2D9AE3CEFD684E039194B72C8A10F9CB9D4764AB26FCC2718D421D3B84');
var a = Address.fromPublicKey(pubkey, 'livenet');
a.toString().should.equal('DFJ1z7FVd8CEodkQ41w54bmCDYhrNd24Dv');
var b = new Address(pubkey, 'livenet', 'pubkeyhash');
b.toString().should.equal('DFJ1z7FVd8CEodkQ41w54bmCDYhrNd24Dv');
});
it('should classify from a custom network', function() {
var custom = {
name: 'customnetwork',
pubkeyhash: 0x1c,
privatekey: 0x1e,
scripthash: 0x28,
xpubkey: 0x02e8de8f,
xprivkey: 0x02e8da54,
networkMagic: 0x0c110907,
port: 7333
};
var addressString = 'CX4WePxBwq1Y6u7VyMJfmmitE7GiTgC9aE';
Networks.add(custom);
var network = Networks.get('customnetwork');
var address = Address.fromString(addressString);
address.type.should.equal(Address.PayToPublicKeyHash);
address.network.should.equal(network);
Networks.remove(network);
});
describe('from a script', function() {
it('should fail to build address from a non p2sh,p2pkh script', function() {
var s = new Script('OP_CHECKMULTISIG');
(function() {
return new Address(s);
}).should.throw('needs to be p2pkh in, p2pkh out, p2sh in, or p2sh out');
});
it('should make this address from a p2pkh output script', function() {
var s = new Script('OP_DUP OP_HASH160 20 ' +
'0xc8e11b0eb0d2ad5362d894f048908341fa61b6e1 OP_EQUALVERIFY OP_CHECKSIG');
var buf = s.toBuffer();
var a = Address.fromScript(s, 'livenet');
a.toString().should.equal('DPTFMF1EYh2tYtGwWJgFqLy37QgLdSSDQW');
var b = new Address(s, 'livenet');
b.toString().should.equal('DPTFMF1EYh2tYtGwWJgFqLy37QgLdSSDQW');
});
it('should make this address from a p2sh input script', function() {
var s = Script.fromString('OP_HASH160 20 0xa6ed4af315271e657ee307828f54a4365fa5d20f OP_EQUAL');
var a = Address.fromScript(s, 'livenet');
a.toString().should.equal('A7eu6dAkyaNZJpjXwSqgUipxxvKTTjJKzY');
var b = new Address(s, 'livenet');
b.toString().should.equal('A7eu6dAkyaNZJpjXwSqgUipxxvKTTjJKzY');
});
it('returns the same address if the script is a pay to public key hash out', function() {
var address = 'D77Z1nmgSZxJTmtN65n2MVF9yvLSB4MpiC';
var script = Script.buildPublicKeyHashOut(new Address(address));
console.log(script);
Address(script, Networks.livenet).toString().should.equal(address);
});
it('returns the same address if the script is a pay to script hash out', function() {
var address = 'A7eu6dAkyaNZJpjXwSqgUipxxvKTTjJKzY';
var script = Script.buildScriptHashOut(new Address(address));
Address(script, Networks.livenet).toString().should.equal(address);
});
});
it('should derive from this known address string livenet', function() {
var address = new Address(str);
var buffer = address.toBuffer();
var slice = buffer.slice(1);
var sliceString = slice.toString('hex');
sliceString.should.equal(pubkeyhash.toString('hex'));
});
it('should derive from this known address string testnet', function() {
var a = new Address(PKHTestnet[0], 'testnet');
var b = new Address(a.toString());
b.toString().should.equal(PKHTestnet[0]);
b.network.should.equal(Networks.testnet);
});
it('should derive from this known address string livenet scripthash', function() {
var a = new Address(P2SHLivenet[0], 'livenet', 'scripthash');
var b = new Address(a.toString());
b.toString().should.equal(P2SHLivenet[0]);
});
it('should derive from this known address string testnet scripthash', function() {
var address = new Address(P2SHTestnet[0], 'testnet', 'scripthash');
address = new Address(address.toString());
address.toString().should.equal(P2SHTestnet[0]);
});
});
describe('#toBuffer', function() {
it('3c3fa3d4adcaf8f52d5b1843975e122548269937 corresponds to hash LQiX3WFFnc6JDULSRRG3Dsjza3VmhJ5pCP', function() {
var address = new Address(str);
address.toBuffer().slice(1).toString('hex').should.equal(pubkeyhash.toString('hex'));
});
});
describe('#object', function() {
it('roundtrip to-from-to', function() {
var obj = new Address(str).toObject();
var address = Address.fromObject(obj);
address.toString().should.equal(str);
});
it('will fail with invalid state', function() {
expect(function() {
return Address.fromObject('¹');
}).to.throw(bitcore.errors.InvalidState);
});
});
describe('#toString', function() {
it('livenet pubkeyhash address', function() {
var address = new Address(str);
address.toString().should.equal(str);
});
it('scripthash address', function() {
var address = new Address(P2SHLivenet[0]);
address.toString().should.equal(P2SHLivenet[0]);
});
it('testnet scripthash address', function() {
var address = new Address(P2SHTestnet[0]);
address.toString().should.equal(P2SHTestnet[0]);
});
it('testnet pubkeyhash address', function() {
var address = new Address(PKHTestnet[0]);
address.toString().should.equal(PKHTestnet[0]);
});
});
describe('#inspect', function() {
it('should output formatted output correctly', function() {
var address = new Address(str);
var output = '<Address: DBtUjAUFWHqS1y8CgetQtPW6YKDhffyFT4, type: pubkeyhash, network: livenet>';
address.inspect().should.equal(output);
});
});
describe('questions about the address', function() {
it('should detect a P2SH address', function() {
new Address(P2SHLivenet[0]).isPayToScriptHash().should.equal(true);
new Address(P2SHLivenet[0]).isPayToPublicKeyHash().should.equal(false);
new Address(P2SHTestnet[0]).isPayToScriptHash().should.equal(true);
new Address(P2SHTestnet[0]).isPayToPublicKeyHash().should.equal(false);
});
it('should detect a Pay To PubkeyHash address', function() {
new Address(PKHLivenet[0]).isPayToPublicKeyHash().should.equal(true);
new Address(PKHLivenet[0]).isPayToScriptHash().should.equal(false);
new Address(PKHTestnet[0]).isPayToPublicKeyHash().should.equal(true);
new Address(PKHTestnet[0]).isPayToScriptHash().should.equal(false);
});
});
it('throws an error if it couldn\'t instantiate', function() {
expect(function() {
return new Address(1);
}).to.throw(TypeError);
});
it('can roundtrip from/to a object', function() {
var address = new Address(P2SHLivenet[0]);
expect(new Address(address.toObject()).toString()).to.equal(P2SHLivenet[0]);
});
it('will use the default network for an object', function() {
var obj = {
hash: '19a7d869032368fd1f1e26e5e73a4ad0e474960e',
type: 'scripthash'
};
var address = new Address(obj);
address.network.should.equal(Networks.defaultNetwork);
});
describe('creating a P2SH address from public keys', function() {
var public1 = '02da5798ed0c055e31339eb9b5cef0d3c0ccdec84a62e2e255eb5c006d4f3e7f5b';
var public2 = '0272073bf0287c4469a2a011567361d42529cd1a72ab0d86aa104ecc89342ffeb0';
var public3 = '02738a516a78355db138e8119e58934864ce222c553a5407cf92b9c1527e03c1a2';
var publics = [public1, public2, public3];
it('can create an address from a set of public keys', function() {
var address = Address.createMultisig(publics, 2, Networks.livenet);
address.toString().should.equal('A6e68GnkmTokZV8xtaRPw7BTBVBCeFFwuT');
address = new Address(publics, 2, Networks.livenet);
address.toString().should.equal('A6e68GnkmTokZV8xtaRPw7BTBVBCeFFwuT');
});
it('works on testnet also', function() {
var address = Address.createMultisig(publics, 2, Networks.testnet);
address.toString().should.equal('2N7T3TAetJrSCruQ39aNrJvYLhG1LJosujf');
});
it('can also be created by Address.createMultisig', function() {
var address = Address.createMultisig(publics, 2);
var address2 = Address.createMultisig(publics, 2);
address.toString().should.equal(address2.toString());
});
it('fails if invalid array is provided', function() {
expect(function() {
return Address.createMultisig([], 3, 'testnet');
}).to.throw('Number of required signatures must be less than or equal to the number of public keys');
});
});
});
|
import $ from "jquery";
import _ from "underscore";
import "bootstrap";
import "jquery-deparam";
import "./configure_datatables";
import View from "../view";
import Cache from "../cache";
import ColumnManager from "./column_manager";
import SelectionManager from "./selection_manager";
import LockManager from "./lock_manager";
import FilterView from "./filter_view";
import { extractColumnCSSClass, toColumnCSSClass } from "../utils/css";
import cidMap from "./cid_map";
import Config from "./config";
class LocalDataTable extends View {
constructor(options) {
super(options);
this.options = options || {};
// copy over certain properties from options to the table itself
_.extend(this, _.pick(this.options, ["selectedIds", "paginate"]));
_.bindAll(this, "_onRowCreated", "_onBulkHeaderClick", "_onBulkRowClick", "_bulkCheckboxAdjust", "_onDraw",
"_onColumnVisibilityChange", "_onColumnReorder");
this._initKeyWithValueOrDefault('urlPagination', this.options.urlPagination, true);
this.urlPagination = this.urlPagination && this.paginate;
this.cache = new Cache();
this.selectionManager = new SelectionManager();
this.rowClass = this.options.rowClass || this._resolveRowClass();
this.config = this.options.config || (this._configFromPlugin && this._configFromPlugin()) || new Config();
this._applyDefaults();
this._columnManager = new ColumnManager(this);
this._lockManager = new LockManager(this);
this.listenTo(this.collection, "add", this._onAdd);
this.listenTo(this.collection, "remove", this._onRemove);
this.listenTo(this.collection, "reset", this._onReset);
}
_initKeyWithValueOrDefault(key, value, defaultValue) {
if (this[key] === undefined) {
if (value !== undefined) {
this[key] = value;
} else {
this[key] = defaultValue;
}
}
}
availableColumnTypes() {
return this.config.columnTypes;
}
// apply filtering
filter(...args) {
this._lockManager.ensureUnlocked("filter");
this.dataTable.fnFilter(...args);
}
// change pagination
page(...args) {
this._lockManager.ensureUnlocked("page");
return this.dataTable.fnPageChange(...args);
}
// sort specific columns
sort(...args) {
this._lockManager.ensureUnlocked("sort");
return this.dataTable.fnSort(...args);
}
selectedModels() {
this._lockManager.ensureUnlocked("bulk");
return this.selectionManager.models();
}
render() {
this.$el.html(this.template);
this._dataTableCreate();
this._initBulkHandling();
this._enableRowHighlight();
this.paginate && this._initPaginationHandling();
this._triggerChangeSelection();
this.urlPagination && this._setupPaginationHistory();
this.trigger("render");
this._afterRender();
return this;
}
renderColumn(id) {
const config = this._columnManager.columnConfigForId(id);
if (!config) {
throw new Error("column not found");
}
this.cache.each(row => {
row.renderColumnByConfig(config);
});
}
selectAllVisible(state) {
this._lockManager.ensureUnlocked("bulk");
this.bulkCheckbox.prop("checked", state);
_.each(this._visibleRowsOnCurrentPage(), function(row) {
this._setRowSelectedState(row.model, row, state);
}, this);
this._triggerChangeSelection({ selectAllVisible: state });
}
selectAllMatching() {
this._lockManager.ensureUnlocked("bulk");
if (!this.paginate) throw new Error("#selectAllMatching can only be used with paginated tables");
_.each(this._allMatchingModels(), function(model) {
this._setRowSelectedState(model, this.cache.get(model), true);
}, this);
this._triggerChangeSelection();
}
matchingCount() {
this._lockManager.ensureUnlocked("bulk");
return this.dataTable.fnSettings().aiDisplay.length;
}
totalRecordsCount() {
this._lockManager.ensureUnlocked("bulk");
return this.dataTable.fnSettings().fnRecordsTotal();
}
pageLimit() {
return this.dataTable.fnSettings()._iDisplayLength;
}
columnRequired(state, id) {
if (!state && this._columnManager.columnConfigForId(id).required) {
throw new Error("can not disable visibility when column is required");
}
}
columnVisibility(attr, state) {
if (arguments.length === 1) {
// getter
return this._columnManager.visibility.get(attr);
} else {
this.columnRequired(state, attr);
this._columnManager.visibility.set(attr, state);
state && this.renderColumn(attr);
}
}
// takes a hash of { columnAttr: columnState, ... }
setColumnVisibilities(columns) {
_.each(columns, this.columnRequired, this);
this._columnManager.visibility.set(columns);
_.each(columns, function(state, attr) {
state && this.renderColumn(attr);
}, this);
}
restoreColumnVisibility() {
_.each(this.columnsConfig(), function(column) {
if (column.id) {
this.columnVisibility(column.id, column.visible);
}
}, this);
}
columnOrder(order) {
if (this._reorderableColumnsEnabled()) {
this._changeColumnOrder(order);
}
}
restoreColumnOrder() {
if (this._reorderableColumnsEnabled()) {
this._changeColumnOrder({ reset: true });
}
}
changeSorting(sorting) {
this._columnManager.changeSorting(sorting);
if (this.dataTable) {
const normalizeSortingColumn = sort => _.first(sort, 2);
sorting = _.map(this._columnManager.dataTableSortingConfig(), normalizeSortingColumn);
let currentSorting = _.map(this.dataTable.fnSettings().aaSorting, normalizeSortingColumn);
if (!_.isEqual(currentSorting, sorting)) {
this.dataTable.fnSort(sorting);
}
}
}
lock(name, state) {
if (arguments.length === 1) {
// getter
return this._lockManager.lock(name);
} else if (arguments.length === 2) {
// setter
this._lockManager.lock(name, state);
} else {
throw new Error("#lock requires a name and/or a state");
}
}
columnsConfig() {
return this._columnManager.columnsConfig();
}
configGenerator() {
return this._columnManager._configGenerator;
}
disableFilters(errorMessage) {
const columns = this.columnsConfig();
for (const c in columns) {
if (!columns[c].filter) continue;
this.child(`filter-${columns[c].id}`).disableFilter(errorMessage);
}
}
enableFilters() {
const columns = this.columnsConfig();
for (const c in columns) {
if (!columns[c].filter) continue;
this.child(`filter-${columns[c].id}`).enableFilter();
}
}
updateAjaxSource() {
// get ajax url
const ajaxURL = this.dataTable.fnSettings().sAjaxSource;
// get the endpoint of ajax url
const splitUrl = ajaxURL.split("?");
const endpoint = splitUrl[0];
// Early exit if no params
if (!splitUrl[1]) {
return;
}
// get parameters of ajax url
const params = $.deparam(splitUrl[1]);
// make ext_filter_json param the same as the current url, now with new filters
params.ext_filter_json = JSON.stringify(this.configGenerator()._getUrlFilterParams());
// Build new url with old endpoint but new params
const newURL = `${endpoint}?${$.param(params)}`;
// Update datatable ajax source
this.dataTable.fnSettings().sAjaxSource = newURL;
// trigger "filter:column" event
this._onColumnFilter();
}
columnElements(selector) {
const selectorString = selector || "";
return this.$("table").find(`thead tr th${selectorString}`);
}
// Private APIs
_enableReorderableColumns() {
const self = this;
self._colReorder = new $.fn.dataTable.ColReorder(this.dataTable, {
fnReorderCallback(fromIndex, toIndex) {
// notify that columns have been externally rearranged
self._columnManager.columnsSwapped(fromIndex, toIndex);
// pass event up
self._onColumnReorder();
},
bAddFixed: false,
bResizeTableWrapper: false,
allowHeaderDoubleClick: false,
allowResize: self.resizableColumns,
// iFixedColumns configures how many columns should be unmovable starting from left
// if the first column is the bulk column we make it unmovable
iFixedColumns: this.$el.find(this.BULK_COLUMN_HEADER_CHECKBOX_SELECTOR).length
});
}
_renderGrandTotalsRow() {
let hasGrandTotalsCell = false;
// if dataTable is available AND we have a totals row
if (this.dataTable && this.totalsRow) {
// If we don't have a footer rendered, render it
if (this.dataTable.find("tfoot").length < 1) {
this.dataTable.append("<tfoot><tr></tr></tfoot>");
}
// Clear the footer
const $grandTotalsRow = this.dataTable.find("tfoot tr");
$grandTotalsRow.html("");
// Iterate over the current columns config
this.columnsConfig().forEach(col => {
if (this.columnVisibility(col.id) || col.bulk) {
const node = $("<td>");
// If column is a non totals column, draw "Grand totals" on the first one and the rest are empty
if (this.isNontotalsColumn && this.isNontotalsColumn(col)) {
if (hasGrandTotalsCell) {
$grandTotalsRow.append(node);
} else {
hasGrandTotalsCell = true;
col.grandTotalRenderer ? col.grandTotalRenderer.apply(this.totalsRow, [node, col]) : node.text("Grand Total");
$grandTotalsRow.append(node);
}
} else {
(col.grandTotalRenderer || col.renderer).apply(this.totalsRow, [node, col]);
$grandTotalsRow.append(node);
}
}
});
}
}
_renderHeaderGroup() {
if (!_.isEmpty(this.rowClass.prototype.columnGroupDefinitions)) {
const columnGroups = this.rowClass.prototype.columnGroupDefinitions;
let tr = this.$("table").find('thead tr.header-groups-row');
if (tr.length === 0) {
tr = $('<tr class="header-groups-row">');
} else {
tr.empty();
}
const uniqueHeaderGroupDataIndex = {};
_.each(this._columnManager._visibilitySummary().visible, col => {
const columnConfig = _.findWhere(this._columnManager.columnsConfig(), { attr: col });
let headerGroupDataIndex = columnConfig.headerGroupDataIndex;
let columnGroupConfig = _.findWhere(columnGroups, { "headerGroupDataIndex": headerGroupDataIndex });
if (!columnGroupConfig || !headerGroupDataIndex) {
console.log(`Unable to find a matching headerGroupDataIndex for ${columnConfig.attr}`);
columnGroupConfig = { colspan: 1, headerName: '' };
headerGroupDataIndex = columnConfig.title;
}
if (columnGroupConfig && !uniqueHeaderGroupDataIndex[headerGroupDataIndex]) {
uniqueHeaderGroupDataIndex[headerGroupDataIndex] = true;
tr.append(`<th colspan="${columnGroupConfig.colspan}" class="header-groups">${columnGroupConfig.headerName}</th>`);
}
});
this.$("table").find('thead').prepend(tr);
}
}
// Changes or resets the column order.
// When called with no args, returns the current order.
// Call with { reset : true } to have it restore column order to initial configuration
// Provide array of indexes as first argument to have it reordered by that
_changeColumnOrder(order) {
if (this._colReorder) {
const columnsOrig = _.clone(this.dataTable.fnSettings().aoColumns);
if (_.isArray(order)) {
this._colReorder.fnOrder(order);
} else if (_.has(order, 'reset') && order.reset) {
this._colReorder.fnReset();
} else {
return this._colReorder.fnOrder();
}
// restore columnsConfig order to match the underlying order from dataTable
const columnsConfig = this.columnsConfig();
const columnsConfigOrig = _.clone(columnsConfig);
// reset config
columnsConfig.splice(0, columnsConfig.length);
// fill in config in correct order
_.each(this.dataTable.fnSettings().aoColumns, tableColumn => {
const oldIndex = columnsOrig.indexOf(tableColumn);
if (oldIndex !== -1) {
columnsConfig.push(columnsConfigOrig[oldIndex]);
}
});
this._columnManager.columnsReordered();
}
}
_allMatchingModels() {
// returns all models matching the current filter criteria, regardless of pagination
// since we are using deferred rendering, the dataTable.$ and dataTable._ methods don't return all
// matching data since some of the rows may not have been rendered yet.
// here we use the the aiDisplay property to get indicies of the data matching the current filtering
// and return the associated models
return _.map(this.dataTable.fnSettings().aiDisplay, function(index) {
return this.collection.at(index);
}, this);
}
_applyDefaults() {
_.defaults(this, {
sorting: [[0, this.paginate ? "desc" : "asc"]]
});
if (!this.objectName.plural) {
throw new Error("plural object name must be provided");
} else if (!this.objectName.singular) {
throw new Error("singular object name must be provided");
}
}
// returns row objects that have not been filtered out and are on the current page
_visibleRowsOnCurrentPage() {
// non-paginated tables will return all rows, ignoring the page param
const visibleRowsCurrentPageArgs = { filter: "applied", page: "current" };
return this.dataTable.$("tr", visibleRowsCurrentPageArgs).map((index, node) => $(node).data("row"));
}
_setRowSelectedState(model, row, state) {
this.selectionManager.process(model, state);
// the row may not exist yet as we utilize deferred rendering. we track the model as
// selected and make the ui reflect this when the row is finally created
row && row.bulkState(state);
}
_dataTableCreate() {
this.dataTable = this.$("table").dataTable(this._dataTableConfig());
this._setupSelect2PaginationAttributes();
this._installSortInterceptors();
this.filteringEnabled && this._setupFiltering();
if (this._reorderableColumnsEnabled()) {
this._enableReorderableColumns();
}
this._columnManager.on("change:visibility", this._onColumnVisibilityChange);
this._columnManager.applyVisibilityPreferences();
this._renderHeaderGroup();
if (this.collection.length) this._onReset(this.collection);
// if resizeable, add resizeable class
if (this._colReorder && this._colReorder.s.allowResize) {
this.$("table").addClass("dataTable-resizeableColumns");
}
if (this.striped) {
this.$("table").addClass("table-striped");
}
}
_areAllVisibleRowsSelected() {
let allSelected;
const visibleRows = this._visibleRowsOnCurrentPage();
if (visibleRows.length) {
allSelected = _.all(visibleRows, row => row.bulkState() === true);
} else {
// have no selections does not count as having all selected
allSelected = false;
}
return allSelected;
}
// when changing between pages / filters we set the header bulk checkbox state based on whether all newly visible rows are selected or not
// note: we defer execution as the "page" and "filter" events are called before new rows are swapped in
// this allows our code to run after the all the new rows are inserted
_bulkCheckboxAdjust() {
if (!this.bulkCheckbox) return;
_.defer(() => {
this.bulkCheckbox.prop("checked", this._areAllVisibleRowsSelected());
});
}
// Do not enable when columnGroupDefinitions is defined and not empty.
_reorderableColumnsEnabled() {
return this.reorderableColumns && _.isEmpty(this.rowClass.prototype.columnGroupDefinitions);
}
_initPaginationHandling() {
this.dataTable.on("page", this._bulkCheckboxAdjust);
}
_setQueryStringPageFromDataTable() {
let page = this.dataTable.fnPagingInfo().iPage;
if (page !== this._parsePageNumberFromQueryString() - 1) {
history.pushState({}, "pagination", this._createQueryStringWithPageNumber(page + 1));
}
}
_setupPaginationHistory() {
this.dataTable.on("page", () => {
this._setQueryStringPageFromDataTable();
});
this.dataTable.on("pageLengthChange", () => {
this._setQueryStringPageFromDataTable();
});
window.onpopstate = () => {
this._goToPageFromQueryString();
};
}
_afterRender() {
if (this.urlPagination) {
this._goToPageFromQueryString();
}
}
_goToPageFromQueryString() {
let pageNumber = this._parsePageNumberFromQueryString() - 1;
if (pageNumber >= 0) {
this.page(pageNumber);
}
}
_urlParameters() {
return $.deparam(window.location.href.split("?")[1] || "");
}
_createQueryStringWithPageNumber(pageNumber) {
let urlParameters = this._urlParameters();
urlParameters.page = pageNumber;
return "?" + $.param(urlParameters);
}
_parsePageNumberFromQueryString() {
let parameters = this._urlParameters();
let page = parseInt(parameters.page);
if (isNaN(page)) {
return 1;
} else {
return page;
}
}
_initBulkHandling() {
const bulkCheckbox = this.$el.find(this.BULK_COLUMN_HEADER_CHECKBOX_SELECTOR);
if (!bulkCheckbox.length) return;
this.bulkCheckbox = bulkCheckbox;
this.bulkCheckbox.click(this._onBulkHeaderClick);
this.dataTable.on("click", this.BULK_COLUMN_CHECKBOXES_SELECTOR, this._onBulkRowClick);
this.dataTable.on("filter", this._bulkCheckboxAdjust);
}
_enableRowHighlight() {
this.dataTable.on("click", this.ROWS_SELECTOR, this._onRowHighlightClick);
}
_onRowHighlightClick(event) {
const el = $(event.target).closest("tr");
const currentState = el.hasClass("highlighted");
$(event.target).closest("tbody").find('tr').toggleClass('highlighted', false);
el.toggleClass("highlighted", !currentState);
}
_dataTableConfig() {
let displayStart, recordTotal;
if (this.urlPagination) {
displayStart = this._getSafeDisplayStartFromPageNumber();
recordTotal = displayStart + this.paginateLength;
}
return {
sDom: this.layout,
bDeferRender: true,
bPaginate: this.paginate,
aLengthMenu: this.paginateLengthMenu,
iDisplayLength: this.paginateLength,
iDisplayStart: displayStart,
iRecordsTotal: recordTotal,
iRecordsDisplay: recordTotal,
bInfo: true,
fnCreatedRow: this._onRowCreated,
aoColumns: this._columnManager.dataTableColumnsConfig(),
aaSorting: this._columnManager.dataTableSortingConfig(),
fnDrawCallback: this._onDraw,
oLanguage: {
sEmptyTable: this.emptyText
}
};
}
_getSafeDisplayStartFromPageNumber() {
let pageIndex = this._parsePageNumberFromQueryString() - 1;
if (pageIndex < 0) {
return 0;
} else {
return pageIndex * this.paginateLength;
}
}
_triggerChangeSelection(extraData) {
const data = _.extend(extraData || {}, { count: this.selectionManager.count() });
this.trigger("change:selected", data);
}
_setupSelect2PaginationAttributes() {
this.$('select')
.attr('data-plugin', 'select2')
.css('width', '5em');
}
// DataTables does not provide a good way to programmatically disable sorting, so we:
// 1) remove the default sorting event handler that dataTables adds
// 2) Create a div and put the header in it. We need to do this so sorting doesn't conflict with filtering
// on the click events.
// 3) insert our own event handler on the div that stops the event if we are locked
// 4) re-insert the dataTables sort event handler
_installSortInterceptors() {
const self = this;
this.dataTable.find("thead th").each(function(index) {
$(this).off("click.DT");
$(this).off("keypress.DT");
const wrapper = $("<div class='DataTables_sort_wrapper'><div class='DataTables_sort_interceptor'></div></div>");
$(this).contents().appendTo(wrapper.find(".DataTables_sort_interceptor"));
$(this).append(wrapper);
// handle clicking on div as sorting
$('.DataTables_sort_interceptor', this).on("click", event => {
if (self.lock("sort")) {
event.stopImmediatePropagation();
} else {
history.pushState({}, "pagination", self._createQueryStringWithPageNumber(1));
}
});
// default sort handler for column with index
self.dataTable.fnSortListener($('.DataTables_sort_wrapper', this), index);
});
}
// Sets up filtering for the dataTable
_setupFiltering() {
const table = this;
const cg = table.configGenerator();
// Close active filter menu if user clicks on document
$("body").on("click", e => {
$("[data-toggle='filter-popover']").each(function() {
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $(".popover").has(e.target).length === 0) {
$(this).popover("hide");
}
});
});
// We make a filter for each column header
table.dataTable.find("thead th").each(function(index) {
// here we use the CSS in the header to get the column config by attr
// there isn't a better way to do this currently
let col;
const columnClassName = extractColumnCSSClass(this.className);
if (columnClassName) {
cg.columnsConfig.forEach(currentColConfig => {
if (currentColConfig.id && toColumnCSSClass(currentColConfig.id) === columnClassName) {
col = currentColConfig;
}
});
} else {
// TODO: FAIL!!!
}
if (col) {
// We only make the filter controls if there's a filter element in the column manager
if (col.filter) {
table.child(`filter-${col.id}`, new FilterView({
column: col,
table,
head: this,
className: "dropdown DataTables_filter_wrapper"
}));
$(this).append(table.child(`filter-${col.id}`).render().$el);
}
}
});
}
// events
_onColumnReorder() {
this.trigger("reorder");
this._renderGrandTotalsRow();
}
_onDraw() {
this.trigger("draw", arguments);
this._renderGrandTotalsRow();
this._renderHeaderGroup();
}
_onColumnVisibilityChange(summary) {
this.dataTable.find(".dataTables_empty").attr("colspan", summary.visible.length);
this._renderGrandTotalsRow();
this._renderHeaderGroup();
}
_onBulkHeaderClick(event) {
const state = this.bulkCheckbox.prop("checked");
this.selectAllVisible(state);
// don't let dataTables sort this column on the click of checkbox
event.stopPropagation();
}
_onBulkRowClick(event) {
const checkbox = $(event.target);
const row = checkbox.closest("tr").data("row");
const checked = checkbox.prop("checked");
// ensure that when a single row checkbox is unchecked, we uncheck the header bulk checkbox
if (!checked) this.bulkCheckbox.prop("checked", false);
this._setRowSelectedState(row.model, row, checked);
this._triggerChangeSelection();
event.stopPropagation();
}
_onRowCreated(node, data) {
const model = this.collection.get(data);
// eslint-disable-next-line new-cap
const row = new this.rowClass({
el: node,
model,
columnsConfig: this.columnsConfig()
});
this.cache.set(model, row);
this.child(`child${row.cid}`, row).render();
// due to deferred rendering, the model associated with the row may have already been selected, but not rendered yet.
this.selectionManager.has(model) && row.bulkState(true);
}
_onAdd(model) {
if (!this.dataTable) return;
this.dataTable.fnAddData({ cid: model.cid });
this._triggerChangeSelection();
}
_onRemove(model) {
if (!this.dataTable) return;
const cache = this.cache;
const row = cache.get(model);
this.dataTable.fnDeleteRow(row.el, () => {
cache.unset(model);
row.close();
});
this.selectionManager.process(model, false);
this._triggerChangeSelection();
}
_onReset(collection) {
if (!this.dataTable) return;
this.dataTable.fnClearTable();
this.cache.each(row => {
row.close();
});
this.cache.reset();
// populate with preselected items
this.selectionManager = new SelectionManager();
_.each(this.selectedIds, function(id) {
// its possible that a selected id is provided for a model that doesn't actually exist in the table, ignore it
const selectedModel = this.collection.get(id);
selectedModel && this._setRowSelectedState(selectedModel, null, true);
}, this);
// add new data
this.dataTable.fnAddData(cidMap(collection));
this._triggerChangeSelection();
}
_onColumnFilter() {
this.trigger("filter:column");
}
}
_.extend(LocalDataTable.prototype, {
BULK_COLUMN_HEADER_CHECKBOX_SELECTOR: "th:first.bulk :checkbox",
BULK_COLUMN_CHECKBOXES_SELECTOR: "td:first-child.bulk :checkbox",
ROWS_SELECTOR: "tbody tr",
template: '<table cellpadding="0" class="table"></table>',
paginate: true,
paginateLengthMenu: [10, 25, 50, 100],
paginateLength: 10,
selectedIds: [],
filteringEnabled: false,
layout: "<'row'<'col-xs-6'l><'col-xs-6'f>r>t<'row'<'col-xs-6'i><'col-xs-6'p>>",
striped: true,
reorderableColumns: true,
resizableColumns: false,
objectName: {
singular: "row",
plural: "rows"
}
});
export default LocalDataTable;
|
var s = document.createElement('script');
s.src = chrome.extension.getURL('flourish.js');
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s); |
import PropTypes from 'prop-types';
import Element from './Element';
export default class Rect extends Element {
static displayName = 'Rect';
static propTypes = {
x: PropTypes.oneOfType([PropTypes.func, PropTypes.number]),
y: PropTypes.oneOfType([PropTypes.func, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.func, PropTypes.number]),
width: PropTypes.oneOfType([PropTypes.func, PropTypes.number]),
};
static defaultProps = {
...Element.defaultProps,
};
defaultComponent='rect'
}
|
'use strict';
// var Boom = require('boom');
var BPromise = require('bluebird');
module.exports = function (handler) {
return function (req, res) {
return new BPromise(function (resolve) {
resolve(handler(req, res));
})
.then(function (response) {
if (response === undefined) {
// [KE] assume the response is handled, eg in a res.redirect
return;
}
if (response.isBoom) {
res.error(response);
return;
}
res.json(response);
}, res.error).catch(res.error);
};
};
|
(function() {
if (typeof module === "undefined") self.queue = queue;
else module.exports = queue;
queue.version = "1.0.1";
function queue(parallelism) {
var queue = {},
active = 0, // number of in-flight deferrals
remaining = 0, // number of deferrals remaining
head, tail, // singly-linked list of deferrals
error = null,
results = [],
await = noop,
awaitAll;
if (arguments.length < 1) parallelism = Infinity;
queue.defer = function() {
if (!error) {
var node = arguments;
node.index = results.push(undefined) - 1;
if (tail) tail.next = node, tail = tail.next;
else head = tail = node;
++remaining;
pop();
}
return queue;
};
queue.await = function(f) {
await = f;
awaitAll = false;
if (!remaining) notify();
return queue;
};
queue.awaitAll = function(f) {
await = f;
awaitAll = true;
if (!remaining) notify();
return queue;
};
function pop() {
if (head && active < parallelism) {
var node = head,
f = node[0],
a = Array.prototype.slice.call(node, 1),
i = node.index;
if (head === tail) head = tail = null;
else head = head.next;
++active;
a.push(function(e, r) {
--active;
if (error != null) return;
if (e != null) {
// clearing remaining cancels subsequent callbacks
// clearing head stops queued tasks from being executed
// setting error ignores subsequent calls to defer
error = e;
remaining = results = head = tail = null;
notify();
} else {
results[i] = r;
if (--remaining) pop();
else notify();
}
});
f.apply(null, a);
}
}
function notify() {
if (error != null) await(error);
else if (awaitAll) await(null, results);
else await.apply(null, [null].concat(results));
}
return queue;
}
function noop() {}
})(); |
/*globals define, WebGMEGlobal, requirejs*/
/*jshint browser: true*/
/**
* @author rkereskenyi / https://github.com/rkereskenyi
* @author lattmann / https://github.com/lattmann
* @author pmeijer / https://github.com/pmeijer
*/
define([
'common/core/coreQ',
'plugin/PluginManagerBase',
'plugin/PluginResult',
'plugin/PluginMessage',
'blob/BlobClient',
'js/Dialogs/PluginConfig/PluginConfigDialog',
'js/logger'
], function (Core, PluginManagerBase, PluginResult, PluginMessage, BlobClient, PluginConfigDialog, Logger) {
'use strict';
var InterpreterManager = function (client, gmeConfig) {
this._client = client;
//this._manager = new PluginManagerBase();
this.gmeConfig = gmeConfig;
this._savedConfigs = {};
this.logger = Logger.create('gme:InterpreterManager', gmeConfig.client.log);
this.logger.debug('InterpreterManager ctor');
};
var getPlugin = function (name, callback) {
if (WebGMEGlobal && WebGMEGlobal.plugins && WebGMEGlobal.plugins.hasOwnProperty(name)) {
callback(null, WebGMEGlobal.plugins[name]);
} else {
requirejs(['/plugin/' + name + '/' + name + '/' + name],
function (InterpreterClass) {
callback(null, InterpreterClass);
},
function (err) {
callback(err, null);
}
);
}
};
function getPluginErrorResult(pluginName, message, startTime, projectId) {
var pluginResult = new PluginResult(),
pluginMessage = new PluginMessage();
pluginMessage.severity = 'error';
pluginMessage.message = message;
pluginResult.setSuccess(false);
pluginResult.setPluginName(pluginName);
pluginResult.setProjectId(projectId || 'N/A');
pluginResult.addMessage(pluginMessage);
pluginResult.setStartTime(startTime);
pluginResult.setFinishTime((new Date()).toISOString());
pluginResult.setError(pluginMessage.message);
return pluginResult;
}
/**
*
* @param {string} name - name of plugin to be executed.
* @param {object} silentPluginCfg - if falsy dialog window will be shown.
* @param {object.string} silentPluginCfg.activeNode - Path to activeNode.
* @param {object.Array.<string>} silentPluginCfg.activeSelection - Paths to nodes in activeSelection.
* @param {object.boolean} silentPluginCfg.runOnServer - Whether to run the plugin on the server or not.
* @param {object.object} silentPluginCfg.pluginConfig - Plugin specific options.
* @param callback
*/
InterpreterManager.prototype.run = function (name, silentPluginCfg, callback) {
var self = this,
projectId = self._client.getProjectObject().projectId,
startTime = (new Date()).toISOString();
getPlugin(name, function (err, plugin) {
self.logger.debug('Getting getPlugin in run.');
if (!err && plugin) {
var plugins = {},
runWithConfiguration;
plugins[name] = plugin;
var pluginManager = new PluginManagerBase(self._client.getProjectObject(), Core, self.logger, plugins,
self.gmeConfig);
pluginManager.notificationHandlers = [function (data, callback) {
self._client.dispatchPluginNotification(data);
callback(null);
}];
pluginManager.initialize(null, function (pluginConfigs, configSaveCallback) {
//#1: display config to user
var serverAllowedGlobal = self.gmeConfig.plugin.allowServerExecution === true,
serverAllowedPlugin = !plugin.disableServerExecution,
browserAllowedGlobal = self.gmeConfig.plugin.allowBrowserExecution === true,
browserAllowedPlugin = !plugin.disableBrowserExecution,
runOptions = {
name: 'runOnServer',
displayName: 'Execute on Server',
description: '',
value: false,
valueType: 'boolean',
readOnly: false
},
hackedConfig = {
'Global Options': [runOptions]
},
i, j, d, len;
if (serverAllowedGlobal === false && browserAllowedGlobal === false) {
callback(getPluginErrorResult(name, 'Plugin execution is disabled!', startTime, projectId));
return;
}
if (serverAllowedPlugin === false && browserAllowedPlugin === false) {
callback(getPluginErrorResult(name, 'This plugin cannot run on the server nor in the browser!?',
startTime, projectId));
return;
}
if (browserAllowedGlobal) {
if (serverAllowedGlobal) {
if (browserAllowedPlugin) {
if (serverAllowedPlugin) {
// This is the default
} else {
runOptions.readOnly = true;
runOptions.description = 'This plugin can not run on the server.';
}
} else {
runOptions.readOnly = true;
runOptions.value = true;
runOptions.description = 'This plugin can not run in the browser.';
}
} else {
if (browserAllowedPlugin) {
runOptions.readOnly = true;
runOptions.description = 'Server execution is disabled.';
} else {
callback(getPluginErrorResult(name,
'This plugin can only run on the server which is disabled!', startTime, projectId));
return;
}
}
} else {
if (browserAllowedPlugin) {
runOptions.readOnly = true;
runOptions.value = true;
runOptions.description = 'Browser execution is disabled.';
} else {
callback(getPluginErrorResult(name,
'This plugin can only run on the server which is disabled!', startTime, projectId));
return;
}
}
for (i in pluginConfigs) {
if (pluginConfigs.hasOwnProperty(i)) {
hackedConfig[i] = pluginConfigs[i];
// retrieve user settings from previous run
if (self._savedConfigs.hasOwnProperty(i)) {
var iConfig = self._savedConfigs[i];
len = hackedConfig[i].length;
while (len--) {
if (iConfig.hasOwnProperty(hackedConfig[i][len].name)) {
hackedConfig[i][len].value = iConfig[hackedConfig[i][len].name];
}
}
}
}
}
runWithConfiguration = function (updatedConfig) {
//when Save&Run is clicked in the dialog (or silentPluginCfg was passed)
var globalconfig = updatedConfig['Global Options'],
activeNode,
errMessage,
activeSelection;
delete updatedConfig['Global Options'];
activeNode = silentPluginCfg.activeNode;
if (!activeNode && WebGMEGlobal && WebGMEGlobal.State) {
activeNode = WebGMEGlobal.State.getActiveObject();
}
activeSelection = silentPluginCfg.activeSelection;
if (!activeSelection && WebGMEGlobal && WebGMEGlobal.State) {
activeSelection = WebGMEGlobal.State.getActiveSelection();
}
// save config from user
for (i in updatedConfig) {
self._savedConfigs[i] = updatedConfig[i];
}
//#2: save it back and run the plugin
if (configSaveCallback) {
configSaveCallback(updatedConfig);
if (self._client.getBranchStatus() &&
self._client.getBranchStatus() !== self._client.CONSTANTS.BRANCH_STATUS.SYNC) {
errMessage = 'Not allowed to invoke plugin while local branch is AHEAD or ' +
'PULLING changes from server.';
self.logger.error(errMessage);
callback(getPluginErrorResult(name, errMessage, startTime, projectId));
return;
}
// TODO: If global config says try to merge branch then we
// TODO: should pass the name of the branch.
var config = {
project: self._client.getActiveProjectId(),
token: '',
activeNode: activeNode, // active object in the editor
activeSelection: activeSelection || [],
commit: self._client.getActiveCommitHash(), //#668b3babcdf2ddcd7ba38b51acb62d63da859d90,
// This will get loaded too which will provide a sanity check on the client state.
rootHash: self._client.getActiveRootHash(),
branchName: self._client.getActiveBranchName()
};
if (globalconfig.runOnServer === true || silentPluginCfg.runOnServer === true) {
var context = {
managerConfig: config,
pluginConfig: updatedConfig[name]
};
self._client.runServerPlugin(name, context, function (err, result) {
if (err) {
self.logger.error(err);
if (result) {
callback(new PluginResult(result));
} else {
errMessage = 'Plugin execution resulted in error, err: ' + err;
callback(getPluginErrorResult(name, errMessage, startTime, projectId));
}
} else {
var resultObject = new PluginResult(result);
callback(resultObject);
}
});
} else {
config.blobClient = new BlobClient({logger: self.logger.fork('BlobClient')});
pluginManager.executePlugin(name, config, function (err, result) {
if (err) {
self.logger.error(err);
}
callback(result);
});
}
}
};
if (silentPluginCfg) {
var updatedConfig = {};
for (i in hackedConfig) {
updatedConfig[i] = {};
len = hackedConfig[i].length;
while (len--) {
updatedConfig[i][hackedConfig[i][len].name] = hackedConfig[i][len].value;
}
if (silentPluginCfg && silentPluginCfg.pluginConfig) {
for (j in silentPluginCfg.pluginConfig) {
updatedConfig[i][j] = silentPluginCfg.pluginConfig[j];
}
}
}
runWithConfiguration(updatedConfig);
} else {
d = new PluginConfigDialog();
silentPluginCfg = {};
d.show(hackedConfig, plugin, runWithConfiguration);
}
});
} else {
self.logger.error(err);
self.logger.error('Unable to load plugin');
callback(getPluginErrorResult(name, 'Unable to load plugin, err:' + err, startTime, projectId));
}
});
};
//TODO: Somehow it would feel more right if we do run in async mode, but if not then we should provide getState and
//TODO: getResult synchronous functions as well.
return InterpreterManager;
});
|
module.exports = function (grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
jshint: {
options: {
"expr": true,
"laxcomma": true,
"smarttabs": true,
"curly": true,
"eqeqeq": false,
"immed": true,
"latedef": true,
"newcap": true,
"noarg": true,
"sub": true,
"es5": true,
"undef": true,
"eqnull": true,
"browser": true,
"regexdash": true,
"loopfunc": true,
"mootools": true,
"node": true,
globals: {
"Mousetrap": true,
"Modernizr": true,
"mootools": true,
"nsUtil": true,
"resource": true,
"define": true,
"debugMode": true,
"rendererModel": true,
"viewMode": true,
"WixGoogleAnalytics": true,
"siteHeader": true,
"editorModel": true,
"siteId": true,
"LOG": true,
"PHASES": true,
"wixLogLegend": true,
"wixEvents": true,
"WixLogger": true,
"wixErrors": true,
"WixBILogger": true,
"managers": true,
"classDefinition": true,
"Utils": true,
"UtilsClass": true,
"WClass": true,
"W": true,
"e": true,
"l": true,
"s": true,
"m": true,
"g": true,
"d": true,
"f": true,
"t": true,
"after": true,
"unescape": true,
"alert": true,
"missingItems": true,
"hex_sha256": true,
"XDomainRequest": true,
"_userAnalyticsAccount": true,
"getCookieInfo": true,
"creationSource": true,
"ActiveXObject": true,
"Test": true,
"main": true,
"Async": true,
"console": true,
"Request": true,
"getAsyncExpects": true,
"fail": true,
"pageTracker": true,
"_gat": true,
"Constants": true,
"expect": true,
"describe": true,
"beforeEach": true,
"it": true,
"waits": true,
"runs": true,
"waitsFor": true,
"afterEach": true,
"spyOn": true,
"sleep": true,
"jasmine": true,
"getPlayGround": true,
"Element": true,
"typeOf": true,
"getSpy": true,
"MockBuilder": true,
"Define": true,
"instanceOf": true,
"xdescribe": true,
"merge": true,
"clone": true
}
},
all: [
'Gruntfile.js',
'tasks/**/*.js',
'test/javascript/**/*.js'
]
},
jasmine_node: {
specNameMatcher: "spec",
projectRoot: ".",
requirejs: false,
forceExit: true,
jUnit: {
report: false,
savePath: "./build/reports/jasmine/",
useDotNotation: true,
consolidate: true
}
},
aggregate: {
"ordered-list": {
src: "test/resources/ordered-list.json",
manifest: "target/ordered-list.json"
},
main: {
src: "test/resources/aggregations.json",
manifest: "target/manifest.json"
},
'no-min': {
src: "test/resources/no-min.json",
manifest: 'target/no-min.json',
min: false
},
'no-copy': {
src: "test/resources/no-copy.json",
manifest: 'target/no-copy.json',
copy: false
},
list: {
src: "test/resources/list.json",
manifest: 'target/list.json',
manifestCopy: 'target/list.copy.json',
min: false,
copy: false
},
exclude: {
src: "test/resources/exclude.json",
manifest: 'target/exclude.json',
manifestCopy: 'target/exclude.copy.json'
},
css: {
src: "test/resources/css.json",
manifest: 'target/css.json'
},
manymin: {
src: "test/resources/manymin.json",
manifest: "target/manymin.json",
min: false,
manymin: true,
copy: false
}
},
modify: {
json: {
base: 'test/resources',
src: ['dir*/**/*.json'],
dest: 'target/mod',
modifier: function (name, content) {
return {
name: name.search('subdir1_2') !== -1 ? 'genereated.name.json' : name,
content: '[' + content + ']'
};
}
}
},
clean: {
test: "target"
},
copy: {
target: {
files: {
'target/aggregations/greatescape/escaped.js': ['test/greatescape/original.js']
}
}
},
greatescape: {
all: 'target/aggregations/greatescape/escaped.js'
}
});
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-jshint');
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// By default, lint and run all tests.
grunt.registerTask('default', ['clean', 'jshint', 'modify', 'aggregate']);
};
|
/*!
CSSLint
Copyright (c) 2011 Nicole Sullivan and Nicholas C. Zakas. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* Build time: 20-August-2012 10:49:54 */
var CSSLint = (function(){
/*!
Parser-Lib
Copyright (c) 2009-2011 Nicholas C. Zakas. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* Version v0.1.9, Build time: 23-July-2012 10:52:31 */
var parserlib = {};
(function(){
/**
* A generic base to inherit from for any object
* that needs event handling.
* @class EventTarget
* @constructor
*/
function EventTarget(){
/**
* The array of listeners for various events.
* @type Object
* @property _listeners
* @private
*/
this._listeners = {};
}
EventTarget.prototype = {
//restore constructor
constructor: EventTarget,
/**
* Adds a listener for a given event type.
* @param {String} type The type of event to add a listener for.
* @param {Function} listener The function to call when the event occurs.
* @return {void}
* @method addListener
*/
addListener: function(type, listener){
if (!this._listeners[type]){
this._listeners[type] = [];
}
this._listeners[type].push(listener);
},
/**
* Fires an event based on the passed-in object.
* @param {Object|String} event An object with at least a 'type' attribute
* or a string indicating the event name.
* @return {void}
* @method fire
*/
fire: function(event){
if (typeof event == "string"){
event = { type: event };
}
if (typeof event.target != "undefined"){
event.target = this;
}
if (typeof event.type == "undefined"){
throw new Error("Event object missing 'type' property.");
}
if (this._listeners[event.type]){
//create a copy of the array and use that so listeners can't chane
var listeners = this._listeners[event.type].concat();
for (var i=0, len=listeners.length; i < len; i++){
listeners[i].call(this, event);
}
}
},
/**
* Removes a listener for a given event type.
* @param {String} type The type of event to remove a listener from.
* @param {Function} listener The function to remove from the event.
* @return {void}
* @method removeListener
*/
removeListener: function(type, listener){
if (this._listeners[type]){
var listeners = this._listeners[type];
for (var i=0, len=listeners.length; i < len; i++){
if (listeners[i] === listener){
listeners.splice(i, 1);
break;
}
}
}
}
};
/**
* Convenient way to read through strings.
* @namespace parserlib.util
* @class StringReader
* @constructor
* @param {String} text The text to read.
*/
function StringReader(text){
/**
* The input text with line endings normalized.
* @property _input
* @type String
* @private
*/
this._input = text.replace(/\n\r?/g, "\n");
/**
* The row for the character to be read next.
* @property _line
* @type int
* @private
*/
this._line = 1;
/**
* The column for the character to be read next.
* @property _col
* @type int
* @private
*/
this._col = 1;
/**
* The index of the character in the input to be read next.
* @property _cursor
* @type int
* @private
*/
this._cursor = 0;
}
StringReader.prototype = {
//restore constructor
constructor: StringReader,
//-------------------------------------------------------------------------
// Position info
//-------------------------------------------------------------------------
/**
* Returns the column of the character to be read next.
* @return {int} The column of the character to be read next.
* @method getCol
*/
getCol: function(){
return this._col;
},
/**
* Returns the row of the character to be read next.
* @return {int} The row of the character to be read next.
* @method getLine
*/
getLine: function(){
return this._line ;
},
/**
* Determines if you're at the end of the input.
* @return {Boolean} True if there's no more input, false otherwise.
* @method eof
*/
eof: function(){
return (this._cursor == this._input.length);
},
//-------------------------------------------------------------------------
// Basic reading
//-------------------------------------------------------------------------
/**
* Reads the next character without advancing the cursor.
* @param {int} count How many characters to look ahead (default is 1).
* @return {String} The next character or null if there is no next character.
* @method peek
*/
peek: function(count){
var c = null;
count = (typeof count == "undefined" ? 1 : count);
//if we're not at the end of the input...
if (this._cursor < this._input.length){
//get character and increment cursor and column
c = this._input.charAt(this._cursor + count - 1);
}
return c;
},
/**
* Reads the next character from the input and adjusts the row and column
* accordingly.
* @return {String} The next character or null if there is no next character.
* @method read
*/
read: function(){
var c = null;
//if we're not at the end of the input...
if (this._cursor < this._input.length){
//if the last character was a newline, increment row count
//and reset column count
if (this._input.charAt(this._cursor) == "\n"){
this._line++;
this._col=1;
} else {
this._col++;
}
//get character and increment cursor and column
c = this._input.charAt(this._cursor++);
}
return c;
},
//-------------------------------------------------------------------------
// Misc
//-------------------------------------------------------------------------
/**
* Saves the current location so it can be returned to later.
* @method mark
* @return {void}
*/
mark: function(){
this._bookmark = {
cursor: this._cursor,
line: this._line,
col: this._col
};
},
reset: function(){
if (this._bookmark){
this._cursor = this._bookmark.cursor;
this._line = this._bookmark.line;
this._col = this._bookmark.col;
delete this._bookmark;
}
},
//-------------------------------------------------------------------------
// Advanced reading
//-------------------------------------------------------------------------
/**
* Reads up to and including the given string. Throws an error if that
* string is not found.
* @param {String} pattern The string to read.
* @return {String} The string when it is found.
* @throws Error when the string pattern is not found.
* @method readTo
*/
readTo: function(pattern){
var buffer = "",
c;
/*
* First, buffer must be the same length as the pattern.
* Then, buffer must end with the pattern or else reach the
* end of the input.
*/
while (buffer.length < pattern.length || buffer.lastIndexOf(pattern) != buffer.length - pattern.length){
c = this.read();
if (c){
buffer += c;
} else {
throw new Error("Expected \"" + pattern + "\" at line " + this._line + ", col " + this._col + ".");
}
}
return buffer;
},
/**
* Reads characters while each character causes the given
* filter function to return true. The function is passed
* in each character and either returns true to continue
* reading or false to stop.
* @param {Function} filter The function to read on each character.
* @return {String} The string made up of all characters that passed the
* filter check.
* @method readWhile
*/
readWhile: function(filter){
var buffer = "",
c = this.read();
while(c !== null && filter(c)){
buffer += c;
c = this.read();
}
return buffer;
},
/**
* Reads characters that match either text or a regular expression and
* returns those characters. If a match is found, the row and column
* are adjusted; if no match is found, the reader's state is unchanged.
* reading or false to stop.
* @param {String|RegExp} matchter If a string, then the literal string
* value is searched for. If a regular expression, then any string
* matching the pattern is search for.
* @return {String} The string made up of all characters that matched or
* null if there was no match.
* @method readMatch
*/
readMatch: function(matcher){
var source = this._input.substring(this._cursor),
value = null;
//if it's a string, just do a straight match
if (typeof matcher == "string"){
if (source.indexOf(matcher) === 0){
value = this.readCount(matcher.length);
}
} else if (matcher instanceof RegExp){
if (matcher.test(source)){
value = this.readCount(RegExp.lastMatch.length);
}
}
return value;
},
/**
* Reads a given number of characters. If the end of the input is reached,
* it reads only the remaining characters and does not throw an error.
* @param {int} count The number of characters to read.
* @return {String} The string made up the read characters.
* @method readCount
*/
readCount: function(count){
var buffer = "";
while(count--){
buffer += this.read();
}
return buffer;
}
};
/**
* Type to use when a syntax error occurs.
* @class SyntaxError
* @namespace parserlib.util
* @constructor
* @param {String} message The error message.
* @param {int} line The line at which the error occurred.
* @param {int} col The column at which the error occurred.
*/
function SyntaxError(message, line, col){
/**
* The column at which the error occurred.
* @type int
* @property col
*/
this.col = col;
/**
* The line at which the error occurred.
* @type int
* @property line
*/
this.line = line;
/**
* The text representation of the unit.
* @type String
* @property text
*/
this.message = message;
}
//inherit from Error
SyntaxError.prototype = new Error();
/**
* Base type to represent a single syntactic unit.
* @class SyntaxUnit
* @namespace parserlib.util
* @constructor
* @param {String} text The text of the unit.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function SyntaxUnit(text, line, col, type){
/**
* The column of text on which the unit resides.
* @type int
* @property col
*/
this.col = col;
/**
* The line of text on which the unit resides.
* @type int
* @property line
*/
this.line = line;
/**
* The text representation of the unit.
* @type String
* @property text
*/
this.text = text;
/**
* The type of syntax unit.
* @type int
* @property type
*/
this.type = type;
}
/**
* Create a new syntax unit based solely on the given token.
* Convenience method for creating a new syntax unit when
* it represents a single token instead of multiple.
* @param {Object} token The token object to represent.
* @return {parserlib.util.SyntaxUnit} The object representing the token.
* @static
* @method fromToken
*/
SyntaxUnit.fromToken = function(token){
return new SyntaxUnit(token.value, token.startLine, token.startCol);
};
SyntaxUnit.prototype = {
//restore constructor
constructor: SyntaxUnit,
/**
* Returns the text representation of the unit.
* @return {String} The text representation of the unit.
* @method valueOf
*/
valueOf: function(){
return this.toString();
},
/**
* Returns the text representation of the unit.
* @return {String} The text representation of the unit.
* @method toString
*/
toString: function(){
return this.text;
}
};
/*global StringReader, SyntaxError*/
/**
* Generic TokenStream providing base functionality.
* @class TokenStreamBase
* @namespace parserlib.util
* @constructor
* @param {String|StringReader} input The text to tokenize or a reader from
* which to read the input.
*/
function TokenStreamBase(input, tokenData){
/**
* The string reader for easy access to the text.
* @type StringReader
* @property _reader
* @private
*/
this._reader = input ? new StringReader(input.toString()) : null;
/**
* Token object for the last consumed token.
* @type Token
* @property _token
* @private
*/
this._token = null;
/**
* The array of token information.
* @type Array
* @property _tokenData
* @private
*/
this._tokenData = tokenData;
/**
* Lookahead token buffer.
* @type Array
* @property _lt
* @private
*/
this._lt = [];
/**
* Lookahead token buffer index.
* @type int
* @property _ltIndex
* @private
*/
this._ltIndex = 0;
this._ltIndexCache = [];
}
/**
* Accepts an array of token information and outputs
* an array of token data containing key-value mappings
* and matching functions that the TokenStream needs.
* @param {Array} tokens An array of token descriptors.
* @return {Array} An array of processed token data.
* @method createTokenData
* @static
*/
TokenStreamBase.createTokenData = function(tokens){
var nameMap = [],
typeMap = {},
tokenData = tokens.concat([]),
i = 0,
len = tokenData.length+1;
tokenData.UNKNOWN = -1;
tokenData.unshift({name:"EOF"});
for (; i < len; i++){
nameMap.push(tokenData[i].name);
tokenData[tokenData[i].name] = i;
if (tokenData[i].text){
typeMap[tokenData[i].text] = i;
}
}
tokenData.name = function(tt){
return nameMap[tt];
};
tokenData.type = function(c){
return typeMap[c];
};
return tokenData;
};
TokenStreamBase.prototype = {
//restore constructor
constructor: TokenStreamBase,
//-------------------------------------------------------------------------
// Matching methods
//-------------------------------------------------------------------------
/**
* Determines if the next token matches the given token type.
* If so, that token is consumed; if not, the token is placed
* back onto the token stream. You can pass in any number of
* token types and this will return true if any of the token
* types is found.
* @param {int|int[]} tokenTypes Either a single token type or an array of
* token types that the next token might be. If an array is passed,
* it's assumed that the token can be any of these.
* @param {variant} channel (Optional) The channel to read from. If not
* provided, reads from the default (unnamed) channel.
* @return {Boolean} True if the token type matches, false if not.
* @method match
*/
match: function(tokenTypes, channel){
//always convert to an array, makes things easier
if (!(tokenTypes instanceof Array)){
tokenTypes = [tokenTypes];
}
var tt = this.get(channel),
i = 0,
len = tokenTypes.length;
while(i < len){
if (tt == tokenTypes[i++]){
return true;
}
}
//no match found, put the token back
this.unget();
return false;
},
/**
* Determines if the next token matches the given token type.
* If so, that token is consumed; if not, an error is thrown.
* @param {int|int[]} tokenTypes Either a single token type or an array of
* token types that the next token should be. If an array is passed,
* it's assumed that the token must be one of these.
* @param {variant} channel (Optional) The channel to read from. If not
* provided, reads from the default (unnamed) channel.
* @return {void}
* @method mustMatch
*/
mustMatch: function(tokenTypes, channel){
var token;
//always convert to an array, makes things easier
if (!(tokenTypes instanceof Array)){
tokenTypes = [tokenTypes];
}
if (!this.match.apply(this, arguments)){
token = this.LT(1);
throw new SyntaxError("Expected " + this._tokenData[tokenTypes[0]].name +
" at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
}
},
//-------------------------------------------------------------------------
// Consuming methods
//-------------------------------------------------------------------------
/**
* Keeps reading from the token stream until either one of the specified
* token types is found or until the end of the input is reached.
* @param {int|int[]} tokenTypes Either a single token type or an array of
* token types that the next token should be. If an array is passed,
* it's assumed that the token must be one of these.
* @param {variant} channel (Optional) The channel to read from. If not
* provided, reads from the default (unnamed) channel.
* @return {void}
* @method advance
*/
advance: function(tokenTypes, channel){
while(this.LA(0) !== 0 && !this.match(tokenTypes, channel)){
this.get();
}
return this.LA(0);
},
/**
* Consumes the next token from the token stream.
* @return {int} The token type of the token that was just consumed.
* @method get
*/
get: function(channel){
var tokenInfo = this._tokenData,
reader = this._reader,
value,
i =0,
len = tokenInfo.length,
found = false,
token,
info;
//check the lookahead buffer first
if (this._lt.length && this._ltIndex >= 0 && this._ltIndex < this._lt.length){
i++;
this._token = this._lt[this._ltIndex++];
info = tokenInfo[this._token.type];
//obey channels logic
while((info.channel !== undefined && channel !== info.channel) &&
this._ltIndex < this._lt.length){
this._token = this._lt[this._ltIndex++];
info = tokenInfo[this._token.type];
i++;
}
//here be dragons
if ((info.channel === undefined || channel === info.channel) &&
this._ltIndex <= this._lt.length){
this._ltIndexCache.push(i);
return this._token.type;
}
}
//call token retriever method
token = this._getToken();
//if it should be hidden, don't save a token
if (token.type > -1 && !tokenInfo[token.type].hide){
//apply token channel
token.channel = tokenInfo[token.type].channel;
//save for later
this._token = token;
this._lt.push(token);
//save space that will be moved (must be done before array is truncated)
this._ltIndexCache.push(this._lt.length - this._ltIndex + i);
//keep the buffer under 5 items
if (this._lt.length > 5){
this._lt.shift();
}
//also keep the shift buffer under 5 items
if (this._ltIndexCache.length > 5){
this._ltIndexCache.shift();
}
//update lookahead index
this._ltIndex = this._lt.length;
}
/*
* Skip to the next token if:
* 1. The token type is marked as hidden.
* 2. The token type has a channel specified and it isn't the current channel.
*/
info = tokenInfo[token.type];
if (info &&
(info.hide ||
(info.channel !== undefined && channel !== info.channel))){
return this.get(channel);
} else {
//return just the type
return token.type;
}
},
/**
* Looks ahead a certain number of tokens and returns the token type at
* that position. This will throw an error if you lookahead past the
* end of input, past the size of the lookahead buffer, or back past
* the first token in the lookahead buffer.
* @param {int} The index of the token type to retrieve. 0 for the
* current token, 1 for the next, -1 for the previous, etc.
* @return {int} The token type of the token in the given position.
* @method LA
*/
LA: function(index){
var total = index,
tt;
if (index > 0){
//TODO: Store 5 somewhere
if (index > 5){
throw new Error("Too much lookahead.");
}
//get all those tokens
while(total){
tt = this.get();
total--;
}
//unget all those tokens
while(total < index){
this.unget();
total++;
}
} else if (index < 0){
if(this._lt[this._ltIndex+index]){
tt = this._lt[this._ltIndex+index].type;
} else {
throw new Error("Too much lookbehind.");
}
} else {
tt = this._token.type;
}
return tt;
},
/**
* Looks ahead a certain number of tokens and returns the token at
* that position. This will throw an error if you lookahead past the
* end of input, past the size of the lookahead buffer, or back past
* the first token in the lookahead buffer.
* @param {int} The index of the token type to retrieve. 0 for the
* current token, 1 for the next, -1 for the previous, etc.
* @return {Object} The token of the token in the given position.
* @method LA
*/
LT: function(index){
//lookahead first to prime the token buffer
this.LA(index);
//now find the token, subtract one because _ltIndex is already at the next index
return this._lt[this._ltIndex+index-1];
},
/**
* Returns the token type for the next token in the stream without
* consuming it.
* @return {int} The token type of the next token in the stream.
* @method peek
*/
peek: function(){
return this.LA(1);
},
/**
* Returns the actual token object for the last consumed token.
* @return {Token} The token object for the last consumed token.
* @method token
*/
token: function(){
return this._token;
},
/**
* Returns the name of the token for the given token type.
* @param {int} tokenType The type of token to get the name of.
* @return {String} The name of the token or "UNKNOWN_TOKEN" for any
* invalid token type.
* @method tokenName
*/
tokenName: function(tokenType){
if (tokenType < 0 || tokenType > this._tokenData.length){
return "UNKNOWN_TOKEN";
} else {
return this._tokenData[tokenType].name;
}
},
/**
* Returns the token type value for the given token name.
* @param {String} tokenName The name of the token whose value should be returned.
* @return {int} The token type value for the given token name or -1
* for an unknown token.
* @method tokenName
*/
tokenType: function(tokenName){
return this._tokenData[tokenName] || -1;
},
/**
* Returns the last consumed token to the token stream.
* @method unget
*/
unget: function(){
//if (this._ltIndex > -1){
if (this._ltIndexCache.length){
this._ltIndex -= this._ltIndexCache.pop();//--;
this._token = this._lt[this._ltIndex - 1];
} else {
throw new Error("Too much lookahead.");
}
}
};
parserlib.util = {
StringReader: StringReader,
SyntaxError : SyntaxError,
SyntaxUnit : SyntaxUnit,
EventTarget : EventTarget,
TokenStreamBase : TokenStreamBase
};
})();
/*
Parser-Lib
Copyright (c) 2009-2011 Nicholas C. Zakas. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* Version v0.1.9, Build time: 23-July-2012 10:52:31 */
(function(){
var EventTarget = parserlib.util.EventTarget,
TokenStreamBase = parserlib.util.TokenStreamBase,
StringReader = parserlib.util.StringReader,
SyntaxError = parserlib.util.SyntaxError,
SyntaxUnit = parserlib.util.SyntaxUnit;
var Colors = {
aliceblue :"#f0f8ff",
antiquewhite :"#faebd7",
aqua :"#00ffff",
aquamarine :"#7fffd4",
azure :"#f0ffff",
beige :"#f5f5dc",
bisque :"#ffe4c4",
black :"#000000",
blanchedalmond :"#ffebcd",
blue :"#0000ff",
blueviolet :"#8a2be2",
brown :"#a52a2a",
burlywood :"#deb887",
cadetblue :"#5f9ea0",
chartreuse :"#7fff00",
chocolate :"#d2691e",
coral :"#ff7f50",
cornflowerblue :"#6495ed",
cornsilk :"#fff8dc",
crimson :"#dc143c",
cyan :"#00ffff",
darkblue :"#00008b",
darkcyan :"#008b8b",
darkgoldenrod :"#b8860b",
darkgray :"#a9a9a9",
darkgreen :"#006400",
darkkhaki :"#bdb76b",
darkmagenta :"#8b008b",
darkolivegreen :"#556b2f",
darkorange :"#ff8c00",
darkorchid :"#9932cc",
darkred :"#8b0000",
darksalmon :"#e9967a",
darkseagreen :"#8fbc8f",
darkslateblue :"#483d8b",
darkslategray :"#2f4f4f",
darkturquoise :"#00ced1",
darkviolet :"#9400d3",
deeppink :"#ff1493",
deepskyblue :"#00bfff",
dimgray :"#696969",
dodgerblue :"#1e90ff",
firebrick :"#b22222",
floralwhite :"#fffaf0",
forestgreen :"#228b22",
fuchsia :"#ff00ff",
gainsboro :"#dcdcdc",
ghostwhite :"#f8f8ff",
gold :"#ffd700",
goldenrod :"#daa520",
gray :"#808080",
green :"#008000",
greenyellow :"#adff2f",
honeydew :"#f0fff0",
hotpink :"#ff69b4",
indianred :"#cd5c5c",
indigo :"#4b0082",
ivory :"#fffff0",
khaki :"#f0e68c",
lavender :"#e6e6fa",
lavenderblush :"#fff0f5",
lawngreen :"#7cfc00",
lemonchiffon :"#fffacd",
lightblue :"#add8e6",
lightcoral :"#f08080",
lightcyan :"#e0ffff",
lightgoldenrodyellow :"#fafad2",
lightgray :"#d3d3d3",
lightgreen :"#90ee90",
lightpink :"#ffb6c1",
lightsalmon :"#ffa07a",
lightseagreen :"#20b2aa",
lightskyblue :"#87cefa",
lightslategray :"#778899",
lightsteelblue :"#b0c4de",
lightyellow :"#ffffe0",
lime :"#00ff00",
limegreen :"#32cd32",
linen :"#faf0e6",
magenta :"#ff00ff",
maroon :"#800000",
mediumaquamarine:"#66cdaa",
mediumblue :"#0000cd",
mediumorchid :"#ba55d3",
mediumpurple :"#9370d8",
mediumseagreen :"#3cb371",
mediumslateblue :"#7b68ee",
mediumspringgreen :"#00fa9a",
mediumturquoise :"#48d1cc",
mediumvioletred :"#c71585",
midnightblue :"#191970",
mintcream :"#f5fffa",
mistyrose :"#ffe4e1",
moccasin :"#ffe4b5",
navajowhite :"#ffdead",
navy :"#000080",
oldlace :"#fdf5e6",
olive :"#808000",
olivedrab :"#6b8e23",
orange :"#ffa500",
orangered :"#ff4500",
orchid :"#da70d6",
palegoldenrod :"#eee8aa",
palegreen :"#98fb98",
paleturquoise :"#afeeee",
palevioletred :"#d87093",
papayawhip :"#ffefd5",
peachpuff :"#ffdab9",
peru :"#cd853f",
pink :"#ffc0cb",
plum :"#dda0dd",
powderblue :"#b0e0e6",
purple :"#800080",
red :"#ff0000",
rosybrown :"#bc8f8f",
royalblue :"#4169e1",
saddlebrown :"#8b4513",
salmon :"#fa8072",
sandybrown :"#f4a460",
seagreen :"#2e8b57",
seashell :"#fff5ee",
sienna :"#a0522d",
silver :"#c0c0c0",
skyblue :"#87ceeb",
slateblue :"#6a5acd",
slategray :"#708090",
snow :"#fffafa",
springgreen :"#00ff7f",
steelblue :"#4682b4",
tan :"#d2b48c",
teal :"#008080",
thistle :"#d8bfd8",
tomato :"#ff6347",
turquoise :"#40e0d0",
violet :"#ee82ee",
wheat :"#f5deb3",
white :"#ffffff",
whitesmoke :"#f5f5f5",
yellow :"#ffff00",
yellowgreen :"#9acd32"
};
/*global SyntaxUnit, Parser*/
/**
* Represents a selector combinator (whitespace, +, >).
* @namespace parserlib.css
* @class Combinator
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {String} text The text representation of the unit.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function Combinator(text, line, col){
SyntaxUnit.call(this, text, line, col, Parser.COMBINATOR_TYPE);
/**
* The type of modifier.
* @type String
* @property type
*/
this.type = "unknown";
//pretty simple
if (/^\s+$/.test(text)){
this.type = "descendant";
} else if (text == ">"){
this.type = "child";
} else if (text == "+"){
this.type = "adjacent-sibling";
} else if (text == "~"){
this.type = "sibling";
}
}
Combinator.prototype = new SyntaxUnit();
Combinator.prototype.constructor = Combinator;
/*global SyntaxUnit, Parser*/
/**
* Represents a media feature, such as max-width:500.
* @namespace parserlib.css
* @class MediaFeature
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {SyntaxUnit} name The name of the feature.
* @param {SyntaxUnit} value The value of the feature or null if none.
*/
function MediaFeature(name, value){
SyntaxUnit.call(this, "(" + name + (value !== null ? ":" + value : "") + ")", name.startLine, name.startCol, Parser.MEDIA_FEATURE_TYPE);
/**
* The name of the media feature
* @type String
* @property name
*/
this.name = name;
/**
* The value for the feature or null if there is none.
* @type SyntaxUnit
* @property value
*/
this.value = value;
}
MediaFeature.prototype = new SyntaxUnit();
MediaFeature.prototype.constructor = MediaFeature;
/*global SyntaxUnit, Parser*/
/**
* Represents an individual media query.
* @namespace parserlib.css
* @class MediaQuery
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {String} modifier The modifier "not" or "only" (or null).
* @param {String} mediaType The type of media (i.e., "print").
* @param {Array} parts Array of selectors parts making up this selector.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function MediaQuery(modifier, mediaType, features, line, col){
SyntaxUnit.call(this, (modifier ? modifier + " ": "") + (mediaType ? mediaType + " " : "") + features.join(" and "), line, col, Parser.MEDIA_QUERY_TYPE);
/**
* The media modifier ("not" or "only")
* @type String
* @property modifier
*/
this.modifier = modifier;
/**
* The mediaType (i.e., "print")
* @type String
* @property mediaType
*/
this.mediaType = mediaType;
/**
* The parts that make up the selector.
* @type Array
* @property features
*/
this.features = features;
}
MediaQuery.prototype = new SyntaxUnit();
MediaQuery.prototype.constructor = MediaQuery;
/*global Tokens, TokenStream, SyntaxError, Properties, Validation, ValidationError, SyntaxUnit,
PropertyValue, PropertyValuePart, SelectorPart, SelectorSubPart, Selector,
PropertyName, Combinator, MediaFeature, MediaQuery, EventTarget */
/**
* A CSS3 parser.
* @namespace parserlib.css
* @class Parser
* @constructor
* @param {Object} options (Optional) Various options for the parser:
* starHack (true|false) to allow IE6 star hack as valid,
* underscoreHack (true|false) to interpret leading underscores
* as IE6-7 targeting for known properties, ieFilters (true|false)
* to indicate that IE < 8 filters should be accepted and not throw
* syntax errors.
*/
function Parser(options){
//inherit event functionality
EventTarget.call(this);
this.options = options || {};
this._tokenStream = null;
}
//Static constants
Parser.DEFAULT_TYPE = 0;
Parser.COMBINATOR_TYPE = 1;
Parser.MEDIA_FEATURE_TYPE = 2;
Parser.MEDIA_QUERY_TYPE = 3;
Parser.PROPERTY_NAME_TYPE = 4;
Parser.PROPERTY_VALUE_TYPE = 5;
Parser.PROPERTY_VALUE_PART_TYPE = 6;
Parser.SELECTOR_TYPE = 7;
Parser.SELECTOR_PART_TYPE = 8;
Parser.SELECTOR_SUB_PART_TYPE = 9;
Parser.prototype = function(){
var proto = new EventTarget(), //new prototype
prop,
additions = {
//restore constructor
constructor: Parser,
//instance constants - yuck
DEFAULT_TYPE : 0,
COMBINATOR_TYPE : 1,
MEDIA_FEATURE_TYPE : 2,
MEDIA_QUERY_TYPE : 3,
PROPERTY_NAME_TYPE : 4,
PROPERTY_VALUE_TYPE : 5,
PROPERTY_VALUE_PART_TYPE : 6,
SELECTOR_TYPE : 7,
SELECTOR_PART_TYPE : 8,
SELECTOR_SUB_PART_TYPE : 9,
//-----------------------------------------------------------------
// Grammar
//-----------------------------------------------------------------
_stylesheet: function(){
/*
* stylesheet
* : [ CHARSET_SYM S* STRING S* ';' ]?
* [S|CDO|CDC]* [ import [S|CDO|CDC]* ]*
* [ namespace [S|CDO|CDC]* ]*
* [ [ ruleset | media | page | font_face | keyframes ] [S|CDO|CDC]* ]*
* ;
*/
var tokenStream = this._tokenStream,
charset = null,
count,
token,
tt;
this.fire("startstylesheet");
//try to read character set
this._charset();
this._skipCruft();
//try to read imports - may be more than one
while (tokenStream.peek() == Tokens.IMPORT_SYM){
this._import();
this._skipCruft();
}
//try to read namespaces - may be more than one
while (tokenStream.peek() == Tokens.NAMESPACE_SYM){
this._namespace();
this._skipCruft();
}
//get the next token
tt = tokenStream.peek();
//try to read the rest
while(tt > Tokens.EOF){
try {
switch(tt){
case Tokens.MEDIA_SYM:
this._media();
this._skipCruft();
break;
case Tokens.PAGE_SYM:
this._page();
this._skipCruft();
break;
case Tokens.FONT_FACE_SYM:
this._font_face();
this._skipCruft();
break;
case Tokens.KEYFRAMES_SYM:
this._keyframes();
this._skipCruft();
break;
case Tokens.UNKNOWN_SYM: //unknown @ rule
tokenStream.get();
if (!this.options.strict){
//fire error event
this.fire({
type: "error",
error: null,
message: "Unknown @ rule: " + tokenStream.LT(0).value + ".",
line: tokenStream.LT(0).startLine,
col: tokenStream.LT(0).startCol
});
//skip braces
count=0;
while (tokenStream.advance([Tokens.LBRACE, Tokens.RBRACE]) == Tokens.LBRACE){
count++; //keep track of nesting depth
}
while(count){
tokenStream.advance([Tokens.RBRACE]);
count--;
}
} else {
//not a syntax error, rethrow it
throw new SyntaxError("Unknown @ rule.", tokenStream.LT(0).startLine, tokenStream.LT(0).startCol);
}
break;
case Tokens.S:
this._readWhitespace();
break;
default:
if(!this._ruleset()){
//error handling for known issues
switch(tt){
case Tokens.CHARSET_SYM:
token = tokenStream.LT(1);
this._charset(false);
throw new SyntaxError("@charset not allowed here.", token.startLine, token.startCol);
case Tokens.IMPORT_SYM:
token = tokenStream.LT(1);
this._import(false);
throw new SyntaxError("@import not allowed here.", token.startLine, token.startCol);
case Tokens.NAMESPACE_SYM:
token = tokenStream.LT(1);
this._namespace(false);
throw new SyntaxError("@namespace not allowed here.", token.startLine, token.startCol);
default:
tokenStream.get(); //get the last token
this._unexpectedToken(tokenStream.token());
}
}
}
} catch(ex) {
if (ex instanceof SyntaxError && !this.options.strict){
this.fire({
type: "error",
error: ex,
message: ex.message,
line: ex.line,
col: ex.col
});
} else {
throw ex;
}
}
tt = tokenStream.peek();
}
if (tt != Tokens.EOF){
this._unexpectedToken(tokenStream.token());
}
this.fire("endstylesheet");
},
_charset: function(emit){
var tokenStream = this._tokenStream,
charset,
token,
line,
col;
if (tokenStream.match(Tokens.CHARSET_SYM)){
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this._readWhitespace();
tokenStream.mustMatch(Tokens.STRING);
token = tokenStream.token();
charset = token.value;
this._readWhitespace();
tokenStream.mustMatch(Tokens.SEMICOLON);
if (emit !== false){
this.fire({
type: "charset",
charset:charset,
line: line,
col: col
});
}
}
},
_import: function(emit){
/*
* import
* : IMPORT_SYM S*
* [STRING|URI] S* media_query_list? ';' S*
*/
var tokenStream = this._tokenStream,
tt,
uri,
importToken,
mediaList = [];
//read import symbol
tokenStream.mustMatch(Tokens.IMPORT_SYM);
importToken = tokenStream.token();
this._readWhitespace();
tokenStream.mustMatch([Tokens.STRING, Tokens.URI]);
//grab the URI value
uri = tokenStream.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/, "$1");
this._readWhitespace();
mediaList = this._media_query_list();
//must end with a semicolon
tokenStream.mustMatch(Tokens.SEMICOLON);
this._readWhitespace();
if (emit !== false){
this.fire({
type: "import",
uri: uri,
media: mediaList,
line: importToken.startLine,
col: importToken.startCol
});
}
},
_namespace: function(emit){
/*
* namespace
* : NAMESPACE_SYM S* [namespace_prefix S*]? [STRING|URI] S* ';' S*
*/
var tokenStream = this._tokenStream,
line,
col,
prefix,
uri;
//read import symbol
tokenStream.mustMatch(Tokens.NAMESPACE_SYM);
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this._readWhitespace();
//it's a namespace prefix - no _namespace_prefix() method because it's just an IDENT
if (tokenStream.match(Tokens.IDENT)){
prefix = tokenStream.token().value;
this._readWhitespace();
}
tokenStream.mustMatch([Tokens.STRING, Tokens.URI]);
/*if (!tokenStream.match(Tokens.STRING)){
tokenStream.mustMatch(Tokens.URI);
}*/
//grab the URI value
uri = tokenStream.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/, "$1");
this._readWhitespace();
//must end with a semicolon
tokenStream.mustMatch(Tokens.SEMICOLON);
this._readWhitespace();
if (emit !== false){
this.fire({
type: "namespace",
prefix: prefix,
uri: uri,
line: line,
col: col
});
}
},
_media: function(){
/*
* media
* : MEDIA_SYM S* media_query_list S* '{' S* ruleset* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
line,
col,
mediaList;// = [];
//look for @media
tokenStream.mustMatch(Tokens.MEDIA_SYM);
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this._readWhitespace();
mediaList = this._media_query_list();
tokenStream.mustMatch(Tokens.LBRACE);
this._readWhitespace();
this.fire({
type: "startmedia",
media: mediaList,
line: line,
col: col
});
while(true) {
if (tokenStream.peek() == Tokens.PAGE_SYM){
this._page();
} else if (!this._ruleset()){
break;
}
}
tokenStream.mustMatch(Tokens.RBRACE);
this._readWhitespace();
this.fire({
type: "endmedia",
media: mediaList,
line: line,
col: col
});
},
//CSS3 Media Queries
_media_query_list: function(){
/*
* media_query_list
* : S* [media_query [ ',' S* media_query ]* ]?
* ;
*/
var tokenStream = this._tokenStream,
mediaList = [];
this._readWhitespace();
if (tokenStream.peek() == Tokens.IDENT || tokenStream.peek() == Tokens.LPAREN){
mediaList.push(this._media_query());
}
while(tokenStream.match(Tokens.COMMA)){
this._readWhitespace();
mediaList.push(this._media_query());
}
return mediaList;
},
/*
* Note: "expression" in the grammar maps to the _media_expression
* method.
*/
_media_query: function(){
/*
* media_query
* : [ONLY | NOT]? S* media_type S* [ AND S* expression ]*
* | expression [ AND S* expression ]*
* ;
*/
var tokenStream = this._tokenStream,
type = null,
ident = null,
token = null,
expressions = [];
if (tokenStream.match(Tokens.IDENT)){
ident = tokenStream.token().value.toLowerCase();
//since there's no custom tokens for these, need to manually check
if (ident != "only" && ident != "not"){
tokenStream.unget();
ident = null;
} else {
token = tokenStream.token();
}
}
this._readWhitespace();
if (tokenStream.peek() == Tokens.IDENT){
type = this._media_type();
if (token === null){
token = tokenStream.token();
}
} else if (tokenStream.peek() == Tokens.LPAREN){
if (token === null){
token = tokenStream.LT(1);
}
expressions.push(this._media_expression());
}
if (type === null && expressions.length === 0){
return null;
} else {
this._readWhitespace();
while (tokenStream.match(Tokens.IDENT)){
if (tokenStream.token().value.toLowerCase() != "and"){
this._unexpectedToken(tokenStream.token());
}
this._readWhitespace();
expressions.push(this._media_expression());
}
}
return new MediaQuery(ident, type, expressions, token.startLine, token.startCol);
},
//CSS3 Media Queries
_media_type: function(){
/*
* media_type
* : IDENT
* ;
*/
return this._media_feature();
},
/**
* Note: in CSS3 Media Queries, this is called "expression".
* Renamed here to avoid conflict with CSS3 Selectors
* definition of "expression". Also note that "expr" in the
* grammar now maps to "expression" from CSS3 selectors.
* @method _media_expression
* @private
*/
_media_expression: function(){
/*
* expression
* : '(' S* media_feature S* [ ':' S* expr ]? ')' S*
* ;
*/
var tokenStream = this._tokenStream,
feature = null,
token,
expression = null;
tokenStream.mustMatch(Tokens.LPAREN);
feature = this._media_feature();
this._readWhitespace();
if (tokenStream.match(Tokens.COLON)){
this._readWhitespace();
token = tokenStream.LT(1);
expression = this._expression();
}
tokenStream.mustMatch(Tokens.RPAREN);
this._readWhitespace();
return new MediaFeature(feature, (expression ? new SyntaxUnit(expression, token.startLine, token.startCol) : null));
},
//CSS3 Media Queries
_media_feature: function(){
/*
* media_feature
* : IDENT
* ;
*/
var tokenStream = this._tokenStream;
tokenStream.mustMatch(Tokens.IDENT);
return SyntaxUnit.fromToken(tokenStream.token());
},
//CSS3 Paged Media
_page: function(){
/*
* page:
* PAGE_SYM S* IDENT? pseudo_page? S*
* '{' S* [ declaration | margin ]? [ ';' S* [ declaration | margin ]? ]* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
line,
col,
identifier = null,
pseudoPage = null;
//look for @page
tokenStream.mustMatch(Tokens.PAGE_SYM);
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this._readWhitespace();
if (tokenStream.match(Tokens.IDENT)){
identifier = tokenStream.token().value;
//The value 'auto' may not be used as a page name and MUST be treated as a syntax error.
if (identifier.toLowerCase() === "auto"){
this._unexpectedToken(tokenStream.token());
}
}
//see if there's a colon upcoming
if (tokenStream.peek() == Tokens.COLON){
pseudoPage = this._pseudo_page();
}
this._readWhitespace();
this.fire({
type: "startpage",
id: identifier,
pseudo: pseudoPage,
line: line,
col: col
});
this._readDeclarations(true, true);
this.fire({
type: "endpage",
id: identifier,
pseudo: pseudoPage,
line: line,
col: col
});
},
//CSS3 Paged Media
_margin: function(){
/*
* margin :
* margin_sym S* '{' declaration [ ';' S* declaration? ]* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
line,
col,
marginSym = this._margin_sym();
if (marginSym){
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this.fire({
type: "startpagemargin",
margin: marginSym,
line: line,
col: col
});
this._readDeclarations(true);
this.fire({
type: "endpagemargin",
margin: marginSym,
line: line,
col: col
});
return true;
} else {
return false;
}
},
//CSS3 Paged Media
_margin_sym: function(){
/*
* margin_sym :
* TOPLEFTCORNER_SYM |
* TOPLEFT_SYM |
* TOPCENTER_SYM |
* TOPRIGHT_SYM |
* TOPRIGHTCORNER_SYM |
* BOTTOMLEFTCORNER_SYM |
* BOTTOMLEFT_SYM |
* BOTTOMCENTER_SYM |
* BOTTOMRIGHT_SYM |
* BOTTOMRIGHTCORNER_SYM |
* LEFTTOP_SYM |
* LEFTMIDDLE_SYM |
* LEFTBOTTOM_SYM |
* RIGHTTOP_SYM |
* RIGHTMIDDLE_SYM |
* RIGHTBOTTOM_SYM
* ;
*/
var tokenStream = this._tokenStream;
if(tokenStream.match([Tokens.TOPLEFTCORNER_SYM, Tokens.TOPLEFT_SYM,
Tokens.TOPCENTER_SYM, Tokens.TOPRIGHT_SYM, Tokens.TOPRIGHTCORNER_SYM,
Tokens.BOTTOMLEFTCORNER_SYM, Tokens.BOTTOMLEFT_SYM,
Tokens.BOTTOMCENTER_SYM, Tokens.BOTTOMRIGHT_SYM,
Tokens.BOTTOMRIGHTCORNER_SYM, Tokens.LEFTTOP_SYM,
Tokens.LEFTMIDDLE_SYM, Tokens.LEFTBOTTOM_SYM, Tokens.RIGHTTOP_SYM,
Tokens.RIGHTMIDDLE_SYM, Tokens.RIGHTBOTTOM_SYM]))
{
return SyntaxUnit.fromToken(tokenStream.token());
} else {
return null;
}
},
_pseudo_page: function(){
/*
* pseudo_page
* : ':' IDENT
* ;
*/
var tokenStream = this._tokenStream;
tokenStream.mustMatch(Tokens.COLON);
tokenStream.mustMatch(Tokens.IDENT);
//TODO: CSS3 Paged Media says only "left", "center", and "right" are allowed
return tokenStream.token().value;
},
_font_face: function(){
/*
* font_face
* : FONT_FACE_SYM S*
* '{' S* declaration [ ';' S* declaration ]* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
line,
col;
//look for @page
tokenStream.mustMatch(Tokens.FONT_FACE_SYM);
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this._readWhitespace();
this.fire({
type: "startfontface",
line: line,
col: col
});
this._readDeclarations(true);
this.fire({
type: "endfontface",
line: line,
col: col
});
},
_operator: function(){
/*
* operator
* : '/' S* | ',' S* | /( empty )/
* ;
*/
var tokenStream = this._tokenStream,
token = null;
if (tokenStream.match([Tokens.SLASH, Tokens.COMMA])){
token = tokenStream.token();
this._readWhitespace();
}
return token ? PropertyValuePart.fromToken(token) : null;
},
_combinator: function(){
/*
* combinator
* : PLUS S* | GREATER S* | TILDE S* | S+
* ;
*/
var tokenStream = this._tokenStream,
value = null,
token;
if(tokenStream.match([Tokens.PLUS, Tokens.GREATER, Tokens.TILDE])){
token = tokenStream.token();
value = new Combinator(token.value, token.startLine, token.startCol);
this._readWhitespace();
}
return value;
},
_unary_operator: function(){
/*
* unary_operator
* : '-' | '+'
* ;
*/
var tokenStream = this._tokenStream;
if (tokenStream.match([Tokens.MINUS, Tokens.PLUS])){
return tokenStream.token().value;
} else {
return null;
}
},
_property: function(){
/*
* property
* : IDENT S*
* ;
*/
var tokenStream = this._tokenStream,
value = null,
hack = null,
tokenValue,
token,
line,
col;
//check for star hack - throws error if not allowed
if (tokenStream.peek() == Tokens.STAR && this.options.starHack){
tokenStream.get();
token = tokenStream.token();
hack = token.value;
line = token.startLine;
col = token.startCol;
}
if(tokenStream.match(Tokens.IDENT)){
token = tokenStream.token();
tokenValue = token.value;
//check for underscore hack - no error if not allowed because it's valid CSS syntax
if (tokenValue.charAt(0) == "_" && this.options.underscoreHack){
hack = "_";
tokenValue = tokenValue.substring(1);
}
value = new PropertyName(tokenValue, hack, (line||token.startLine), (col||token.startCol));
this._readWhitespace();
}
return value;
},
//Augmented with CSS3 Selectors
_ruleset: function(){
/*
* ruleset
* : selectors_group
* '{' S* declaration? [ ';' S* declaration? ]* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
tt,
selectors;
/*
* Error Recovery: If even a single selector fails to parse,
* then the entire ruleset should be thrown away.
*/
try {
selectors = this._selectors_group();
} catch (ex){
if (ex instanceof SyntaxError && !this.options.strict){
//fire error event
this.fire({
type: "error",
error: ex,
message: ex.message,
line: ex.line,
col: ex.col
});
//skip over everything until closing brace
tt = tokenStream.advance([Tokens.RBRACE]);
if (tt == Tokens.RBRACE){
//if there's a right brace, the rule is finished so don't do anything
} else {
//otherwise, rethrow the error because it wasn't handled properly
throw ex;
}
} else {
//not a syntax error, rethrow it
throw ex;
}
//trigger parser to continue
return true;
}
//if it got here, all selectors parsed
if (selectors){
this.fire({
type: "startrule",
selectors: selectors,
line: selectors[0].line,
col: selectors[0].col
});
this._readDeclarations(true);
this.fire({
type: "endrule",
selectors: selectors,
line: selectors[0].line,
col: selectors[0].col
});
}
return selectors;
},
//CSS3 Selectors
_selectors_group: function(){
/*
* selectors_group
* : selector [ COMMA S* selector ]*
* ;
*/
var tokenStream = this._tokenStream,
selectors = [],
selector;
selector = this._selector();
if (selector !== null){
selectors.push(selector);
while(tokenStream.match(Tokens.COMMA)){
this._readWhitespace();
selector = this._selector();
if (selector !== null){
selectors.push(selector);
} else {
this._unexpectedToken(tokenStream.LT(1));
}
}
}
return selectors.length ? selectors : null;
},
//CSS3 Selectors
_selector: function(){
/*
* selector
* : simple_selector_sequence [ combinator simple_selector_sequence ]*
* ;
*/
var tokenStream = this._tokenStream,
selector = [],
nextSelector = null,
combinator = null,
ws = null;
//if there's no simple selector, then there's no selector
nextSelector = this._simple_selector_sequence();
if (nextSelector === null){
return null;
}
selector.push(nextSelector);
do {
//look for a combinator
combinator = this._combinator();
if (combinator !== null){
selector.push(combinator);
nextSelector = this._simple_selector_sequence();
//there must be a next selector
if (nextSelector === null){
this._unexpectedToken(this.LT(1));
} else {
//nextSelector is an instance of SelectorPart
selector.push(nextSelector);
}
} else {
//if there's not whitespace, we're done
if (this._readWhitespace()){
//add whitespace separator
ws = new Combinator(tokenStream.token().value, tokenStream.token().startLine, tokenStream.token().startCol);
//combinator is not required
combinator = this._combinator();
//selector is required if there's a combinator
nextSelector = this._simple_selector_sequence();
if (nextSelector === null){
if (combinator !== null){
this._unexpectedToken(tokenStream.LT(1));
}
} else {
if (combinator !== null){
selector.push(combinator);
} else {
selector.push(ws);
}
selector.push(nextSelector);
}
} else {
break;
}
}
} while(true);
return new Selector(selector, selector[0].line, selector[0].col);
},
//CSS3 Selectors
_simple_selector_sequence: function(){
/*
* simple_selector_sequence
* : [ type_selector | universal ]
* [ HASH | class | attrib | pseudo | negation ]*
* | [ HASH | class | attrib | pseudo | negation ]+
* ;
*/
var tokenStream = this._tokenStream,
//parts of a simple selector
elementName = null,
modifiers = [],
//complete selector text
selectorText= "",
//the different parts after the element name to search for
components = [
//HASH
function(){
return tokenStream.match(Tokens.HASH) ?
new SelectorSubPart(tokenStream.token().value, "id", tokenStream.token().startLine, tokenStream.token().startCol) :
null;
},
this._class,
this._attrib,
this._pseudo,
this._negation
],
i = 0,
len = components.length,
component = null,
found = false,
line,
col;
//get starting line and column for the selector
line = tokenStream.LT(1).startLine;
col = tokenStream.LT(1).startCol;
elementName = this._type_selector();
if (!elementName){
elementName = this._universal();
}
if (elementName !== null){
selectorText += elementName;
}
while(true){
//whitespace means we're done
if (tokenStream.peek() === Tokens.S){
break;
}
//check for each component
while(i < len && component === null){
component = components[i++].call(this);
}
if (component === null){
//we don't have a selector
if (selectorText === ""){
return null;
} else {
break;
}
} else {
i = 0;
modifiers.push(component);
selectorText += component.toString();
component = null;
}
}
return selectorText !== "" ?
new SelectorPart(elementName, modifiers, selectorText, line, col) :
null;
},
//CSS3 Selectors
_type_selector: function(){
/*
* type_selector
* : [ namespace_prefix ]? element_name
* ;
*/
var tokenStream = this._tokenStream,
ns = this._namespace_prefix(),
elementName = this._element_name();
if (!elementName){
/*
* Need to back out the namespace that was read due to both
* type_selector and universal reading namespace_prefix
* first. Kind of hacky, but only way I can figure out
* right now how to not change the grammar.
*/
if (ns){
tokenStream.unget();
if (ns.length > 1){
tokenStream.unget();
}
}
return null;
} else {
if (ns){
elementName.text = ns + elementName.text;
elementName.col -= ns.length;
}
return elementName;
}
},
//CSS3 Selectors
_class: function(){
/*
* class
* : '.' IDENT
* ;
*/
var tokenStream = this._tokenStream,
token;
if (tokenStream.match(Tokens.DOT)){
tokenStream.mustMatch(Tokens.IDENT);
token = tokenStream.token();
return new SelectorSubPart("." + token.value, "class", token.startLine, token.startCol - 1);
} else {
return null;
}
},
//CSS3 Selectors
_element_name: function(){
/*
* element_name
* : IDENT
* ;
*/
var tokenStream = this._tokenStream,
token;
if (tokenStream.match(Tokens.IDENT)){
token = tokenStream.token();
return new SelectorSubPart(token.value, "elementName", token.startLine, token.startCol);
} else {
return null;
}
},
//CSS3 Selectors
_namespace_prefix: function(){
/*
* namespace_prefix
* : [ IDENT | '*' ]? '|'
* ;
*/
var tokenStream = this._tokenStream,
value = "";
//verify that this is a namespace prefix
if (tokenStream.LA(1) === Tokens.PIPE || tokenStream.LA(2) === Tokens.PIPE){
if(tokenStream.match([Tokens.IDENT, Tokens.STAR])){
value += tokenStream.token().value;
}
tokenStream.mustMatch(Tokens.PIPE);
value += "|";
}
return value.length ? value : null;
},
//CSS3 Selectors
_universal: function(){
/*
* universal
* : [ namespace_prefix ]? '*'
* ;
*/
var tokenStream = this._tokenStream,
value = "",
ns;
ns = this._namespace_prefix();
if(ns){
value += ns;
}
if(tokenStream.match(Tokens.STAR)){
value += "*";
}
return value.length ? value : null;
},
//CSS3 Selectors
_attrib: function(){
/*
* attrib
* : '[' S* [ namespace_prefix ]? IDENT S*
* [ [ PREFIXMATCH |
* SUFFIXMATCH |
* SUBSTRINGMATCH |
* '=' |
* INCLUDES |
* DASHMATCH ] S* [ IDENT | STRING ] S*
* ]? ']'
* ;
*/
var tokenStream = this._tokenStream,
value = null,
ns,
token;
if (tokenStream.match(Tokens.LBRACKET)){
token = tokenStream.token();
value = token.value;
value += this._readWhitespace();
ns = this._namespace_prefix();
if (ns){
value += ns;
}
tokenStream.mustMatch(Tokens.IDENT);
value += tokenStream.token().value;
value += this._readWhitespace();
if(tokenStream.match([Tokens.PREFIXMATCH, Tokens.SUFFIXMATCH, Tokens.SUBSTRINGMATCH,
Tokens.EQUALS, Tokens.INCLUDES, Tokens.DASHMATCH])){
value += tokenStream.token().value;
value += this._readWhitespace();
tokenStream.mustMatch([Tokens.IDENT, Tokens.STRING]);
value += tokenStream.token().value;
value += this._readWhitespace();
}
tokenStream.mustMatch(Tokens.RBRACKET);
return new SelectorSubPart(value + "]", "attribute", token.startLine, token.startCol);
} else {
return null;
}
},
//CSS3 Selectors
_pseudo: function(){
/*
* pseudo
* : ':' ':'? [ IDENT | functional_pseudo ]
* ;
*/
var tokenStream = this._tokenStream,
pseudo = null,
colons = ":",
line,
col;
if (tokenStream.match(Tokens.COLON)){
if (tokenStream.match(Tokens.COLON)){
colons += ":";
}
if (tokenStream.match(Tokens.IDENT)){
pseudo = tokenStream.token().value;
line = tokenStream.token().startLine;
col = tokenStream.token().startCol - colons.length;
} else if (tokenStream.peek() == Tokens.FUNCTION){
line = tokenStream.LT(1).startLine;
col = tokenStream.LT(1).startCol - colons.length;
pseudo = this._functional_pseudo();
}
if (pseudo){
pseudo = new SelectorSubPart(colons + pseudo, "pseudo", line, col);
}
}
return pseudo;
},
//CSS3 Selectors
_functional_pseudo: function(){
/*
* functional_pseudo
* : FUNCTION S* expression ')'
* ;
*/
var tokenStream = this._tokenStream,
value = null;
if(tokenStream.match(Tokens.FUNCTION)){
value = tokenStream.token().value;
value += this._readWhitespace();
value += this._expression();
tokenStream.mustMatch(Tokens.RPAREN);
value += ")";
}
return value;
},
//CSS3 Selectors
_expression: function(){
/*
* expression
* : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+
* ;
*/
var tokenStream = this._tokenStream,
value = "";
while(tokenStream.match([Tokens.PLUS, Tokens.MINUS, Tokens.DIMENSION,
Tokens.NUMBER, Tokens.STRING, Tokens.IDENT, Tokens.LENGTH,
Tokens.FREQ, Tokens.ANGLE, Tokens.TIME,
Tokens.RESOLUTION])){
value += tokenStream.token().value;
value += this._readWhitespace();
}
return value.length ? value : null;
},
//CSS3 Selectors
_negation: function(){
/*
* negation
* : NOT S* negation_arg S* ')'
* ;
*/
var tokenStream = this._tokenStream,
line,
col,
value = "",
arg,
subpart = null;
if (tokenStream.match(Tokens.NOT)){
value = tokenStream.token().value;
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
value += this._readWhitespace();
arg = this._negation_arg();
value += arg;
value += this._readWhitespace();
tokenStream.match(Tokens.RPAREN);
value += tokenStream.token().value;
subpart = new SelectorSubPart(value, "not", line, col);
subpart.args.push(arg);
}
return subpart;
},
//CSS3 Selectors
_negation_arg: function(){
/*
* negation_arg
* : type_selector | universal | HASH | class | attrib | pseudo
* ;
*/
var tokenStream = this._tokenStream,
args = [
this._type_selector,
this._universal,
function(){
return tokenStream.match(Tokens.HASH) ?
new SelectorSubPart(tokenStream.token().value, "id", tokenStream.token().startLine, tokenStream.token().startCol) :
null;
},
this._class,
this._attrib,
this._pseudo
],
arg = null,
i = 0,
len = args.length,
elementName,
line,
col,
part;
line = tokenStream.LT(1).startLine;
col = tokenStream.LT(1).startCol;
while(i < len && arg === null){
arg = args[i].call(this);
i++;
}
//must be a negation arg
if (arg === null){
this._unexpectedToken(tokenStream.LT(1));
}
//it's an element name
if (arg.type == "elementName"){
part = new SelectorPart(arg, [], arg.toString(), line, col);
} else {
part = new SelectorPart(null, [arg], arg.toString(), line, col);
}
return part;
},
_declaration: function(){
/*
* declaration
* : property ':' S* expr prio?
* | /( empty )/
* ;
*/
var tokenStream = this._tokenStream,
property = null,
expr = null,
prio = null,
error = null,
invalid = null,
propertyName= "";
property = this._property();
if (property !== null){
tokenStream.mustMatch(Tokens.COLON);
this._readWhitespace();
expr = this._expr();
//if there's no parts for the value, it's an error
if (!expr || expr.length === 0){
this._unexpectedToken(tokenStream.LT(1));
}
prio = this._prio();
/*
* If hacks should be allowed, then only check the root
* property. If hacks should not be allowed, treat
* _property or *property as invalid properties.
*/
propertyName = property.toString();
if (this.options.starHack && property.hack == "*" ||
this.options.underscoreHack && property.hack == "_") {
propertyName = property.text;
}
try {
this._validateProperty(propertyName, expr);
} catch (ex) {
invalid = ex;
}
this.fire({
type: "property",
property: property,
value: expr,
important: prio,
line: property.line,
col: property.col,
invalid: invalid
});
return true;
} else {
return false;
}
},
_prio: function(){
/*
* prio
* : IMPORTANT_SYM S*
* ;
*/
var tokenStream = this._tokenStream,
result = tokenStream.match(Tokens.IMPORTANT_SYM);
this._readWhitespace();
return result;
},
_expr: function(){
/*
* expr
* : term [ operator term ]*
* ;
*/
var tokenStream = this._tokenStream,
values = [],
//valueParts = [],
value = null,
operator = null;
value = this._term();
if (value !== null){
values.push(value);
do {
operator = this._operator();
//if there's an operator, keep building up the value parts
if (operator){
values.push(operator);
} /*else {
//if there's not an operator, you have a full value
values.push(new PropertyValue(valueParts, valueParts[0].line, valueParts[0].col));
valueParts = [];
}*/
value = this._term();
if (value === null){
break;
} else {
values.push(value);
}
} while(true);
}
//cleanup
/*if (valueParts.length){
values.push(new PropertyValue(valueParts, valueParts[0].line, valueParts[0].col));
}*/
return values.length > 0 ? new PropertyValue(values, values[0].line, values[0].col) : null;
},
_term: function(){
/*
* term
* : unary_operator?
* [ NUMBER S* | PERCENTAGE S* | LENGTH S* | ANGLE S* |
* TIME S* | FREQ S* | function | ie_function ]
* | STRING S* | IDENT S* | URI S* | UNICODERANGE S* | hexcolor
* ;
*/
var tokenStream = this._tokenStream,
unary = null,
value = null,
token,
line,
col;
//returns the operator or null
unary = this._unary_operator();
if (unary !== null){
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
}
//exception for IE filters
if (tokenStream.peek() == Tokens.IE_FUNCTION && this.options.ieFilters){
value = this._ie_function();
if (unary === null){
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
}
//see if there's a simple match
} else if (tokenStream.match([Tokens.NUMBER, Tokens.PERCENTAGE, Tokens.LENGTH,
Tokens.ANGLE, Tokens.TIME,
Tokens.FREQ, Tokens.STRING, Tokens.IDENT, Tokens.URI, Tokens.UNICODE_RANGE])){
value = tokenStream.token().value;
if (unary === null){
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
}
this._readWhitespace();
} else {
//see if it's a color
token = this._hexcolor();
if (token === null){
//if there's no unary, get the start of the next token for line/col info
if (unary === null){
line = tokenStream.LT(1).startLine;
col = tokenStream.LT(1).startCol;
}
//has to be a function
if (value === null){
/*
* This checks for alpha(opacity=0) style of IE
* functions. IE_FUNCTION only presents progid: style.
*/
if (tokenStream.LA(3) == Tokens.EQUALS && this.options.ieFilters){
value = this._ie_function();
} else {
value = this._function();
}
}
/*if (value === null){
return null;
//throw new Error("Expected identifier at line " + tokenStream.token().startLine + ", character " + tokenStream.token().startCol + ".");
}*/
} else {
value = token.value;
if (unary === null){
line = token.startLine;
col = token.startCol;
}
}
}
return value !== null ?
new PropertyValuePart(unary !== null ? unary + value : value, line, col) :
null;
},
_function: function(){
/*
* function
* : FUNCTION S* expr ')' S*
* ;
*/
var tokenStream = this._tokenStream,
functionText = null,
expr = null,
lt;
if (tokenStream.match(Tokens.FUNCTION)){
functionText = tokenStream.token().value;
this._readWhitespace();
expr = this._expr();
functionText += expr;
//START: Horrible hack in case it's an IE filter
if (this.options.ieFilters && tokenStream.peek() == Tokens.EQUALS){
do {
if (this._readWhitespace()){
functionText += tokenStream.token().value;
}
//might be second time in the loop
if (tokenStream.LA(0) == Tokens.COMMA){
functionText += tokenStream.token().value;
}
tokenStream.match(Tokens.IDENT);
functionText += tokenStream.token().value;
tokenStream.match(Tokens.EQUALS);
functionText += tokenStream.token().value;
//functionText += this._term();
lt = tokenStream.peek();
while(lt != Tokens.COMMA && lt != Tokens.S && lt != Tokens.RPAREN){
tokenStream.get();
functionText += tokenStream.token().value;
lt = tokenStream.peek();
}
} while(tokenStream.match([Tokens.COMMA, Tokens.S]));
}
//END: Horrible Hack
tokenStream.match(Tokens.RPAREN);
functionText += ")";
this._readWhitespace();
}
return functionText;
},
_ie_function: function(){
/* (My own extension)
* ie_function
* : IE_FUNCTION S* IDENT '=' term [S* ','? IDENT '=' term]+ ')' S*
* ;
*/
var tokenStream = this._tokenStream,
functionText = null,
expr = null,
lt;
//IE function can begin like a regular function, too
if (tokenStream.match([Tokens.IE_FUNCTION, Tokens.FUNCTION])){
functionText = tokenStream.token().value;
do {
if (this._readWhitespace()){
functionText += tokenStream.token().value;
}
//might be second time in the loop
if (tokenStream.LA(0) == Tokens.COMMA){
functionText += tokenStream.token().value;
}
tokenStream.match(Tokens.IDENT);
functionText += tokenStream.token().value;
tokenStream.match(Tokens.EQUALS);
functionText += tokenStream.token().value;
//functionText += this._term();
lt = tokenStream.peek();
while(lt != Tokens.COMMA && lt != Tokens.S && lt != Tokens.RPAREN){
tokenStream.get();
functionText += tokenStream.token().value;
lt = tokenStream.peek();
}
} while(tokenStream.match([Tokens.COMMA, Tokens.S]));
tokenStream.match(Tokens.RPAREN);
functionText += ")";
this._readWhitespace();
}
return functionText;
},
_hexcolor: function(){
/*
* There is a constraint on the color that it must
* have either 3 or 6 hex-digits (i.e., [0-9a-fA-F])
* after the "#"; e.g., "#000" is OK, but "#abcd" is not.
*
* hexcolor
* : HASH S*
* ;
*/
var tokenStream = this._tokenStream,
token = null,
color;
if(tokenStream.match(Tokens.HASH)){
//need to do some validation here
token = tokenStream.token();
color = token.value;
if (!/#[a-f0-9]{3,6}/i.test(color)){
throw new SyntaxError("Expected a hex color but found '" + color + "' at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
}
this._readWhitespace();
}
return token;
},
//-----------------------------------------------------------------
// Animations methods
//-----------------------------------------------------------------
_keyframes: function(){
/*
* keyframes:
* : KEYFRAMES_SYM S* keyframe_name S* '{' S* keyframe_rule* '}' {
* ;
*/
var tokenStream = this._tokenStream,
token,
tt,
name,
prefix = "";
tokenStream.mustMatch(Tokens.KEYFRAMES_SYM);
token = tokenStream.token();
if (/^@\-([^\-]+)\-/.test(token.value)) {
prefix = RegExp.$1;
}
this._readWhitespace();
name = this._keyframe_name();
this._readWhitespace();
tokenStream.mustMatch(Tokens.LBRACE);
this.fire({
type: "startkeyframes",
name: name,
prefix: prefix,
line: token.startLine,
col: token.startCol
});
this._readWhitespace();
tt = tokenStream.peek();
//check for key
while(tt == Tokens.IDENT || tt == Tokens.PERCENTAGE) {
this._keyframe_rule();
this._readWhitespace();
tt = tokenStream.peek();
}
this.fire({
type: "endkeyframes",
name: name,
prefix: prefix,
line: token.startLine,
col: token.startCol
});
this._readWhitespace();
tokenStream.mustMatch(Tokens.RBRACE);
},
_keyframe_name: function(){
/*
* keyframe_name:
* : IDENT
* | STRING
* ;
*/
var tokenStream = this._tokenStream,
token;
tokenStream.mustMatch([Tokens.IDENT, Tokens.STRING]);
return SyntaxUnit.fromToken(tokenStream.token());
},
_keyframe_rule: function(){
/*
* keyframe_rule:
* : key_list S*
* '{' S* declaration [ ';' S* declaration ]* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
token,
keyList = this._key_list();
this.fire({
type: "startkeyframerule",
keys: keyList,
line: keyList[0].line,
col: keyList[0].col
});
this._readDeclarations(true);
this.fire({
type: "endkeyframerule",
keys: keyList,
line: keyList[0].line,
col: keyList[0].col
});
},
_key_list: function(){
/*
* key_list:
* : key [ S* ',' S* key]*
* ;
*/
var tokenStream = this._tokenStream,
token,
key,
keyList = [];
//must be least one key
keyList.push(this._key());
this._readWhitespace();
while(tokenStream.match(Tokens.COMMA)){
this._readWhitespace();
keyList.push(this._key());
this._readWhitespace();
}
return keyList;
},
_key: function(){
/*
* There is a restriction that IDENT can be only "from" or "to".
*
* key
* : PERCENTAGE
* | IDENT
* ;
*/
var tokenStream = this._tokenStream,
token;
if (tokenStream.match(Tokens.PERCENTAGE)){
return SyntaxUnit.fromToken(tokenStream.token());
} else if (tokenStream.match(Tokens.IDENT)){
token = tokenStream.token();
if (/from|to/i.test(token.value)){
return SyntaxUnit.fromToken(token);
}
tokenStream.unget();
}
//if it gets here, there wasn't a valid token, so time to explode
this._unexpectedToken(tokenStream.LT(1));
},
//-----------------------------------------------------------------
// Helper methods
//-----------------------------------------------------------------
/**
* Not part of CSS grammar, but useful for skipping over
* combination of white space and HTML-style comments.
* @return {void}
* @method _skipCruft
* @private
*/
_skipCruft: function(){
while(this._tokenStream.match([Tokens.S, Tokens.CDO, Tokens.CDC])){
//noop
}
},
/**
* Not part of CSS grammar, but this pattern occurs frequently
* in the official CSS grammar. Split out here to eliminate
* duplicate code.
* @param {Boolean} checkStart Indicates if the rule should check
* for the left brace at the beginning.
* @param {Boolean} readMargins Indicates if the rule should check
* for margin patterns.
* @return {void}
* @method _readDeclarations
* @private
*/
_readDeclarations: function(checkStart, readMargins){
/*
* Reads the pattern
* S* '{' S* declaration [ ';' S* declaration ]* '}' S*
* or
* S* '{' S* [ declaration | margin ]? [ ';' S* [ declaration | margin ]? ]* '}' S*
* Note that this is how it is described in CSS3 Paged Media, but is actually incorrect.
* A semicolon is only necessary following a delcaration is there's another declaration
* or margin afterwards.
*/
var tokenStream = this._tokenStream,
tt;
this._readWhitespace();
if (checkStart){
tokenStream.mustMatch(Tokens.LBRACE);
}
this._readWhitespace();
try {
while(true){
if (tokenStream.match(Tokens.SEMICOLON) || (readMargins && this._margin())){
//noop
} else if (this._declaration()){
if (!tokenStream.match(Tokens.SEMICOLON)){
break;
}
} else {
break;
}
//if ((!this._margin() && !this._declaration()) || !tokenStream.match(Tokens.SEMICOLON)){
// break;
//}
this._readWhitespace();
}
tokenStream.mustMatch(Tokens.RBRACE);
this._readWhitespace();
} catch (ex) {
if (ex instanceof SyntaxError && !this.options.strict){
//fire error event
this.fire({
type: "error",
error: ex,
message: ex.message,
line: ex.line,
col: ex.col
});
//see if there's another declaration
tt = tokenStream.advance([Tokens.SEMICOLON, Tokens.RBRACE]);
if (tt == Tokens.SEMICOLON){
//if there's a semicolon, then there might be another declaration
this._readDeclarations(false, readMargins);
} else if (tt != Tokens.RBRACE){
//if there's a right brace, the rule is finished so don't do anything
//otherwise, rethrow the error because it wasn't handled properly
throw ex;
}
} else {
//not a syntax error, rethrow it
throw ex;
}
}
},
/**
* In some cases, you can end up with two white space tokens in a
* row. Instead of making a change in every function that looks for
* white space, this function is used to match as much white space
* as necessary.
* @method _readWhitespace
* @return {String} The white space if found, empty string if not.
* @private
*/
_readWhitespace: function(){
var tokenStream = this._tokenStream,
ws = "";
while(tokenStream.match(Tokens.S)){
ws += tokenStream.token().value;
}
return ws;
},
/**
* Throws an error when an unexpected token is found.
* @param {Object} token The token that was found.
* @method _unexpectedToken
* @return {void}
* @private
*/
_unexpectedToken: function(token){
throw new SyntaxError("Unexpected token '" + token.value + "' at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
},
/**
* Helper method used for parsing subparts of a style sheet.
* @return {void}
* @method _verifyEnd
* @private
*/
_verifyEnd: function(){
if (this._tokenStream.LA(1) != Tokens.EOF){
this._unexpectedToken(this._tokenStream.LT(1));
}
},
//-----------------------------------------------------------------
// Validation methods
//-----------------------------------------------------------------
_validateProperty: function(property, value){
Validation.validate(property, value);
},
//-----------------------------------------------------------------
// Parsing methods
//-----------------------------------------------------------------
parse: function(input){
this._tokenStream = new TokenStream(input, Tokens);
this._stylesheet();
},
parseStyleSheet: function(input){
//just passthrough
return this.parse(input);
},
parseMediaQuery: function(input){
this._tokenStream = new TokenStream(input, Tokens);
var result = this._media_query();
//if there's anything more, then it's an invalid selector
this._verifyEnd();
//otherwise return result
return result;
},
/**
* Parses a property value (everything after the semicolon).
* @return {parserlib.css.PropertyValue} The property value.
* @throws parserlib.util.SyntaxError If an unexpected token is found.
* @method parserPropertyValue
*/
parsePropertyValue: function(input){
this._tokenStream = new TokenStream(input, Tokens);
this._readWhitespace();
var result = this._expr();
//okay to have a trailing white space
this._readWhitespace();
//if there's anything more, then it's an invalid selector
this._verifyEnd();
//otherwise return result
return result;
},
/**
* Parses a complete CSS rule, including selectors and
* properties.
* @param {String} input The text to parser.
* @return {Boolean} True if the parse completed successfully, false if not.
* @method parseRule
*/
parseRule: function(input){
this._tokenStream = new TokenStream(input, Tokens);
//skip any leading white space
this._readWhitespace();
var result = this._ruleset();
//skip any trailing white space
this._readWhitespace();
//if there's anything more, then it's an invalid selector
this._verifyEnd();
//otherwise return result
return result;
},
/**
* Parses a single CSS selector (no comma)
* @param {String} input The text to parse as a CSS selector.
* @return {Selector} An object representing the selector.
* @throws parserlib.util.SyntaxError If an unexpected token is found.
* @method parseSelector
*/
parseSelector: function(input){
this._tokenStream = new TokenStream(input, Tokens);
//skip any leading white space
this._readWhitespace();
var result = this._selector();
//skip any trailing white space
this._readWhitespace();
//if there's anything more, then it's an invalid selector
this._verifyEnd();
//otherwise return result
return result;
},
/**
* Parses an HTML style attribute: a set of CSS declarations
* separated by semicolons.
* @param {String} input The text to parse as a style attribute
* @return {void}
* @method parseStyleAttribute
*/
parseStyleAttribute: function(input){
input += "}"; // for error recovery in _readDeclarations()
this._tokenStream = new TokenStream(input, Tokens);
this._readDeclarations();
}
};
//copy over onto prototype
for (prop in additions){
if (additions.hasOwnProperty(prop)){
proto[prop] = additions[prop];
}
}
return proto;
}();
/*
nth
: S* [ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]? |
['-'|'+']? INTEGER | {O}{D}{D} | {E}{V}{E}{N} ] S*
;
*/
/*global Validation, ValidationTypes, ValidationError*/
var Properties = {
//A
"alignment-adjust" : "auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | <percentage> | <length>",
"alignment-baseline" : "baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
"animation" : 1,
"animation-delay" : { multi: "<time>", comma: true },
"animation-direction" : { multi: "normal | alternate", comma: true },
"animation-duration" : { multi: "<time>", comma: true },
"animation-iteration-count" : { multi: "<number> | infinite", comma: true },
"animation-name" : { multi: "none | <ident>", comma: true },
"animation-play-state" : { multi: "running | paused", comma: true },
"animation-timing-function" : 1,
//vendor prefixed
"-moz-animation-delay" : { multi: "<time>", comma: true },
"-moz-animation-direction" : { multi: "normal | alternate", comma: true },
"-moz-animation-duration" : { multi: "<time>", comma: true },
"-moz-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
"-moz-animation-name" : { multi: "none | <ident>", comma: true },
"-moz-animation-play-state" : { multi: "running | paused", comma: true },
"-ms-animation-delay" : { multi: "<time>", comma: true },
"-ms-animation-direction" : { multi: "normal | alternate", comma: true },
"-ms-animation-duration" : { multi: "<time>", comma: true },
"-ms-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
"-ms-animation-name" : { multi: "none | <ident>", comma: true },
"-ms-animation-play-state" : { multi: "running | paused", comma: true },
"-webkit-animation-delay" : { multi: "<time>", comma: true },
"-webkit-animation-direction" : { multi: "normal | alternate", comma: true },
"-webkit-animation-duration" : { multi: "<time>", comma: true },
"-webkit-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
"-webkit-animation-name" : { multi: "none | <ident>", comma: true },
"-webkit-animation-play-state" : { multi: "running | paused", comma: true },
"-o-animation-delay" : { multi: "<time>", comma: true },
"-o-animation-direction" : { multi: "normal | alternate", comma: true },
"-o-animation-duration" : { multi: "<time>", comma: true },
"-o-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
"-o-animation-name" : { multi: "none | <ident>", comma: true },
"-o-animation-play-state" : { multi: "running | paused", comma: true },
"appearance" : "icon | window | desktop | workspace | document | tooltip | dialog | button | push-button | hyperlink | radio-button | checkbox | menu-item | tab | menu | menubar | pull-down-menu | pop-up-menu | list-menu | radio-group | checkbox-group | outline-tree | range | field | combo-box | signature | password | normal | inherit",
"azimuth" : function (expression) {
var simple = "<angle> | leftwards | rightwards | inherit",
direction = "left-side | far-left | left | center-left | center | center-right | right | far-right | right-side",
behind = false,
valid = false,
part;
if (!ValidationTypes.isAny(expression, simple)) {
if (ValidationTypes.isAny(expression, "behind")) {
behind = true;
valid = true;
}
if (ValidationTypes.isAny(expression, direction)) {
valid = true;
if (!behind) {
ValidationTypes.isAny(expression, "behind");
}
}
}
if (expression.hasNext()) {
part = expression.next();
if (valid) {
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (<'azimuth'>) but found '" + part + "'.", part.line, part.col);
}
}
},
//B
"backface-visibility" : "visible | hidden",
"background" : 1,
"background-attachment" : { multi: "<attachment>", comma: true },
"background-clip" : { multi: "<box>", comma: true },
"background-color" : "<color> | inherit",
"background-image" : { multi: "<bg-image>", comma: true },
"background-origin" : { multi: "<box>", comma: true },
"background-position" : { multi: "<bg-position>", comma: true },
"background-repeat" : { multi: "<repeat-style>" },
"background-size" : { multi: "<bg-size>", comma: true },
"baseline-shift" : "baseline | sub | super | <percentage> | <length>",
"behavior" : 1,
"binding" : 1,
"bleed" : "<length>",
"bookmark-label" : "<content> | <attr> | <string>",
"bookmark-level" : "none | <integer>",
"bookmark-state" : "open | closed",
"bookmark-target" : "none | <uri> | <attr>",
"border" : "<border-width> || <border-style> || <color>",
"border-bottom" : "<border-width> || <border-style> || <color>",
"border-bottom-color" : "<color>",
"border-bottom-left-radius" : "<x-one-radius>",
"border-bottom-right-radius" : "<x-one-radius>",
"border-bottom-style" : "<border-style>",
"border-bottom-width" : "<border-width>",
"border-collapse" : "collapse | separate | inherit",
"border-color" : { multi: "<color> | inherit", max: 4 },
"border-image" : 1,
"border-image-outset" : { multi: "<length> | <number>", max: 4 },
"border-image-repeat" : { multi: "stretch | repeat | round", max: 2 },
"border-image-slice" : function(expression) {
var valid = false,
numeric = "<number> | <percentage>",
fill = false,
count = 0,
max = 4,
part;
if (ValidationTypes.isAny(expression, "fill")) {
fill = true;
valid = true;
}
while (expression.hasNext() && count < max) {
valid = ValidationTypes.isAny(expression, numeric);
if (!valid) {
break;
}
count++;
}
if (!fill) {
ValidationTypes.isAny(expression, "fill");
} else {
valid = true;
}
if (expression.hasNext()) {
part = expression.next();
if (valid) {
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected ([<number> | <percentage>]{1,4} && fill?) but found '" + part + "'.", part.line, part.col);
}
}
},
"border-image-source" : "<image> | none",
"border-image-width" : { multi: "<length> | <percentage> | <number> | auto", max: 4 },
"border-left" : "<border-width> || <border-style> || <color>",
"border-left-color" : "<color> | inherit",
"border-left-style" : "<border-style>",
"border-left-width" : "<border-width>",
"border-radius" : function(expression) {
var valid = false,
numeric = "<length> | <percentage>",
slash = false,
fill = false,
count = 0,
max = 8,
part;
while (expression.hasNext() && count < max) {
valid = ValidationTypes.isAny(expression, numeric);
if (!valid) {
if (expression.peek() == "/" && count > 1 && !slash) {
slash = true;
max = count + 5;
expression.next();
} else {
break;
}
}
count++;
}
if (expression.hasNext()) {
part = expression.next();
if (valid) {
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (<'border-radius'>) but found '" + part + "'.", part.line, part.col);
}
}
},
"border-right" : "<border-width> || <border-style> || <color>",
"border-right-color" : "<color> | inherit",
"border-right-style" : "<border-style>",
"border-right-width" : "<border-width>",
"border-spacing" : { multi: "<length> | inherit", max: 2 },
"border-style" : { multi: "<border-style>", max: 4 },
"border-top" : "<border-width> || <border-style> || <color>",
"border-top-color" : "<color> | inherit",
"border-top-left-radius" : "<x-one-radius>",
"border-top-right-radius" : "<x-one-radius>",
"border-top-style" : "<border-style>",
"border-top-width" : "<border-width>",
"border-width" : { multi: "<border-width>", max: 4 },
"bottom" : "<margin-width> | inherit",
"box-align" : "start | end | center | baseline | stretch", //http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/
"box-decoration-break" : "slice |clone",
"box-direction" : "normal | reverse | inherit",
"box-flex" : "<number>",
"box-flex-group" : "<integer>",
"box-lines" : "single | multiple",
"box-ordinal-group" : "<integer>",
"box-orient" : "horizontal | vertical | inline-axis | block-axis | inherit",
"box-pack" : "start | end | center | justify",
"box-shadow" : function (expression) {
var result = false,
part;
if (!ValidationTypes.isAny(expression, "none")) {
Validation.multiProperty("<shadow>", expression, true, Infinity);
} else {
if (expression.hasNext()) {
part = expression.next();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
}
}
},
"box-sizing" : "content-box | border-box | inherit",
"break-after" : "auto | always | avoid | left | right | page | column | avoid-page | avoid-column",
"break-before" : "auto | always | avoid | left | right | page | column | avoid-page | avoid-column",
"break-inside" : "auto | avoid | avoid-page | avoid-column",
//C
"caption-side" : "top | bottom | inherit",
"clear" : "none | right | left | both | inherit",
"clip" : 1,
"color" : "<color> | inherit",
"color-profile" : 1,
"column-count" : "<integer> | auto", //http://www.w3.org/TR/css3-multicol/
"column-fill" : "auto | balance",
"column-gap" : "<length> | normal",
"column-rule" : "<border-width> || <border-style> || <color>",
"column-rule-color" : "<color>",
"column-rule-style" : "<border-style>",
"column-rule-width" : "<border-width>",
"column-span" : "none | all",
"column-width" : "<length> | auto",
"columns" : 1,
"content" : 1,
"counter-increment" : 1,
"counter-reset" : 1,
"crop" : "<shape> | auto",
"cue" : "cue-after | cue-before | inherit",
"cue-after" : 1,
"cue-before" : 1,
"cursor" : 1,
//D
"direction" : "ltr | rtl | inherit",
"display" : "inline | block | list-item | inline-block | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | box | inline-box | grid | inline-grid | none | inherit | -webkit-box",
"dominant-baseline" : 1,
"drop-initial-after-adjust" : "central | middle | after-edge | text-after-edge | ideographic | alphabetic | mathematical | <percentage> | <length>",
"drop-initial-after-align" : "baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
"drop-initial-before-adjust" : "before-edge | text-before-edge | central | middle | hanging | mathematical | <percentage> | <length>",
"drop-initial-before-align" : "caps-height | baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
"drop-initial-size" : "auto | line | <length> | <percentage>",
"drop-initial-value" : "initial | <integer>",
//E
"elevation" : "<angle> | below | level | above | higher | lower | inherit",
"empty-cells" : "show | hide | inherit",
//F
"filter" : 1,
"fit" : "fill | hidden | meet | slice",
"fit-position" : 1,
"float" : "left | right | none | inherit",
"float-offset" : 1,
"font" : 1,
"font-family" : 1,
"font-size" : "<absolute-size> | <relative-size> | <length> | <percentage> | inherit",
"font-size-adjust" : "<number> | none | inherit",
"font-stretch" : "normal | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | inherit",
"font-style" : "normal | italic | oblique | inherit",
"font-variant" : "normal | small-caps | inherit",
"font-weight" : "normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit",
//G
"grid-cell-stacking" : "columns | rows | layer",
"grid-column" : 1,
"grid-columns" : 1,
"grid-column-align" : "start | end | center | stretch",
"grid-column-sizing" : 1,
"grid-column-span" : "<integer>",
"grid-flow" : "none | rows | columns",
"grid-layer" : "<integer>",
"grid-row" : 1,
"grid-rows" : 1,
"grid-row-align" : "start | end | center | stretch",
"grid-row-span" : "<integer>",
"grid-row-sizing" : 1,
//H
"hanging-punctuation" : 1,
"height" : "<margin-width> | inherit",
"hyphenate-after" : "<integer> | auto",
"hyphenate-before" : "<integer> | auto",
"hyphenate-character" : "<string> | auto",
"hyphenate-lines" : "no-limit | <integer>",
"hyphenate-resource" : 1,
"hyphens" : "none | manual | auto",
//I
"icon" : 1,
"image-orientation" : "angle | auto",
"image-rendering" : 1,
"image-resolution" : 1,
"inline-box-align" : "initial | last | <integer>",
//L
"left" : "<margin-width> | inherit",
"letter-spacing" : "<length> | normal | inherit",
"line-height" : "<number> | <length> | <percentage> | normal | inherit",
"line-break" : "auto | loose | normal | strict",
"line-stacking" : 1,
"line-stacking-ruby" : "exclude-ruby | include-ruby",
"line-stacking-shift" : "consider-shifts | disregard-shifts",
"line-stacking-strategy" : "inline-line-height | block-line-height | max-height | grid-height",
"list-style" : 1,
"list-style-image" : "<uri> | none | inherit",
"list-style-position" : "inside | outside | inherit",
"list-style-type" : "disc | circle | square | decimal | decimal-leading-zero | lower-roman | upper-roman | lower-greek | lower-latin | upper-latin | armenian | georgian | lower-alpha | upper-alpha | none | inherit",
//M
"margin" : { multi: "<margin-width> | inherit", max: 4 },
"margin-bottom" : "<margin-width> | inherit",
"margin-left" : "<margin-width> | inherit",
"margin-right" : "<margin-width> | inherit",
"margin-top" : "<margin-width> | inherit",
"mark" : 1,
"mark-after" : 1,
"mark-before" : 1,
"marks" : 1,
"marquee-direction" : 1,
"marquee-play-count" : 1,
"marquee-speed" : 1,
"marquee-style" : 1,
"max-height" : "<length> | <percentage> | none | inherit",
"max-width" : "<length> | <percentage> | none | inherit",
"min-height" : "<length> | <percentage> | inherit",
"min-width" : "<length> | <percentage> | inherit",
"move-to" : 1,
//N
"nav-down" : 1,
"nav-index" : 1,
"nav-left" : 1,
"nav-right" : 1,
"nav-up" : 1,
//O
"opacity" : "<number> | inherit",
"orphans" : "<integer> | inherit",
"outline" : 1,
"outline-color" : "<color> | invert | inherit",
"outline-offset" : 1,
"outline-style" : "<border-style> | inherit",
"outline-width" : "<border-width> | inherit",
"overflow" : "visible | hidden | scroll | auto | inherit",
"overflow-style" : 1,
"overflow-x" : 1,
"overflow-y" : 1,
//P
"padding" : { multi: "<padding-width> | inherit", max: 4 },
"padding-bottom" : "<padding-width> | inherit",
"padding-left" : "<padding-width> | inherit",
"padding-right" : "<padding-width> | inherit",
"padding-top" : "<padding-width> | inherit",
"page" : 1,
"page-break-after" : "auto | always | avoid | left | right | inherit",
"page-break-before" : "auto | always | avoid | left | right | inherit",
"page-break-inside" : "auto | avoid | inherit",
"page-policy" : 1,
"pause" : 1,
"pause-after" : 1,
"pause-before" : 1,
"perspective" : 1,
"perspective-origin" : 1,
"phonemes" : 1,
"pitch" : 1,
"pitch-range" : 1,
"play-during" : 1,
"pointer-events" : "auto | none | visiblePainted | visibleFill | visibleStroke | visible | painted | fill | stroke | all | inherit",
"position" : "static | relative | absolute | fixed | inherit",
"presentation-level" : 1,
"punctuation-trim" : 1,
//Q
"quotes" : 1,
//R
"rendering-intent" : 1,
"resize" : 1,
"rest" : 1,
"rest-after" : 1,
"rest-before" : 1,
"richness" : 1,
"right" : "<margin-width> | inherit",
"rotation" : 1,
"rotation-point" : 1,
"ruby-align" : 1,
"ruby-overhang" : 1,
"ruby-position" : 1,
"ruby-span" : 1,
//S
"size" : 1,
"speak" : "normal | none | spell-out | inherit",
"speak-header" : "once | always | inherit",
"speak-numeral" : "digits | continuous | inherit",
"speak-punctuation" : "code | none | inherit",
"speech-rate" : 1,
"src" : 1,
"stress" : 1,
"string-set" : 1,
"table-layout" : "auto | fixed | inherit",
"tab-size" : "<integer> | <length>",
"target" : 1,
"target-name" : 1,
"target-new" : 1,
"target-position" : 1,
"text-align" : "left | right | center | justify | inherit" ,
"text-align-last" : 1,
"text-decoration" : 1,
"text-emphasis" : 1,
"text-height" : 1,
"text-indent" : "<length> | <percentage> | inherit",
"text-justify" : "auto | none | inter-word | inter-ideograph | inter-cluster | distribute | kashida",
"text-outline" : 1,
"text-overflow" : 1,
"text-rendering" : "auto | optimizeSpeed | optimizeLegibility | geometricPrecision | inherit",
"text-shadow" : 1,
"text-transform" : "capitalize | uppercase | lowercase | none | inherit",
"text-wrap" : "normal | none | avoid",
"top" : "<margin-width> | inherit",
"transform" : 1,
"transform-origin" : 1,
"transform-style" : 1,
"transition" : 1,
"transition-delay" : 1,
"transition-duration" : 1,
"transition-property" : 1,
"transition-timing-function" : 1,
//U
"unicode-bidi" : "normal | embed | bidi-override | inherit",
"user-modify" : "read-only | read-write | write-only | inherit",
"user-select" : "none | text | toggle | element | elements | all | inherit",
//V
"vertical-align" : "<percentage> | <length> | baseline | sub | super | top | text-top | middle | bottom | text-bottom | inherit",
"visibility" : "visible | hidden | collapse | inherit",
"voice-balance" : 1,
"voice-duration" : 1,
"voice-family" : 1,
"voice-pitch" : 1,
"voice-pitch-range" : 1,
"voice-rate" : 1,
"voice-stress" : 1,
"voice-volume" : 1,
"volume" : 1,
//W
"white-space" : "normal | pre | nowrap | pre-wrap | pre-line | inherit",
"white-space-collapse" : 1,
"widows" : "<integer> | inherit",
"width" : "<length> | <percentage> | auto | inherit" ,
"word-break" : "normal | keep-all | break-all",
"word-spacing" : "<length> | normal | inherit",
"word-wrap" : 1,
//Z
"z-index" : "<integer> | auto | inherit",
"zoom" : "<number> | <percentage> | normal"
};
/*global SyntaxUnit, Parser*/
/**
* Represents a selector combinator (whitespace, +, >).
* @namespace parserlib.css
* @class PropertyName
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {String} text The text representation of the unit.
* @param {String} hack The type of IE hack applied ("*", "_", or null).
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function PropertyName(text, hack, line, col){
SyntaxUnit.call(this, text, line, col, Parser.PROPERTY_NAME_TYPE);
/**
* The type of IE hack applied ("*", "_", or null).
* @type String
* @property hack
*/
this.hack = hack;
}
PropertyName.prototype = new SyntaxUnit();
PropertyName.prototype.constructor = PropertyName;
PropertyName.prototype.toString = function(){
return (this.hack ? this.hack : "") + this.text;
};
/*global SyntaxUnit, Parser*/
/**
* Represents a single part of a CSS property value, meaning that it represents
* just everything single part between ":" and ";". If there are multiple values
* separated by commas, this type represents just one of the values.
* @param {String[]} parts An array of value parts making up this value.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
* @namespace parserlib.css
* @class PropertyValue
* @extends parserlib.util.SyntaxUnit
* @constructor
*/
function PropertyValue(parts, line, col){
SyntaxUnit.call(this, parts.join(" "), line, col, Parser.PROPERTY_VALUE_TYPE);
/**
* The parts that make up the selector.
* @type Array
* @property parts
*/
this.parts = parts;
}
PropertyValue.prototype = new SyntaxUnit();
PropertyValue.prototype.constructor = PropertyValue;
/*global SyntaxUnit, Parser*/
/**
* A utility class that allows for easy iteration over the various parts of a
* property value.
* @param {parserlib.css.PropertyValue} value The property value to iterate over.
* @namespace parserlib.css
* @class PropertyValueIterator
* @constructor
*/
function PropertyValueIterator(value){
/**
* Iterator value
* @type int
* @property _i
* @private
*/
this._i = 0;
/**
* The parts that make up the value.
* @type Array
* @property _parts
* @private
*/
this._parts = value.parts;
/**
* Keeps track of bookmarks along the way.
* @type Array
* @property _marks
* @private
*/
this._marks = [];
/**
* Holds the original property value.
* @type parserlib.css.PropertyValue
* @property value
*/
this.value = value;
}
/**
* Returns the total number of parts in the value.
* @return {int} The total number of parts in the value.
* @method count
*/
PropertyValueIterator.prototype.count = function(){
return this._parts.length;
};
/**
* Indicates if the iterator is positioned at the first item.
* @return {Boolean} True if positioned at first item, false if not.
* @method isFirst
*/
PropertyValueIterator.prototype.isFirst = function(){
return this._i === 0;
};
/**
* Indicates if there are more parts of the property value.
* @return {Boolean} True if there are more parts, false if not.
* @method hasNext
*/
PropertyValueIterator.prototype.hasNext = function(){
return (this._i < this._parts.length);
};
/**
* Marks the current spot in the iteration so it can be restored to
* later on.
* @return {void}
* @method mark
*/
PropertyValueIterator.prototype.mark = function(){
this._marks.push(this._i);
};
/**
* Returns the next part of the property value or null if there is no next
* part. Does not move the internal counter forward.
* @return {parserlib.css.PropertyValuePart} The next part of the property value or null if there is no next
* part.
* @method peek
*/
PropertyValueIterator.prototype.peek = function(count){
return this.hasNext() ? this._parts[this._i + (count || 0)] : null;
};
/**
* Returns the next part of the property value or null if there is no next
* part.
* @return {parserlib.css.PropertyValuePart} The next part of the property value or null if there is no next
* part.
* @method next
*/
PropertyValueIterator.prototype.next = function(){
return this.hasNext() ? this._parts[this._i++] : null;
};
/**
* Returns the previous part of the property value or null if there is no
* previous part.
* @return {parserlib.css.PropertyValuePart} The previous part of the
* property value or null if there is no next part.
* @method previous
*/
PropertyValueIterator.prototype.previous = function(){
return this._i > 0 ? this._parts[--this._i] : null;
};
/**
* Restores the last saved bookmark.
* @return {void}
* @method restore
*/
PropertyValueIterator.prototype.restore = function(){
if (this._marks.length){
this._i = this._marks.pop();
}
};
/*global SyntaxUnit, Parser, Colors*/
/**
* Represents a single part of a CSS property value, meaning that it represents
* just one part of the data between ":" and ";".
* @param {String} text The text representation of the unit.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
* @namespace parserlib.css
* @class PropertyValuePart
* @extends parserlib.util.SyntaxUnit
* @constructor
*/
function PropertyValuePart(text, line, col){
SyntaxUnit.call(this, text, line, col, Parser.PROPERTY_VALUE_PART_TYPE);
/**
* Indicates the type of value unit.
* @type String
* @property type
*/
this.type = "unknown";
//figure out what type of data it is
var temp;
//it is a measurement?
if (/^([+\-]?[\d\.]+)([a-z]+)$/i.test(text)){ //dimension
this.type = "dimension";
this.value = +RegExp.$1;
this.units = RegExp.$2;
//try to narrow down
switch(this.units.toLowerCase()){
case "em":
case "rem":
case "ex":
case "px":
case "cm":
case "mm":
case "in":
case "pt":
case "pc":
case "ch":
this.type = "length";
break;
case "deg":
case "rad":
case "grad":
this.type = "angle";
break;
case "ms":
case "s":
this.type = "time";
break;
case "hz":
case "khz":
this.type = "frequency";
break;
case "dpi":
case "dpcm":
this.type = "resolution";
break;
//default
}
} else if (/^([+\-]?[\d\.]+)%$/i.test(text)){ //percentage
this.type = "percentage";
this.value = +RegExp.$1;
} else if (/^([+\-]?[\d\.]+)%$/i.test(text)){ //percentage
this.type = "percentage";
this.value = +RegExp.$1;
} else if (/^([+\-]?\d+)$/i.test(text)){ //integer
this.type = "integer";
this.value = +RegExp.$1;
} else if (/^([+\-]?[\d\.]+)$/i.test(text)){ //number
this.type = "number";
this.value = +RegExp.$1;
} else if (/^#([a-f0-9]{3,6})/i.test(text)){ //hexcolor
this.type = "color";
temp = RegExp.$1;
if (temp.length == 3){
this.red = parseInt(temp.charAt(0)+temp.charAt(0),16);
this.green = parseInt(temp.charAt(1)+temp.charAt(1),16);
this.blue = parseInt(temp.charAt(2)+temp.charAt(2),16);
} else {
this.red = parseInt(temp.substring(0,2),16);
this.green = parseInt(temp.substring(2,4),16);
this.blue = parseInt(temp.substring(4,6),16);
}
} else if (/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i.test(text)){ //rgb() color with absolute numbers
this.type = "color";
this.red = +RegExp.$1;
this.green = +RegExp.$2;
this.blue = +RegExp.$3;
} else if (/^rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)){ //rgb() color with percentages
this.type = "color";
this.red = +RegExp.$1 * 255 / 100;
this.green = +RegExp.$2 * 255 / 100;
this.blue = +RegExp.$3 * 255 / 100;
} else if (/^rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //rgba() color with absolute numbers
this.type = "color";
this.red = +RegExp.$1;
this.green = +RegExp.$2;
this.blue = +RegExp.$3;
this.alpha = +RegExp.$4;
} else if (/^rgba\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //rgba() color with percentages
this.type = "color";
this.red = +RegExp.$1 * 255 / 100;
this.green = +RegExp.$2 * 255 / 100;
this.blue = +RegExp.$3 * 255 / 100;
this.alpha = +RegExp.$4;
} else if (/^hsl\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)){ //hsl()
this.type = "color";
this.hue = +RegExp.$1;
this.saturation = +RegExp.$2 / 100;
this.lightness = +RegExp.$3 / 100;
} else if (/^hsla\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //hsla() color with percentages
this.type = "color";
this.hue = +RegExp.$1;
this.saturation = +RegExp.$2 / 100;
this.lightness = +RegExp.$3 / 100;
this.alpha = +RegExp.$4;
} else if (/^url\(["']?([^\)"']+)["']?\)/i.test(text)){ //URI
this.type = "uri";
this.uri = RegExp.$1;
} else if (/^([^\(]+)\(/i.test(text)){
this.type = "function";
this.name = RegExp.$1;
this.value = text;
} else if (/^["'][^"']*["']/.test(text)){ //string
this.type = "string";
this.value = eval(text);
} else if (Colors[text.toLowerCase()]){ //named color
this.type = "color";
temp = Colors[text.toLowerCase()].substring(1);
this.red = parseInt(temp.substring(0,2),16);
this.green = parseInt(temp.substring(2,4),16);
this.blue = parseInt(temp.substring(4,6),16);
} else if (/^[\,\/]$/.test(text)){
this.type = "operator";
this.value = text;
} else if (/^[a-z\-\u0080-\uFFFF][a-z0-9\-\u0080-\uFFFF]*$/i.test(text)){
this.type = "identifier";
this.value = text;
}
}
PropertyValuePart.prototype = new SyntaxUnit();
PropertyValuePart.prototype.constructor = PropertyValuePart;
/**
* Create a new syntax unit based solely on the given token.
* Convenience method for creating a new syntax unit when
* it represents a single token instead of multiple.
* @param {Object} token The token object to represent.
* @return {parserlib.css.PropertyValuePart} The object representing the token.
* @static
* @method fromToken
*/
PropertyValuePart.fromToken = function(token){
return new PropertyValuePart(token.value, token.startLine, token.startCol);
};
var Pseudos = {
":first-letter": 1,
":first-line": 1,
":before": 1,
":after": 1
};
Pseudos.ELEMENT = 1;
Pseudos.CLASS = 2;
Pseudos.isElement = function(pseudo){
return pseudo.indexOf("::") === 0 || Pseudos[pseudo.toLowerCase()] == Pseudos.ELEMENT;
};
/*global SyntaxUnit, Parser, Specificity*/
/**
* Represents an entire single selector, including all parts but not
* including multiple selectors (those separated by commas).
* @namespace parserlib.css
* @class Selector
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {Array} parts Array of selectors parts making up this selector.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function Selector(parts, line, col){
SyntaxUnit.call(this, parts.join(" "), line, col, Parser.SELECTOR_TYPE);
/**
* The parts that make up the selector.
* @type Array
* @property parts
*/
this.parts = parts;
/**
* The specificity of the selector.
* @type parserlib.css.Specificity
* @property specificity
*/
this.specificity = Specificity.calculate(this);
}
Selector.prototype = new SyntaxUnit();
Selector.prototype.constructor = Selector;
/*global SyntaxUnit, Parser*/
/**
* Represents a single part of a selector string, meaning a single set of
* element name and modifiers. This does not include combinators such as
* spaces, +, >, etc.
* @namespace parserlib.css
* @class SelectorPart
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {String} elementName The element name in the selector or null
* if there is no element name.
* @param {Array} modifiers Array of individual modifiers for the element.
* May be empty if there are none.
* @param {String} text The text representation of the unit.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function SelectorPart(elementName, modifiers, text, line, col){
SyntaxUnit.call(this, text, line, col, Parser.SELECTOR_PART_TYPE);
/**
* The tag name of the element to which this part
* of the selector affects.
* @type String
* @property elementName
*/
this.elementName = elementName;
/**
* The parts that come after the element name, such as class names, IDs,
* pseudo classes/elements, etc.
* @type Array
* @property modifiers
*/
this.modifiers = modifiers;
}
SelectorPart.prototype = new SyntaxUnit();
SelectorPart.prototype.constructor = SelectorPart;
/*global SyntaxUnit, Parser*/
/**
* Represents a selector modifier string, meaning a class name, element name,
* element ID, pseudo rule, etc.
* @namespace parserlib.css
* @class SelectorSubPart
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {String} text The text representation of the unit.
* @param {String} type The type of selector modifier.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function SelectorSubPart(text, type, line, col){
SyntaxUnit.call(this, text, line, col, Parser.SELECTOR_SUB_PART_TYPE);
/**
* The type of modifier.
* @type String
* @property type
*/
this.type = type;
/**
* Some subparts have arguments, this represents them.
* @type Array
* @property args
*/
this.args = [];
}
SelectorSubPart.prototype = new SyntaxUnit();
SelectorSubPart.prototype.constructor = SelectorSubPart;
/*global Pseudos, SelectorPart*/
/**
* Represents a selector's specificity.
* @namespace parserlib.css
* @class Specificity
* @constructor
* @param {int} a Should be 1 for inline styles, zero for stylesheet styles
* @param {int} b Number of ID selectors
* @param {int} c Number of classes and pseudo classes
* @param {int} d Number of element names and pseudo elements
*/
function Specificity(a, b, c, d){
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
Specificity.prototype = {
constructor: Specificity,
/**
* Compare this specificity to another.
* @param {Specificity} other The other specificity to compare to.
* @return {int} -1 if the other specificity is larger, 1 if smaller, 0 if equal.
* @method compare
*/
compare: function(other){
var comps = ["a", "b", "c", "d"],
i, len;
for (i=0, len=comps.length; i < len; i++){
if (this[comps[i]] < other[comps[i]]){
return -1;
} else if (this[comps[i]] > other[comps[i]]){
return 1;
}
}
return 0;
},
/**
* Creates a numeric value for the specificity.
* @return {int} The numeric value for the specificity.
* @method valueOf
*/
valueOf: function(){
return (this.a * 1000) + (this.b * 100) + (this.c * 10) + this.d;
},
/**
* Returns a string representation for specificity.
* @return {String} The string representation of specificity.
* @method toString
*/
toString: function(){
return this.a + "," + this.b + "," + this.c + "," + this.d;
}
};
/**
* Calculates the specificity of the given selector.
* @param {parserlib.css.Selector} The selector to calculate specificity for.
* @return {parserlib.css.Specificity} The specificity of the selector.
* @static
* @method calculate
*/
Specificity.calculate = function(selector){
var i, len,
part,
b=0, c=0, d=0;
function updateValues(part){
var i, j, len, num,
elementName = part.elementName ? part.elementName.text : "",
modifier;
if (elementName && elementName.charAt(elementName.length-1) != "*") {
d++;
}
for (i=0, len=part.modifiers.length; i < len; i++){
modifier = part.modifiers[i];
switch(modifier.type){
case "class":
case "attribute":
c++;
break;
case "id":
b++;
break;
case "pseudo":
if (Pseudos.isElement(modifier.text)){
d++;
} else {
c++;
}
break;
case "not":
for (j=0, num=modifier.args.length; j < num; j++){
updateValues(modifier.args[j]);
}
}
}
}
for (i=0, len=selector.parts.length; i < len; i++){
part = selector.parts[i];
if (part instanceof SelectorPart){
updateValues(part);
}
}
return new Specificity(0, b, c, d);
};
/*global Tokens, TokenStreamBase*/
var h = /^[0-9a-fA-F]$/,
nonascii = /^[\u0080-\uFFFF]$/,
nl = /\n|\r\n|\r|\f/;
//-----------------------------------------------------------------------------
// Helper functions
//-----------------------------------------------------------------------------
function isHexDigit(c){
return c !== null && h.test(c);
}
function isDigit(c){
return c !== null && /\d/.test(c);
}
function isWhitespace(c){
return c !== null && /\s/.test(c);
}
function isNewLine(c){
return c !== null && nl.test(c);
}
function isNameStart(c){
return c !== null && (/[a-z_\u0080-\uFFFF\\]/i.test(c));
}
function isNameChar(c){
return c !== null && (isNameStart(c) || /[0-9\-\\]/.test(c));
}
function isIdentStart(c){
return c !== null && (isNameStart(c) || /\-\\/.test(c));
}
function mix(receiver, supplier){
for (var prop in supplier){
if (supplier.hasOwnProperty(prop)){
receiver[prop] = supplier[prop];
}
}
return receiver;
}
//-----------------------------------------------------------------------------
// CSS Token Stream
//-----------------------------------------------------------------------------
/**
* A token stream that produces CSS tokens.
* @param {String|Reader} input The source of text to tokenize.
* @constructor
* @class TokenStream
* @namespace parserlib.css
*/
function TokenStream(input){
TokenStreamBase.call(this, input, Tokens);
}
TokenStream.prototype = mix(new TokenStreamBase(), {
/**
* Overrides the TokenStreamBase method of the same name
* to produce CSS tokens.
* @param {variant} channel The name of the channel to use
* for the next token.
* @return {Object} A token object representing the next token.
* @method _getToken
* @private
*/
_getToken: function(channel){
var c,
reader = this._reader,
token = null,
startLine = reader.getLine(),
startCol = reader.getCol();
c = reader.read();
while(c){
switch(c){
/*
* Potential tokens:
* - COMMENT
* - SLASH
* - CHAR
*/
case "/":
if(reader.peek() == "*"){
token = this.commentToken(c, startLine, startCol);
} else {
token = this.charToken(c, startLine, startCol);
}
break;
/*
* Potential tokens:
* - DASHMATCH
* - INCLUDES
* - PREFIXMATCH
* - SUFFIXMATCH
* - SUBSTRINGMATCH
* - CHAR
*/
case "|":
case "~":
case "^":
case "$":
case "*":
if(reader.peek() == "="){
token = this.comparisonToken(c, startLine, startCol);
} else {
token = this.charToken(c, startLine, startCol);
}
break;
/*
* Potential tokens:
* - STRING
* - INVALID
*/
case "\"":
case "'":
token = this.stringToken(c, startLine, startCol);
break;
/*
* Potential tokens:
* - HASH
* - CHAR
*/
case "#":
if (isNameChar(reader.peek())){
token = this.hashToken(c, startLine, startCol);
} else {
token = this.charToken(c, startLine, startCol);
}
break;
/*
* Potential tokens:
* - DOT
* - NUMBER
* - DIMENSION
* - PERCENTAGE
*/
case ".":
if (isDigit(reader.peek())){
token = this.numberToken(c, startLine, startCol);
} else {
token = this.charToken(c, startLine, startCol);
}
break;
/*
* Potential tokens:
* - CDC
* - MINUS
* - NUMBER
* - DIMENSION
* - PERCENTAGE
*/
case "-":
if (reader.peek() == "-"){ //could be closing HTML-style comment
token = this.htmlCommentEndToken(c, startLine, startCol);
} else if (isNameStart(reader.peek())){
token = this.identOrFunctionToken(c, startLine, startCol);
} else {
token = this.charToken(c, startLine, startCol);
}
break;
/*
* Potential tokens:
* - IMPORTANT_SYM
* - CHAR
*/
case "!":
token = this.importantToken(c, startLine, startCol);
break;
/*
* Any at-keyword or CHAR
*/
case "@":
token = this.atRuleToken(c, startLine, startCol);
break;
/*
* Potential tokens:
* - NOT
* - CHAR
*/
case ":":
token = this.notToken(c, startLine, startCol);
break;
/*
* Potential tokens:
* - CDO
* - CHAR
*/
case "<":
token = this.htmlCommentStartToken(c, startLine, startCol);
break;
/*
* Potential tokens:
* - UNICODE_RANGE
* - URL
* - CHAR
*/
case "U":
case "u":
if (reader.peek() == "+"){
token = this.unicodeRangeToken(c, startLine, startCol);
break;
}
/* falls through */
default:
/*
* Potential tokens:
* - NUMBER
* - DIMENSION
* - LENGTH
* - FREQ
* - TIME
* - EMS
* - EXS
* - ANGLE
*/
if (isDigit(c)){
token = this.numberToken(c, startLine, startCol);
} else
/*
* Potential tokens:
* - S
*/
if (isWhitespace(c)){
token = this.whitespaceToken(c, startLine, startCol);
} else
/*
* Potential tokens:
* - IDENT
*/
if (isIdentStart(c)){
token = this.identOrFunctionToken(c, startLine, startCol);
} else
/*
* Potential tokens:
* - CHAR
* - PLUS
*/
{
token = this.charToken(c, startLine, startCol);
}
}
//make sure this token is wanted
//TODO: check channel
break;
}
if (!token && c === null){
token = this.createToken(Tokens.EOF,null,startLine,startCol);
}
return token;
},
//-------------------------------------------------------------------------
// Methods to create tokens
//-------------------------------------------------------------------------
/**
* Produces a token based on available data and the current
* reader position information. This method is called by other
* private methods to create tokens and is never called directly.
* @param {int} tt The token type.
* @param {String} value The text value of the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @param {Object} options (Optional) Specifies a channel property
* to indicate that a different channel should be scanned
* and/or a hide property indicating that the token should
* be hidden.
* @return {Object} A token object.
* @method createToken
*/
createToken: function(tt, value, startLine, startCol, options){
var reader = this._reader;
options = options || {};
return {
value: value,
type: tt,
channel: options.channel,
hide: options.hide || false,
startLine: startLine,
startCol: startCol,
endLine: reader.getLine(),
endCol: reader.getCol()
};
},
//-------------------------------------------------------------------------
// Methods to create specific tokens
//-------------------------------------------------------------------------
/**
* Produces a token for any at-rule. If the at-rule is unknown, then
* the token is for a single "@" character.
* @param {String} first The first character for the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method atRuleToken
*/
atRuleToken: function(first, startLine, startCol){
var rule = first,
reader = this._reader,
tt = Tokens.CHAR,
valid = false,
ident,
c;
/*
* First, mark where we are. There are only four @ rules,
* so anything else is really just an invalid token.
* Basically, if this doesn't match one of the known @
* rules, just return '@' as an unknown token and allow
* parsing to continue after that point.
*/
reader.mark();
//try to find the at-keyword
ident = this.readName();
rule = first + ident;
tt = Tokens.type(rule.toLowerCase());
//if it's not valid, use the first character only and reset the reader
if (tt == Tokens.CHAR || tt == Tokens.UNKNOWN){
if (rule.length > 1){
tt = Tokens.UNKNOWN_SYM;
} else {
tt = Tokens.CHAR;
rule = first;
reader.reset();
}
}
return this.createToken(tt, rule, startLine, startCol);
},
/**
* Produces a character token based on the given character
* and location in the stream. If there's a special (non-standard)
* token name, this is used; otherwise CHAR is used.
* @param {String} c The character for the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method charToken
*/
charToken: function(c, startLine, startCol){
var tt = Tokens.type(c);
if (tt == -1){
tt = Tokens.CHAR;
}
return this.createToken(tt, c, startLine, startCol);
},
/**
* Produces a character token based on the given character
* and location in the stream. If there's a special (non-standard)
* token name, this is used; otherwise CHAR is used.
* @param {String} first The first character for the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method commentToken
*/
commentToken: function(first, startLine, startCol){
var reader = this._reader,
comment = this.readComment(first);
return this.createToken(Tokens.COMMENT, comment, startLine, startCol);
},
/**
* Produces a comparison token based on the given character
* and location in the stream. The next character must be
* read and is already known to be an equals sign.
* @param {String} c The character for the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method comparisonToken
*/
comparisonToken: function(c, startLine, startCol){
var reader = this._reader,
comparison = c + reader.read(),
tt = Tokens.type(comparison) || Tokens.CHAR;
return this.createToken(tt, comparison, startLine, startCol);
},
/**
* Produces a hash token based on the specified information. The
* first character provided is the pound sign (#) and then this
* method reads a name afterward.
* @param {String} first The first character (#) in the hash name.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method hashToken
*/
hashToken: function(first, startLine, startCol){
var reader = this._reader,
name = this.readName(first);
return this.createToken(Tokens.HASH, name, startLine, startCol);
},
/**
* Produces a CDO or CHAR token based on the specified information. The
* first character is provided and the rest is read by the function to determine
* the correct token to create.
* @param {String} first The first character in the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method htmlCommentStartToken
*/
htmlCommentStartToken: function(first, startLine, startCol){
var reader = this._reader,
text = first;
reader.mark();
text += reader.readCount(3);
if (text == "<!--"){
return this.createToken(Tokens.CDO, text, startLine, startCol);
} else {
reader.reset();
return this.charToken(first, startLine, startCol);
}
},
/**
* Produces a CDC or CHAR token based on the specified information. The
* first character is provided and the rest is read by the function to determine
* the correct token to create.
* @param {String} first The first character in the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method htmlCommentEndToken
*/
htmlCommentEndToken: function(first, startLine, startCol){
var reader = this._reader,
text = first;
reader.mark();
text += reader.readCount(2);
if (text == "-->"){
return this.createToken(Tokens.CDC, text, startLine, startCol);
} else {
reader.reset();
return this.charToken(first, startLine, startCol);
}
},
/**
* Produces an IDENT or FUNCTION token based on the specified information. The
* first character is provided and the rest is read by the function to determine
* the correct token to create.
* @param {String} first The first character in the identifier.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method identOrFunctionToken
*/
identOrFunctionToken: function(first, startLine, startCol){
var reader = this._reader,
ident = this.readName(first),
tt = Tokens.IDENT;
//if there's a left paren immediately after, it's a URI or function
if (reader.peek() == "("){
ident += reader.read();
if (ident.toLowerCase() == "url("){
tt = Tokens.URI;
ident = this.readURI(ident);
//didn't find a valid URL or there's no closing paren
if (ident.toLowerCase() == "url("){
tt = Tokens.FUNCTION;
}
} else {
tt = Tokens.FUNCTION;
}
} else if (reader.peek() == ":"){ //might be an IE function
//IE-specific functions always being with progid:
if (ident.toLowerCase() == "progid"){
ident += reader.readTo("(");
tt = Tokens.IE_FUNCTION;
}
}
return this.createToken(tt, ident, startLine, startCol);
},
/**
* Produces an IMPORTANT_SYM or CHAR token based on the specified information. The
* first character is provided and the rest is read by the function to determine
* the correct token to create.
* @param {String} first The first character in the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method importantToken
*/
importantToken: function(first, startLine, startCol){
var reader = this._reader,
important = first,
tt = Tokens.CHAR,
temp,
c;
reader.mark();
c = reader.read();
while(c){
//there can be a comment in here
if (c == "/"){
//if the next character isn't a star, then this isn't a valid !important token
if (reader.peek() != "*"){
break;
} else {
temp = this.readComment(c);
if (temp === ""){ //broken!
break;
}
}
} else if (isWhitespace(c)){
important += c + this.readWhitespace();
} else if (/i/i.test(c)){
temp = reader.readCount(8);
if (/mportant/i.test(temp)){
important += c + temp;
tt = Tokens.IMPORTANT_SYM;
}
break; //we're done
} else {
break;
}
c = reader.read();
}
if (tt == Tokens.CHAR){
reader.reset();
return this.charToken(first, startLine, startCol);
} else {
return this.createToken(tt, important, startLine, startCol);
}
},
/**
* Produces a NOT or CHAR token based on the specified information. The
* first character is provided and the rest is read by the function to determine
* the correct token to create.
* @param {String} first The first character in the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method notToken
*/
notToken: function(first, startLine, startCol){
var reader = this._reader,
text = first;
reader.mark();
text += reader.readCount(4);
if (text.toLowerCase() == ":not("){
return this.createToken(Tokens.NOT, text, startLine, startCol);
} else {
reader.reset();
return this.charToken(first, startLine, startCol);
}
},
/**
* Produces a number token based on the given character
* and location in the stream. This may return a token of
* NUMBER, EMS, EXS, LENGTH, ANGLE, TIME, FREQ, DIMENSION,
* or PERCENTAGE.
* @param {String} first The first character for the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method numberToken
*/
numberToken: function(first, startLine, startCol){
var reader = this._reader,
value = this.readNumber(first),
ident,
tt = Tokens.NUMBER,
c = reader.peek();
if (isIdentStart(c)){
ident = this.readName(reader.read());
value += ident;
if (/^em$|^ex$|^px$|^gd$|^rem$|^vw$|^vh$|^vm$|^ch$|^cm$|^mm$|^in$|^pt$|^pc$/i.test(ident)){
tt = Tokens.LENGTH;
} else if (/^deg|^rad$|^grad$/i.test(ident)){
tt = Tokens.ANGLE;
} else if (/^ms$|^s$/i.test(ident)){
tt = Tokens.TIME;
} else if (/^hz$|^khz$/i.test(ident)){
tt = Tokens.FREQ;
} else if (/^dpi$|^dpcm$/i.test(ident)){
tt = Tokens.RESOLUTION;
} else {
tt = Tokens.DIMENSION;
}
} else if (c == "%"){
value += reader.read();
tt = Tokens.PERCENTAGE;
}
return this.createToken(tt, value, startLine, startCol);
},
/**
* Produces a string token based on the given character
* and location in the stream. Since strings may be indicated
* by single or double quotes, a failure to match starting
* and ending quotes results in an INVALID token being generated.
* The first character in the string is passed in and then
* the rest are read up to and including the final quotation mark.
* @param {String} first The first character in the string.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method stringToken
*/
stringToken: function(first, startLine, startCol){
var delim = first,
string = first,
reader = this._reader,
prev = first,
tt = Tokens.STRING,
c = reader.read();
while(c){
string += c;
//if the delimiter is found with an escapement, we're done.
if (c == delim && prev != "\\"){
break;
}
//if there's a newline without an escapement, it's an invalid string
if (isNewLine(reader.peek()) && c != "\\"){
tt = Tokens.INVALID;
break;
}
//save previous and get next
prev = c;
c = reader.read();
}
//if c is null, that means we're out of input and the string was never closed
if (c === null){
tt = Tokens.INVALID;
}
return this.createToken(tt, string, startLine, startCol);
},
unicodeRangeToken: function(first, startLine, startCol){
var reader = this._reader,
value = first,
temp,
tt = Tokens.CHAR;
//then it should be a unicode range
if (reader.peek() == "+"){
reader.mark();
value += reader.read();
value += this.readUnicodeRangePart(true);
//ensure there's an actual unicode range here
if (value.length == 2){
reader.reset();
} else {
tt = Tokens.UNICODE_RANGE;
//if there's a ? in the first part, there can't be a second part
if (value.indexOf("?") == -1){
if (reader.peek() == "-"){
reader.mark();
temp = reader.read();
temp += this.readUnicodeRangePart(false);
//if there's not another value, back up and just take the first
if (temp.length == 1){
reader.reset();
} else {
value += temp;
}
}
}
}
}
return this.createToken(tt, value, startLine, startCol);
},
/**
* Produces a S token based on the specified information. Since whitespace
* may have multiple characters, this consumes all whitespace characters
* into a single token.
* @param {String} first The first character in the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method whitespaceToken
*/
whitespaceToken: function(first, startLine, startCol){
var reader = this._reader,
value = first + this.readWhitespace();
return this.createToken(Tokens.S, value, startLine, startCol);
},
//-------------------------------------------------------------------------
// Methods to read values from the string stream
//-------------------------------------------------------------------------
readUnicodeRangePart: function(allowQuestionMark){
var reader = this._reader,
part = "",
c = reader.peek();
//first read hex digits
while(isHexDigit(c) && part.length < 6){
reader.read();
part += c;
c = reader.peek();
}
//then read question marks if allowed
if (allowQuestionMark){
while(c == "?" && part.length < 6){
reader.read();
part += c;
c = reader.peek();
}
}
//there can't be any other characters after this point
return part;
},
readWhitespace: function(){
var reader = this._reader,
whitespace = "",
c = reader.peek();
while(isWhitespace(c)){
reader.read();
whitespace += c;
c = reader.peek();
}
return whitespace;
},
readNumber: function(first){
var reader = this._reader,
number = first,
hasDot = (first == "."),
c = reader.peek();
while(c){
if (isDigit(c)){
number += reader.read();
} else if (c == "."){
if (hasDot){
break;
} else {
hasDot = true;
number += reader.read();
}
} else {
break;
}
c = reader.peek();
}
return number;
},
readString: function(){
var reader = this._reader,
delim = reader.read(),
string = delim,
prev = delim,
c = reader.peek();
while(c){
c = reader.read();
string += c;
//if the delimiter is found with an escapement, we're done.
if (c == delim && prev != "\\"){
break;
}
//if there's a newline without an escapement, it's an invalid string
if (isNewLine(reader.peek()) && c != "\\"){
string = "";
break;
}
//save previous and get next
prev = c;
c = reader.peek();
}
//if c is null, that means we're out of input and the string was never closed
if (c === null){
string = "";
}
return string;
},
readURI: function(first){
var reader = this._reader,
uri = first,
inner = "",
c = reader.peek();
reader.mark();
//skip whitespace before
while(c && isWhitespace(c)){
reader.read();
c = reader.peek();
}
//it's a string
if (c == "'" || c == "\""){
inner = this.readString();
} else {
inner = this.readURL();
}
c = reader.peek();
//skip whitespace after
while(c && isWhitespace(c)){
reader.read();
c = reader.peek();
}
//if there was no inner value or the next character isn't closing paren, it's not a URI
if (inner === "" || c != ")"){
uri = first;
reader.reset();
} else {
uri += inner + reader.read();
}
return uri;
},
readURL: function(){
var reader = this._reader,
url = "",
c = reader.peek();
//TODO: Check for escape and nonascii
while (/^[!#$%&\\*-~]$/.test(c)){
url += reader.read();
c = reader.peek();
}
return url;
},
readName: function(first){
var reader = this._reader,
ident = first || "",
c = reader.peek();
while(true){
if (c == "\\"){
ident += this.readEscape(reader.read());
c = reader.peek();
} else if(c && isNameChar(c)){
ident += reader.read();
c = reader.peek();
} else {
break;
}
}
return ident;
},
readEscape: function(first){
var reader = this._reader,
cssEscape = first || "",
i = 0,
c = reader.peek();
if (isHexDigit(c)){
do {
cssEscape += reader.read();
c = reader.peek();
} while(c && isHexDigit(c) && ++i < 6);
}
if (cssEscape.length == 3 && /\s/.test(c) ||
cssEscape.length == 7 || cssEscape.length == 1){
reader.read();
} else {
c = "";
}
return cssEscape + c;
},
readComment: function(first){
var reader = this._reader,
comment = first || "",
c = reader.read();
if (c == "*"){
while(c){
comment += c;
//look for end of comment
if (comment.length > 2 && c == "*" && reader.peek() == "/"){
comment += reader.read();
break;
}
c = reader.read();
}
return comment;
} else {
return "";
}
}
});
var Tokens = [
/*
* The following token names are defined in CSS3 Grammar: http://www.w3.org/TR/css3-syntax/#lexical
*/
//HTML-style comments
{ name: "CDO"},
{ name: "CDC"},
//ignorables
{ name: "S", whitespace: true/*, channel: "ws"*/},
{ name: "COMMENT", comment: true, hide: true, channel: "comment" },
//attribute equality
{ name: "INCLUDES", text: "~="},
{ name: "DASHMATCH", text: "|="},
{ name: "PREFIXMATCH", text: "^="},
{ name: "SUFFIXMATCH", text: "$="},
{ name: "SUBSTRINGMATCH", text: "*="},
//identifier types
{ name: "STRING"},
{ name: "IDENT"},
{ name: "HASH"},
//at-keywords
{ name: "IMPORT_SYM", text: "@import"},
{ name: "PAGE_SYM", text: "@page"},
{ name: "MEDIA_SYM", text: "@media"},
{ name: "FONT_FACE_SYM", text: "@font-face"},
{ name: "CHARSET_SYM", text: "@charset"},
{ name: "NAMESPACE_SYM", text: "@namespace"},
{ name: "UNKNOWN_SYM" },
//{ name: "ATKEYWORD"},
//CSS3 animations
{ name: "KEYFRAMES_SYM", text: [ "@keyframes", "@-webkit-keyframes", "@-moz-keyframes", "@-o-keyframes" ] },
//important symbol
{ name: "IMPORTANT_SYM"},
//measurements
{ name: "LENGTH"},
{ name: "ANGLE"},
{ name: "TIME"},
{ name: "FREQ"},
{ name: "DIMENSION"},
{ name: "PERCENTAGE"},
{ name: "NUMBER"},
//functions
{ name: "URI"},
{ name: "FUNCTION"},
//Unicode ranges
{ name: "UNICODE_RANGE"},
/*
* The following token names are defined in CSS3 Selectors: http://www.w3.org/TR/css3-selectors/#selector-syntax
*/
//invalid string
{ name: "INVALID"},
//combinators
{ name: "PLUS", text: "+" },
{ name: "GREATER", text: ">"},
{ name: "COMMA", text: ","},
{ name: "TILDE", text: "~"},
//modifier
{ name: "NOT"},
/*
* Defined in CSS3 Paged Media
*/
{ name: "TOPLEFTCORNER_SYM", text: "@top-left-corner"},
{ name: "TOPLEFT_SYM", text: "@top-left"},
{ name: "TOPCENTER_SYM", text: "@top-center"},
{ name: "TOPRIGHT_SYM", text: "@top-right"},
{ name: "TOPRIGHTCORNER_SYM", text: "@top-right-corner"},
{ name: "BOTTOMLEFTCORNER_SYM", text: "@bottom-left-corner"},
{ name: "BOTTOMLEFT_SYM", text: "@bottom-left"},
{ name: "BOTTOMCENTER_SYM", text: "@bottom-center"},
{ name: "BOTTOMRIGHT_SYM", text: "@bottom-right"},
{ name: "BOTTOMRIGHTCORNER_SYM", text: "@bottom-right-corner"},
{ name: "LEFTTOP_SYM", text: "@left-top"},
{ name: "LEFTMIDDLE_SYM", text: "@left-middle"},
{ name: "LEFTBOTTOM_SYM", text: "@left-bottom"},
{ name: "RIGHTTOP_SYM", text: "@right-top"},
{ name: "RIGHTMIDDLE_SYM", text: "@right-middle"},
{ name: "RIGHTBOTTOM_SYM", text: "@right-bottom"},
/*
* The following token names are defined in CSS3 Media Queries: http://www.w3.org/TR/css3-mediaqueries/#syntax
*/
/*{ name: "MEDIA_ONLY", state: "media"},
{ name: "MEDIA_NOT", state: "media"},
{ name: "MEDIA_AND", state: "media"},*/
{ name: "RESOLUTION", state: "media"},
/*
* The following token names are not defined in any CSS specification but are used by the lexer.
*/
//not a real token, but useful for stupid IE filters
{ name: "IE_FUNCTION" },
//part of CSS3 grammar but not the Flex code
{ name: "CHAR" },
//TODO: Needed?
//Not defined as tokens, but might as well be
{
name: "PIPE",
text: "|"
},
{
name: "SLASH",
text: "/"
},
{
name: "MINUS",
text: "-"
},
{
name: "STAR",
text: "*"
},
{
name: "LBRACE",
text: "{"
},
{
name: "RBRACE",
text: "}"
},
{
name: "LBRACKET",
text: "["
},
{
name: "RBRACKET",
text: "]"
},
{
name: "EQUALS",
text: "="
},
{
name: "COLON",
text: ":"
},
{
name: "SEMICOLON",
text: ";"
},
{
name: "LPAREN",
text: "("
},
{
name: "RPAREN",
text: ")"
},
{
name: "DOT",
text: "."
}
];
(function(){
var nameMap = [],
typeMap = {};
Tokens.UNKNOWN = -1;
Tokens.unshift({name:"EOF"});
for (var i=0, len = Tokens.length; i < len; i++){
nameMap.push(Tokens[i].name);
Tokens[Tokens[i].name] = i;
if (Tokens[i].text){
if (Tokens[i].text instanceof Array){
for (var j=0; j < Tokens[i].text.length; j++){
typeMap[Tokens[i].text[j]] = i;
}
} else {
typeMap[Tokens[i].text] = i;
}
}
}
Tokens.name = function(tt){
return nameMap[tt];
};
Tokens.type = function(c){
return typeMap[c] || -1;
};
})();
//This file will likely change a lot! Very experimental!
/*global Properties, ValidationTypes, ValidationError, PropertyValueIterator */
var Validation = {
validate: function(property, value){
//normalize name
var name = property.toString().toLowerCase(),
parts = value.parts,
expression = new PropertyValueIterator(value),
spec = Properties[name],
part,
valid,
j, count,
msg,
types,
last,
literals,
max, multi, group;
if (!spec) {
if (name.indexOf("-") !== 0){ //vendor prefixed are ok
throw new ValidationError("Unknown property '" + property + "'.", property.line, property.col);
}
} else if (typeof spec != "number"){
//initialization
if (typeof spec == "string"){
if (spec.indexOf("||") > -1) {
this.groupProperty(spec, expression);
} else {
this.singleProperty(spec, expression, 1);
}
} else if (spec.multi) {
this.multiProperty(spec.multi, expression, spec.comma, spec.max || Infinity);
} else if (typeof spec == "function") {
spec(expression);
}
}
},
singleProperty: function(types, expression, max, partial) {
var result = false,
value = expression.value,
count = 0,
part;
while (expression.hasNext() && count < max) {
result = ValidationTypes.isAny(expression, types);
if (!result) {
break;
}
count++;
}
if (!result) {
if (expression.hasNext() && !expression.isFirst()) {
part = expression.peek();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col);
}
} else if (expression.hasNext()) {
part = expression.next();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
}
},
multiProperty: function (types, expression, comma, max) {
var result = false,
value = expression.value,
count = 0,
sep = false,
part;
while(expression.hasNext() && !result && count < max) {
if (ValidationTypes.isAny(expression, types)) {
count++;
if (!expression.hasNext()) {
result = true;
} else if (comma) {
if (expression.peek() == ",") {
part = expression.next();
} else {
break;
}
}
} else {
break;
}
}
if (!result) {
if (expression.hasNext() && !expression.isFirst()) {
part = expression.peek();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
part = expression.previous();
if (comma && part == ",") {
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col);
}
}
} else if (expression.hasNext()) {
part = expression.next();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
}
},
groupProperty: function (types, expression, comma) {
var result = false,
value = expression.value,
typeCount = types.split("||").length,
groups = { count: 0 },
partial = false,
name,
part;
while(expression.hasNext() && !result) {
name = ValidationTypes.isAnyOfGroup(expression, types);
if (name) {
//no dupes
if (groups[name]) {
break;
} else {
groups[name] = 1;
groups.count++;
partial = true;
if (groups.count == typeCount || !expression.hasNext()) {
result = true;
}
}
} else {
break;
}
}
if (!result) {
if (partial && expression.hasNext()) {
part = expression.peek();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col);
}
} else if (expression.hasNext()) {
part = expression.next();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
}
}
};
/**
* Type to use when a validation error occurs.
* @class ValidationError
* @namespace parserlib.util
* @constructor
* @param {String} message The error message.
* @param {int} line The line at which the error occurred.
* @param {int} col The column at which the error occurred.
*/
function ValidationError(message, line, col){
/**
* The column at which the error occurred.
* @type int
* @property col
*/
this.col = col;
/**
* The line at which the error occurred.
* @type int
* @property line
*/
this.line = line;
/**
* The text representation of the unit.
* @type String
* @property text
*/
this.message = message;
}
//inherit from Error
ValidationError.prototype = new Error();
//This file will likely change a lot! Very experimental!
/*global Properties, Validation, ValidationError, PropertyValueIterator, console*/
var ValidationTypes = {
isLiteral: function (part, literals) {
var text = part.text.toString().toLowerCase(),
args = literals.split(" | "),
i, len, found = false;
for (i=0,len=args.length; i < len && !found; i++){
if (text == args[i].toLowerCase()){
found = true;
}
}
return found;
},
isSimple: function(type) {
return !!this.simple[type];
},
isComplex: function(type) {
return !!this.complex[type];
},
/**
* Determines if the next part(s) of the given expression
* are any of the given types.
*/
isAny: function (expression, types) {
var args = types.split(" | "),
i, len, found = false;
for (i=0,len=args.length; i < len && !found && expression.hasNext(); i++){
found = this.isType(expression, args[i]);
}
return found;
},
/**
* Determines if the next part(s) of the given expresion
* are one of a group.
*/
isAnyOfGroup: function(expression, types) {
var args = types.split(" || "),
i, len, found = false;
for (i=0,len=args.length; i < len && !found; i++){
found = this.isType(expression, args[i]);
}
return found ? args[i-1] : false;
},
/**
* Determines if the next part(s) of the given expression
* are of a given type.
*/
isType: function (expression, type) {
var part = expression.peek(),
result = false;
if (type.charAt(0) != "<") {
result = this.isLiteral(part, type);
if (result) {
expression.next();
}
} else if (this.simple[type]) {
result = this.simple[type](part);
if (result) {
expression.next();
}
} else {
result = this.complex[type](expression);
}
return result;
},
simple: {
"<absolute-size>": function(part){
return ValidationTypes.isLiteral(part, "xx-small | x-small | small | medium | large | x-large | xx-large");
},
"<attachment>": function(part){
return ValidationTypes.isLiteral(part, "scroll | fixed | local");
},
"<attr>": function(part){
return part.type == "function" && part.name == "attr";
},
"<bg-image>": function(part){
return this["<image>"](part) || this["<gradient>"](part) || part == "none";
},
"<gradient>": function(part) {
return part.type == "function" && /^(?:\-(?:ms|moz|o|webkit)\-)?(?:repeating\-)?(?:radial\-|linear\-)?gradient/i.test(part);
},
"<box>": function(part){
return ValidationTypes.isLiteral(part, "padding-box | border-box | content-box");
},
"<content>": function(part){
return part.type == "function" && part.name == "content";
},
"<relative-size>": function(part){
return ValidationTypes.isLiteral(part, "smaller | larger");
},
//any identifier
"<ident>": function(part){
return part.type == "identifier";
},
"<length>": function(part){
return part.type == "length" || part.type == "number" || part.type == "integer" || part == "0";
},
"<color>": function(part){
return part.type == "color" || part == "transparent";
},
"<number>": function(part){
return part.type == "number" || this["<integer>"](part);
},
"<integer>": function(part){
return part.type == "integer";
},
"<line>": function(part){
return part.type == "integer";
},
"<angle>": function(part){
return part.type == "angle";
},
"<uri>": function(part){
return part.type == "uri";
},
"<image>": function(part){
return this["<uri>"](part);
},
"<percentage>": function(part){
return part.type == "percentage" || part == "0";
},
"<border-width>": function(part){
return this["<length>"](part) || ValidationTypes.isLiteral(part, "thin | medium | thick");
},
"<border-style>": function(part){
return ValidationTypes.isLiteral(part, "none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset");
},
"<margin-width>": function(part){
return this["<length>"](part) || this["<percentage>"](part) || ValidationTypes.isLiteral(part, "auto");
},
"<padding-width>": function(part){
return this["<length>"](part) || this["<percentage>"](part);
},
"<shape>": function(part){
return part.type == "function" && (part.name == "rect" || part.name == "inset-rect");
},
"<time>": function(part) {
return part.type == "time";
}
},
complex: {
"<bg-position>": function(expression){
var types = this,
result = false,
numeric = "<percentage> | <length>",
xDir = "left | center | right",
yDir = "top | center | bottom",
part,
i, len;
/*
<position> = [
[ left | center | right | top | bottom | <percentage> | <length> ]
|
[ left | center | right | <percentage> | <length> ]
[ top | center | bottom | <percentage> | <length> ]
|
[ center | [ left | right ] [ <percentage> | <length> ]? ] &&
[ center | [ top | bottom ] [ <percentage> | <length> ]? ]
]
*/
if (ValidationTypes.isAny(expression, "top | bottom")) {
result = true;
} else {
//must be two-part
if (ValidationTypes.isAny(expression, numeric)){
if (expression.hasNext()){
result = ValidationTypes.isAny(expression, numeric + " | " + yDir);
}
} else if (ValidationTypes.isAny(expression, xDir)){
if (expression.hasNext()){
//two- or three-part
if (ValidationTypes.isAny(expression, yDir)){
result = true;
ValidationTypes.isAny(expression, numeric);
} else if (ValidationTypes.isAny(expression, numeric)){
//could also be two-part, so check the next part
if (ValidationTypes.isAny(expression, yDir)){
ValidationTypes.isAny(expression, numeric);
}
result = true;
}
}
}
}
return result;
},
"<bg-size>": function(expression){
//<bg-size> = [ <length> | <percentage> | auto ]{1,2} | cover | contain
var types = this,
result = false,
numeric = "<percentage> | <length> | auto",
part,
i, len;
if (ValidationTypes.isAny(expression, "cover | contain")) {
result = true;
} else if (ValidationTypes.isAny(expression, numeric)) {
result = true;
ValidationTypes.isAny(expression, numeric);
}
return result;
},
"<repeat-style>": function(expression){
//repeat-x | repeat-y | [repeat | space | round | no-repeat]{1,2}
var result = false,
values = "repeat | space | round | no-repeat",
part;
if (expression.hasNext()){
part = expression.next();
if (ValidationTypes.isLiteral(part, "repeat-x | repeat-y")) {
result = true;
} else if (ValidationTypes.isLiteral(part, values)) {
result = true;
if (expression.hasNext() && ValidationTypes.isLiteral(expression.peek(), values)) {
expression.next();
}
}
}
return result;
},
"<shadow>": function(expression) {
//inset? && [ <length>{2,4} && <color>? ]
var result = false,
count = 0,
inset = false,
color = false,
part;
if (expression.hasNext()) {
if (ValidationTypes.isAny(expression, "inset")){
inset = true;
}
if (ValidationTypes.isAny(expression, "<color>")) {
color = true;
}
while (ValidationTypes.isAny(expression, "<length>") && count < 4) {
count++;
}
if (expression.hasNext()) {
if (!color) {
ValidationTypes.isAny(expression, "<color>");
}
if (!inset) {
ValidationTypes.isAny(expression, "inset");
}
}
result = (count >= 2 && count <= 4);
}
return result;
},
"<x-one-radius>": function(expression) {
//[ <length> | <percentage> ] [ <length> | <percentage> ]?
var result = false,
count = 0,
numeric = "<length> | <percentage>",
part;
if (ValidationTypes.isAny(expression, numeric)){
result = true;
ValidationTypes.isAny(expression, numeric);
}
return result;
}
}
};
parserlib.css = {
Colors :Colors,
Combinator :Combinator,
Parser :Parser,
PropertyName :PropertyName,
PropertyValue :PropertyValue,
PropertyValuePart :PropertyValuePart,
MediaFeature :MediaFeature,
MediaQuery :MediaQuery,
Selector :Selector,
SelectorPart :SelectorPart,
SelectorSubPart :SelectorSubPart,
Specificity :Specificity,
TokenStream :TokenStream,
Tokens :Tokens,
ValidationError :ValidationError
};
})();
/**
* Main CSSLint object.
* @class CSSLint
* @static
* @extends parserlib.util.EventTarget
*/
/*global parserlib, Reporter*/
var CSSLint = (function(){
var rules = [],
formatters = [],
api = new parserlib.util.EventTarget();
api.version = "0.9.8";
//-------------------------------------------------------------------------
// Rule Management
//-------------------------------------------------------------------------
/**
* Adds a new rule to the engine.
* @param {Object} rule The rule to add.
* @method addRule
*/
api.addRule = function(rule){
rules.push(rule);
rules[rule.id] = rule;
};
/**
* Clears all rule from the engine.
* @method clearRules
*/
api.clearRules = function(){
rules = [];
};
/**
* Returns the rule objects.
* @return An array of rule objects.
* @method getRules
*/
api.getRules = function(){
return [].concat(rules).sort(function(a,b){
return a.id > b.id ? 1 : 0;
});
};
/**
* Returns a ruleset configuration object with all current rules.
* @return A ruleset object.
* @method getRuleset
*/
api.getRuleset = function() {
var ruleset = {},
i = 0,
len = rules.length;
while (i < len){
ruleset[rules[i++].id] = 1; //by default, everything is a warning
}
return ruleset;
};
//-------------------------------------------------------------------------
// Formatters
//-------------------------------------------------------------------------
/**
* Adds a new formatter to the engine.
* @param {Object} formatter The formatter to add.
* @method addFormatter
*/
api.addFormatter = function(formatter) {
// formatters.push(formatter);
formatters[formatter.id] = formatter;
};
/**
* Retrieves a formatter for use.
* @param {String} formatId The name of the format to retrieve.
* @return {Object} The formatter or undefined.
* @method getFormatter
*/
api.getFormatter = function(formatId){
return formatters[formatId];
};
/**
* Formats the results in a particular format for a single file.
* @param {Object} result The results returned from CSSLint.verify().
* @param {String} filename The filename for which the results apply.
* @param {String} formatId The name of the formatter to use.
* @param {Object} options (Optional) for special output handling.
* @return {String} A formatted string for the results.
* @method format
*/
api.format = function(results, filename, formatId, options) {
var formatter = this.getFormatter(formatId),
result = null;
if (formatter){
result = formatter.startFormat();
result += formatter.formatResults(results, filename, options || {});
result += formatter.endFormat();
}
return result;
};
/**
* Indicates if the given format is supported.
* @param {String} formatId The ID of the format to check.
* @return {Boolean} True if the format exists, false if not.
* @method hasFormat
*/
api.hasFormat = function(formatId){
return formatters.hasOwnProperty(formatId);
};
//-------------------------------------------------------------------------
// Verification
//-------------------------------------------------------------------------
/**
* Starts the verification process for the given CSS text.
* @param {String} text The CSS text to verify.
* @param {Object} ruleset (Optional) List of rules to apply. If null, then
* all rules are used. If a rule has a value of 1 then it's a warning,
* a value of 2 means it's an error.
* @return {Object} Results of the verification.
* @method verify
*/
api.verify = function(text, ruleset){
var i = 0,
len = rules.length,
reporter,
lines,
report,
parser = new parserlib.css.Parser({ starHack: true, ieFilters: true,
underscoreHack: true, strict: false });
// normalize line endings
lines = text.replace(/\n\r?/g, "$split$").split('$split$');
if (!ruleset){
ruleset = this.getRuleset();
}
reporter = new Reporter(lines, ruleset);
ruleset.errors = 2; //always report parsing errors as errors
for (i in ruleset){
if(ruleset.hasOwnProperty(i)){
if (rules[i]){
rules[i].init(parser, reporter);
}
}
}
//capture most horrible error type
try {
parser.parse(text);
} catch (ex) {
reporter.error("Fatal error, cannot continue: " + ex.message, ex.line, ex.col, {});
}
report = {
messages : reporter.messages,
stats : reporter.stats
};
//sort by line numbers, rollups at the bottom
report.messages.sort(function (a, b){
if (a.rollup && !b.rollup){
return 1;
} else if (!a.rollup && b.rollup){
return -1;
} else {
return a.line - b.line;
}
});
return report;
};
//-------------------------------------------------------------------------
// Publish the API
//-------------------------------------------------------------------------
return api;
})();
/*global CSSLint*/
/**
* An instance of Report is used to report results of the
* verification back to the main API.
* @class Reporter
* @constructor
* @param {String[]} lines The text lines of the source.
* @param {Object} ruleset The set of rules to work with, including if
* they are errors or warnings.
*/
function Reporter(lines, ruleset){
/**
* List of messages being reported.
* @property messages
* @type String[]
*/
this.messages = [];
/**
* List of statistics being reported.
* @property stats
* @type String[]
*/
this.stats = [];
/**
* Lines of code being reported on. Used to provide contextual information
* for messages.
* @property lines
* @type String[]
*/
this.lines = lines;
/**
* Information about the rules. Used to determine whether an issue is an
* error or warning.
* @property ruleset
* @type Object
*/
this.ruleset = ruleset;
}
Reporter.prototype = {
//restore constructor
constructor: Reporter,
/**
* Report an error.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method error
*/
error: function(message, line, col, rule){
this.messages.push({
type : "error",
line : line,
col : col,
message : message,
evidence: this.lines[line-1],
rule : rule || {}
});
},
/**
* Report an warning.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method warn
* @deprecated Use report instead.
*/
warn: function(message, line, col, rule){
this.report(message, line, col, rule);
},
/**
* Report an issue.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method report
*/
report: function(message, line, col, rule){
this.messages.push({
type : this.ruleset[rule.id] == 2 ? "error" : "warning",
line : line,
col : col,
message : message,
evidence: this.lines[line-1],
rule : rule
});
},
/**
* Report some informational text.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method info
*/
info: function(message, line, col, rule){
this.messages.push({
type : "info",
line : line,
col : col,
message : message,
evidence: this.lines[line-1],
rule : rule
});
},
/**
* Report some rollup error information.
* @param {String} message The message to store.
* @param {Object} rule The rule this message relates to.
* @method rollupError
*/
rollupError: function(message, rule){
this.messages.push({
type : "error",
rollup : true,
message : message,
rule : rule
});
},
/**
* Report some rollup warning information.
* @param {String} message The message to store.
* @param {Object} rule The rule this message relates to.
* @method rollupWarn
*/
rollupWarn: function(message, rule){
this.messages.push({
type : "warning",
rollup : true,
message : message,
rule : rule
});
},
/**
* Report a statistic.
* @param {String} name The name of the stat to store.
* @param {Variant} value The value of the stat.
* @method stat
*/
stat: function(name, value){
this.stats[name] = value;
}
};
//expose for testing purposes
CSSLint._Reporter = Reporter;
/*global CSSLint*/
/*
* Utility functions that make life easier.
*/
CSSLint.Util = {
/*
* Adds all properties from supplier onto receiver,
* overwriting if the same name already exists on
* reciever.
* @param {Object} The object to receive the properties.
* @param {Object} The object to provide the properties.
* @return {Object} The receiver
*/
mix: function(receiver, supplier){
var prop;
for (prop in supplier){
if (supplier.hasOwnProperty(prop)){
receiver[prop] = supplier[prop];
}
}
return prop;
},
/*
* Polyfill for array indexOf() method.
* @param {Array} values The array to search.
* @param {Variant} value The value to search for.
* @return {int} The index of the value if found, -1 if not.
*/
indexOf: function(values, value){
if (values.indexOf){
return values.indexOf(value);
} else {
for (var i=0, len=values.length; i < len; i++){
if (values[i] === value){
return i;
}
}
return -1;
}
},
/*
* Polyfill for array forEach() method.
* @param {Array} values The array to operate on.
* @param {Function} func The function to call on each item.
* @return {void}
*/
forEach: function(values, func) {
if (values.forEach){
return values.forEach(func);
} else {
for (var i=0, len=values.length; i < len; i++){
func(values[i], i, values);
}
}
}
};
/*global CSSLint*/
/*
* Rule: Don't use adjoining classes (.foo.bar).
*/
CSSLint.addRule({
//rule information
id: "adjoining-classes",
name: "Disallow adjoining classes",
desc: "Don't use adjoining classes.",
browsers: "IE6",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
classCount,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type == parser.SELECTOR_PART_TYPE){
classCount = 0;
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type == "class"){
classCount++;
}
if (classCount > 1){
reporter.report("Don't use adjoining classes.", part.line, part.col, rule);
}
}
}
}
}
});
}
});
/*global CSSLint*/
/*
* Rule: Don't use width or height when using padding or border.
*/
CSSLint.addRule({
//rule information
id: "box-model",
name: "Beware of broken box size",
desc: "Don't use width or height when using padding or border.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
widthProperties = {
border: 1,
"border-left": 1,
"border-right": 1,
padding: 1,
"padding-left": 1,
"padding-right": 1
},
heightProperties = {
border: 1,
"border-bottom": 1,
"border-top": 1,
padding: 1,
"padding-bottom": 1,
"padding-top": 1
},
properties;
function startRule(){
properties = {};
}
function endRule(){
var prop, value;
if (properties.height){
for (prop in heightProperties){
if (heightProperties.hasOwnProperty(prop) && properties[prop]){
value = properties[prop].value;
//special case for padding
if (!(prop == "padding" && value.parts.length === 2 && value.parts[0].value === 0)){
reporter.report("Using height with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule);
}
}
}
}
if (properties.width){
for (prop in widthProperties){
if (widthProperties.hasOwnProperty(prop) && properties[prop]){
value = properties[prop].value;
if (!(prop == "padding" && value.parts.length === 2 && value.parts[1].value === 0)){
reporter.report("Using width with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule);
}
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (heightProperties[name] || widthProperties[name]){
if (!/^0\S*$/.test(event.value) && !(name == "border" && event.value == "none")){
properties[name] = { line: event.property.line, col: event.property.col, value: event.value };
}
} else {
if (/^(width|height)/i.test(name) && /^(length|percentage)/.test(event.value.parts[0].type)){
properties[name] = 1;
}
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endpage", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endkeyframerule", endRule);
}
});
/*global CSSLint*/
/*
* Rule: box-sizing doesn't work in IE6 and IE7.
*/
CSSLint.addRule({
//rule information
id: "box-sizing",
name: "Disallow use of box-sizing",
desc: "The box-sizing properties isn't supported in IE6 and IE7.",
browsers: "IE6, IE7",
tags: ["Compatibility"],
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (name == "box-sizing"){
reporter.report("The box-sizing property isn't supported in IE6 and IE7.", event.line, event.col, rule);
}
});
}
});
/*
* Rule: Include all compatible vendor prefixes to reach a wider
* range of users.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "compatible-vendor-prefixes",
name: "Require compatible vendor prefixes",
desc: "Include all compatible vendor prefixes to reach a wider range of users.",
browsers: "All",
//initialization
init: function (parser, reporter) {
var rule = this,
compatiblePrefixes,
properties,
prop,
variations,
prefixed,
i,
len,
inKeyFrame = false,
arrayPush = Array.prototype.push,
applyTo = [];
// See http://peter.sh/experiments/vendor-prefixed-css-property-overview/ for details
compatiblePrefixes = {
"animation" : "webkit moz",
"animation-delay" : "webkit moz",
"animation-direction" : "webkit moz",
"animation-duration" : "webkit moz",
"animation-fill-mode" : "webkit moz",
"animation-iteration-count" : "webkit moz",
"animation-name" : "webkit moz",
"animation-play-state" : "webkit moz",
"animation-timing-function" : "webkit moz",
"appearance" : "webkit moz",
"border-end" : "webkit moz",
"border-end-color" : "webkit moz",
"border-end-style" : "webkit moz",
"border-end-width" : "webkit moz",
"border-image" : "webkit moz o",
"border-radius" : "webkit moz",
"border-start" : "webkit moz",
"border-start-color" : "webkit moz",
"border-start-style" : "webkit moz",
"border-start-width" : "webkit moz",
"box-align" : "webkit moz ms",
"box-direction" : "webkit moz ms",
"box-flex" : "webkit moz ms",
"box-lines" : "webkit ms",
"box-ordinal-group" : "webkit moz ms",
"box-orient" : "webkit moz ms",
"box-pack" : "webkit moz ms",
"box-sizing" : "webkit moz",
"box-shadow" : "webkit moz",
"column-count" : "webkit moz ms",
"column-gap" : "webkit moz ms",
"column-rule" : "webkit moz ms",
"column-rule-color" : "webkit moz ms",
"column-rule-style" : "webkit moz ms",
"column-rule-width" : "webkit moz ms",
"column-width" : "webkit moz ms",
"hyphens" : "epub moz",
"line-break" : "webkit ms",
"margin-end" : "webkit moz",
"margin-start" : "webkit moz",
"marquee-speed" : "webkit wap",
"marquee-style" : "webkit wap",
"padding-end" : "webkit moz",
"padding-start" : "webkit moz",
"tab-size" : "moz o",
"text-size-adjust" : "webkit ms",
"transform" : "webkit moz ms o",
"transform-origin" : "webkit moz ms o",
"transition" : "webkit moz o",
"transition-delay" : "webkit moz o",
"transition-duration" : "webkit moz o",
"transition-property" : "webkit moz o",
"transition-timing-function" : "webkit moz o",
"user-modify" : "webkit moz",
"user-select" : "webkit moz ms",
"word-break" : "epub ms",
"writing-mode" : "epub ms"
};
for (prop in compatiblePrefixes) {
if (compatiblePrefixes.hasOwnProperty(prop)) {
variations = [];
prefixed = compatiblePrefixes[prop].split(' ');
for (i = 0, len = prefixed.length; i < len; i++) {
variations.push('-' + prefixed[i] + '-' + prop);
}
compatiblePrefixes[prop] = variations;
arrayPush.apply(applyTo, variations);
}
}
parser.addListener("startrule", function () {
properties = [];
});
parser.addListener("startkeyframes", function (event) {
inKeyFrame = event.prefix || true;
});
parser.addListener("endkeyframes", function (event) {
inKeyFrame = false;
});
parser.addListener("property", function (event) {
var name = event.property;
if (CSSLint.Util.indexOf(applyTo, name.text) > -1) {
// e.g., -moz-transform is okay to be alone in @-moz-keyframes
if (!inKeyFrame || typeof inKeyFrame != "string" ||
name.text.indexOf("-" + inKeyFrame + "-") !== 0) {
properties.push(name);
}
}
});
parser.addListener("endrule", function (event) {
if (!properties.length) {
return;
}
var propertyGroups = {},
i,
len,
name,
prop,
variations,
value,
full,
actual,
item,
propertiesSpecified;
for (i = 0, len = properties.length; i < len; i++) {
name = properties[i];
for (prop in compatiblePrefixes) {
if (compatiblePrefixes.hasOwnProperty(prop)) {
variations = compatiblePrefixes[prop];
if (CSSLint.Util.indexOf(variations, name.text) > -1) {
if (!propertyGroups[prop]) {
propertyGroups[prop] = {
full : variations.slice(0),
actual : [],
actualNodes: []
};
}
if (CSSLint.Util.indexOf(propertyGroups[prop].actual, name.text) === -1) {
propertyGroups[prop].actual.push(name.text);
propertyGroups[prop].actualNodes.push(name);
}
}
}
}
}
for (prop in propertyGroups) {
if (propertyGroups.hasOwnProperty(prop)) {
value = propertyGroups[prop];
full = value.full;
actual = value.actual;
if (full.length > actual.length) {
for (i = 0, len = full.length; i < len; i++) {
item = full[i];
if (CSSLint.Util.indexOf(actual, item) === -1) {
propertiesSpecified = (actual.length === 1) ? actual[0] : (actual.length == 2) ? actual.join(" and ") : actual.join(", ");
reporter.report("The property " + item + " is compatible with " + propertiesSpecified + " and should be included as well.", value.actualNodes[0].line, value.actualNodes[0].col, rule);
}
}
}
}
}
});
}
});
/*
* Rule: Certain properties don't play well with certain display values.
* - float should not be used with inline-block
* - height, width, margin-top, margin-bottom, float should not be used with inline
* - vertical-align should not be used with block
* - margin, float should not be used with table-*
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "display-property-grouping",
name: "Require properties appropriate for display",
desc: "Certain properties shouldn't be used with certain display property values.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
var propertiesToCheck = {
display: 1,
"float": "none",
height: 1,
width: 1,
margin: 1,
"margin-left": 1,
"margin-right": 1,
"margin-bottom": 1,
"margin-top": 1,
padding: 1,
"padding-left": 1,
"padding-right": 1,
"padding-bottom": 1,
"padding-top": 1,
"vertical-align": 1
},
properties;
function reportProperty(name, display, msg){
if (properties[name]){
if (typeof propertiesToCheck[name] != "string" || properties[name].value.toLowerCase() != propertiesToCheck[name]){
reporter.report(msg || name + " can't be used with display: " + display + ".", properties[name].line, properties[name].col, rule);
}
}
}
function startRule(){
properties = {};
}
function endRule(){
var display = properties.display ? properties.display.value : null;
if (display){
switch(display){
case "inline":
//height, width, margin-top, margin-bottom, float should not be used with inline
reportProperty("height", display);
reportProperty("width", display);
reportProperty("margin", display);
reportProperty("margin-top", display);
reportProperty("margin-bottom", display);
reportProperty("float", display, "display:inline has no effect on floated elements (but may be used to fix the IE6 double-margin bug).");
break;
case "block":
//vertical-align should not be used with block
reportProperty("vertical-align", display);
break;
case "inline-block":
//float should not be used with inline-block
reportProperty("float", display);
break;
default:
//margin, float should not be used with table
if (display.indexOf("table-") === 0){
reportProperty("margin", display);
reportProperty("margin-left", display);
reportProperty("margin-right", display);
reportProperty("margin-top", display);
reportProperty("margin-bottom", display);
reportProperty("float", display);
}
//otherwise do nothing
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startpage", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (propertiesToCheck[name]){
properties[name] = { value: event.value.text, line: event.property.line, col: event.property.col };
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endkeyframerule", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endpage", endRule);
}
});
/*
* Rule: Disallow duplicate background-images (using url).
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "duplicate-background-images",
name: "Disallow duplicate background images",
desc: "Every background-image should be unique. Use a common class for e.g. sprites.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
stack = {};
parser.addListener("property", function(event){
var name = event.property.text,
value = event.value,
i, len;
if (name.match(/background/i)) {
for (i=0, len=value.parts.length; i < len; i++) {
if (value.parts[i].type == 'uri') {
if (typeof stack[value.parts[i].uri] === 'undefined') {
stack[value.parts[i].uri] = event;
}
else {
reporter.report("Background image '" + value.parts[i].uri + "' was used multiple times, first declared at line " + stack[value.parts[i].uri].line + ", col " + stack[value.parts[i].uri].col + ".", event.line, event.col, rule);
}
}
}
}
});
}
});
/*
* Rule: Duplicate properties must appear one after the other. If an already-defined
* property appears somewhere else in the rule, then it's likely an error.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "duplicate-properties",
name: "Disallow duplicate properties",
desc: "Duplicate properties must appear one after the other.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
properties,
lastProperty;
function startRule(event){
properties = {};
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("property", function(event){
var property = event.property,
name = property.text.toLowerCase();
if (properties[name] && (lastProperty != name || properties[name] == event.value.text)){
reporter.report("Duplicate property '" + event.property + "' found.", event.line, event.col, rule);
}
properties[name] = event.value.text;
lastProperty = name;
});
}
});
/*
* Rule: Style rules without any properties defined should be removed.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "empty-rules",
name: "Disallow empty rules",
desc: "Rules without any properties specified should be removed.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
count = 0;
parser.addListener("startrule", function(){
count=0;
});
parser.addListener("property", function(){
count++;
});
parser.addListener("endrule", function(event){
var selectors = event.selectors;
if (count === 0){
reporter.report("Rule is empty.", selectors[0].line, selectors[0].col, rule);
}
});
}
});
/*
* Rule: There should be no syntax errors. (Duh.)
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "errors",
name: "Parsing Errors",
desc: "This rule looks for recoverable syntax errors.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("error", function(event){
reporter.error(event.message, event.line, event.col, rule);
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "fallback-colors",
name: "Require fallback colors",
desc: "For older browsers that don't support RGBA, HSL, or HSLA, provide a fallback color.",
browsers: "IE6,IE7,IE8",
//initialization
init: function(parser, reporter){
var rule = this,
lastProperty,
propertiesToCheck = {
color: 1,
background: 1,
"background-color": 1
},
properties;
function startRule(event){
properties = {};
lastProperty = null;
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("property", function(event){
var property = event.property,
name = property.text.toLowerCase(),
parts = event.value.parts,
i = 0,
colorType = "",
len = parts.length;
if(propertiesToCheck[name]){
while(i < len){
if (parts[i].type == "color"){
if ("alpha" in parts[i] || "hue" in parts[i]){
if (/([^\)]+)\(/.test(parts[i])){
colorType = RegExp.$1.toUpperCase();
}
if (!lastProperty || (lastProperty.property.text.toLowerCase() != name || lastProperty.colorType != "compat")){
reporter.report("Fallback " + name + " (hex or RGB) should precede " + colorType + " " + name + ".", event.line, event.col, rule);
}
} else {
event.colorType = "compat";
}
}
i++;
}
}
lastProperty = event;
});
}
});
/*
* Rule: You shouldn't use more than 10 floats. If you do, there's probably
* room for some abstraction.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "floats",
name: "Disallow too many floats",
desc: "This rule tests if the float property is used too many times",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
var count = 0;
//count how many times "float" is used
parser.addListener("property", function(event){
if (event.property.text.toLowerCase() == "float" &&
event.value.text.toLowerCase() != "none"){
count++;
}
});
//report the results
parser.addListener("endstylesheet", function(){
reporter.stat("floats", count);
if (count >= 10){
reporter.rollupWarn("Too many floats (" + count + "), you're probably using them for layout. Consider using a grid system instead.", rule);
}
});
}
});
/*
* Rule: Avoid too many @font-face declarations in the same stylesheet.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "font-faces",
name: "Don't use too many web fonts",
desc: "Too many different web fonts in the same stylesheet.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
count = 0;
parser.addListener("startfontface", function(){
count++;
});
parser.addListener("endstylesheet", function(){
if (count > 5){
reporter.rollupWarn("Too many @font-face declarations (" + count + ").", rule);
}
});
}
});
/*
* Rule: You shouldn't need more than 9 font-size declarations.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "font-sizes",
name: "Disallow too many font sizes",
desc: "Checks the number of font-size declarations.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
count = 0;
//check for use of "font-size"
parser.addListener("property", function(event){
if (event.property == "font-size"){
count++;
}
});
//report the results
parser.addListener("endstylesheet", function(){
reporter.stat("font-sizes", count);
if (count >= 10){
reporter.rollupWarn("Too many font-size declarations (" + count + "), abstraction needed.", rule);
}
});
}
});
/*
* Rule: When using a vendor-prefixed gradient, make sure to use them all.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "gradients",
name: "Require all gradient definitions",
desc: "When using a vendor-prefixed gradient, make sure to use them all.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
gradients;
parser.addListener("startrule", function(){
gradients = {
moz: 0,
webkit: 0,
oldWebkit: 0,
ms: 0,
o: 0
};
});
parser.addListener("property", function(event){
if (/\-(moz|ms|o|webkit)(?:\-(?:linear|radial))\-gradient/i.test(event.value)){
gradients[RegExp.$1] = 1;
} else if (/\-webkit\-gradient/i.test(event.value)){
gradients.oldWebkit = 1;
}
});
parser.addListener("endrule", function(event){
var missing = [];
if (!gradients.moz){
missing.push("Firefox 3.6+");
}
if (!gradients.webkit){
missing.push("Webkit (Safari 5+, Chrome)");
}
if (!gradients.oldWebkit){
missing.push("Old Webkit (Safari 4+, Chrome)");
}
if (!gradients.ms){
missing.push("Internet Explorer 10+");
}
if (!gradients.o){
missing.push("Opera 11.1+");
}
if (missing.length && missing.length < 5){
reporter.report("Missing vendor-prefixed CSS gradients for " + missing.join(", ") + ".", event.selectors[0].line, event.selectors[0].col, rule);
}
});
}
});
/*
* Rule: Don't use IDs for selectors.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "ids",
name: "Disallow IDs in selectors",
desc: "Selectors should not contain IDs.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
idCount,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
idCount = 0;
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type == parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type == "id"){
idCount++;
}
}
}
}
if (idCount == 1){
reporter.report("Don't use IDs in selectors.", selector.line, selector.col, rule);
} else if (idCount > 1){
reporter.report(idCount + " IDs in the selector, really?", selector.line, selector.col, rule);
}
}
});
}
});
/*
* Rule: Don't use @import, use <link> instead.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "import",
name: "Disallow @import",
desc: "Don't use @import, use <link> instead.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("import", function(event){
reporter.report("@import prevents parallel downloads, use <link> instead.", event.line, event.col, rule);
});
}
});
/*
* Rule: Make sure !important is not overused, this could lead to specificity
* war. Display a warning on !important declarations, an error if it's
* used more at least 10 times.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "important",
name: "Disallow !important",
desc: "Be careful when using !important declaration",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
count = 0;
//warn that important is used and increment the declaration counter
parser.addListener("property", function(event){
if (event.important === true){
count++;
reporter.report("Use of !important", event.line, event.col, rule);
}
});
//if there are more than 10, show an error
parser.addListener("endstylesheet", function(){
reporter.stat("important", count);
if (count >= 10){
reporter.rollupWarn("Too many !important declarations (" + count + "), try to use less than 10 to avoid specificity issues.", rule);
}
});
}
});
/*
* Rule: Properties should be known (listed in CSS3 specification) or
* be a vendor-prefixed property.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "known-properties",
name: "Require use of known properties",
desc: "Properties should be known (listed in CSS3 specification) or be a vendor-prefixed property.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
// the check is handled entirely by the parser-lib (https://github.com/nzakas/parser-lib)
if (event.invalid) {
reporter.report(event.invalid.message, event.line, event.col, rule);
}
});
}
});
/*
* Rule: outline: none or outline: 0 should only be used in a :focus rule
* and only if there are other properties in the same rule.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "outline-none",
name: "Disallow outline: none",
desc: "Use of outline: none or outline: 0 should be limited to :focus rules.",
browsers: "All",
tags: ["Accessibility"],
//initialization
init: function(parser, reporter){
var rule = this,
lastRule;
function startRule(event){
if (event.selectors){
lastRule = {
line: event.line,
col: event.col,
selectors: event.selectors,
propCount: 0,
outline: false
};
} else {
lastRule = null;
}
}
function endRule(event){
if (lastRule){
if (lastRule.outline){
if (lastRule.selectors.toString().toLowerCase().indexOf(":focus") == -1){
reporter.report("Outlines should only be modified using :focus.", lastRule.line, lastRule.col, rule);
} else if (lastRule.propCount == 1) {
reporter.report("Outlines shouldn't be hidden unless other visual changes are made.", lastRule.line, lastRule.col, rule);
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase(),
value = event.value;
if (lastRule){
lastRule.propCount++;
if (name == "outline" && (value == "none" || value == "0")){
lastRule.outline = true;
}
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endpage", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endkeyframerule", endRule);
}
});
/*
* Rule: Don't use classes or IDs with elements (a.foo or a#foo).
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "overqualified-elements",
name: "Disallow overqualified elements",
desc: "Don't use classes or IDs with elements (a.foo or a#foo).",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
classes = {};
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type == parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (part.elementName && modifier.type == "id"){
reporter.report("Element (" + part + ") is overqualified, just use " + modifier + " without element name.", part.line, part.col, rule);
} else if (modifier.type == "class"){
if (!classes[modifier]){
classes[modifier] = [];
}
classes[modifier].push({ modifier: modifier, part: part });
}
}
}
}
}
});
parser.addListener("endstylesheet", function(){
var prop;
for (prop in classes){
if (classes.hasOwnProperty(prop)){
//one use means that this is overqualified
if (classes[prop].length == 1 && classes[prop][0].part.elementName){
reporter.report("Element (" + classes[prop][0].part + ") is overqualified, just use " + classes[prop][0].modifier + " without element name.", classes[prop][0].part.line, classes[prop][0].part.col, rule);
}
}
}
});
}
});
/*
* Rule: Headings (h1-h6) should not be qualified (namespaced).
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "qualified-headings",
name: "Disallow qualified headings",
desc: "Headings should not be qualified (namespaced).",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
i, j;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type == parser.SELECTOR_PART_TYPE){
if (part.elementName && /h[1-6]/.test(part.elementName.toString()) && j > 0){
reporter.report("Heading (" + part.elementName + ") should not be qualified.", part.line, part.col, rule);
}
}
}
}
});
}
});
/*
* Rule: Selectors that look like regular expressions are slow and should be avoided.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "regex-selectors",
name: "Disallow selectors that look like regexs",
desc: "Selectors that look like regular expressions are slow and should be avoided.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type == parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type == "attribute"){
if (/([\~\|\^\$\*]=)/.test(modifier)){
reporter.report("Attribute selectors with " + RegExp.$1 + " are slow!", modifier.line, modifier.col, rule);
}
}
}
}
}
}
});
}
});
/*
* Rule: Total number of rules should not exceed x.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "rules-count",
name: "Rules Count",
desc: "Track how many rules there are.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
count = 0;
//count each rule
parser.addListener("startrule", function(){
count++;
});
parser.addListener("endstylesheet", function(){
reporter.stat("rule-count", count);
});
}
});
/*
* Rule: Use shorthand properties where possible.
*
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "shorthand",
name: "Require shorthand properties",
desc: "Use shorthand properties where possible.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
prop, i, len,
propertiesToCheck = {},
properties,
mapping = {
"margin": [
"margin-top",
"margin-bottom",
"margin-left",
"margin-right"
],
"padding": [
"padding-top",
"padding-bottom",
"padding-left",
"padding-right"
]
};
//initialize propertiesToCheck
for (prop in mapping){
if (mapping.hasOwnProperty(prop)){
for (i=0, len=mapping[prop].length; i < len; i++){
propertiesToCheck[mapping[prop][i]] = prop;
}
}
}
function startRule(event){
properties = {};
}
//event handler for end of rules
function endRule(event){
var prop, i, len, total;
//check which properties this rule has
for (prop in mapping){
if (mapping.hasOwnProperty(prop)){
total=0;
for (i=0, len=mapping[prop].length; i < len; i++){
total += properties[mapping[prop][i]] ? 1 : 0;
}
if (total == mapping[prop].length){
reporter.report("The properties " + mapping[prop].join(", ") + " can be replaced by " + prop + ".", event.line, event.col, rule);
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
//check for use of "font-size"
parser.addListener("property", function(event){
var name = event.property.toString().toLowerCase(),
value = event.value.parts[0].value;
if (propertiesToCheck[name]){
properties[name] = 1;
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
}
});
/*
* Rule: Don't use properties with a star prefix.
*
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "star-property-hack",
name: "Disallow properties with a star prefix",
desc: "Checks for the star property hack (targets IE6/7)",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
//check if property name starts with "*"
parser.addListener("property", function(event){
var property = event.property;
if (property.hack == "*") {
reporter.report("Property with star prefix found.", event.property.line, event.property.col, rule);
}
});
}
});
/*
* Rule: Don't use text-indent for image replacement if you need to support rtl.
*
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "text-indent",
name: "Disallow negative text-indent",
desc: "Checks for text indent less than -99px",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
textIndent,
direction;
function startRule(event){
textIndent = false;
direction = "inherit";
}
//event handler for end of rules
function endRule(event){
if (textIndent && direction != "ltr"){
reporter.report("Negative text-indent doesn't work well with RTL. If you use text-indent for image replacement explicitly set direction for that item to ltr.", textIndent.line, textIndent.col, rule);
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
//check for use of "font-size"
parser.addListener("property", function(event){
var name = event.property.toString().toLowerCase(),
value = event.value;
if (name == "text-indent" && value.parts[0].value < -99){
textIndent = event.property;
} else if (name == "direction" && value == "ltr"){
direction = "ltr";
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
}
});
/*
* Rule: Don't use properties with a underscore prefix.
*
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "underscore-property-hack",
name: "Disallow properties with an underscore prefix",
desc: "Checks for the underscore property hack (targets IE6)",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
//check if property name starts with "_"
parser.addListener("property", function(event){
var property = event.property;
if (property.hack == "_") {
reporter.report("Property with underscore prefix found.", event.property.line, event.property.col, rule);
}
});
}
});
/*
* Rule: Headings (h1-h6) should be defined only once.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "unique-headings",
name: "Headings should only be defined once",
desc: "Headings should be defined only once.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
var headings = {
h1: 0,
h2: 0,
h3: 0,
h4: 0,
h5: 0,
h6: 0
};
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
pseudo,
i, j;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
part = selector.parts[selector.parts.length-1];
if (part.elementName && /(h[1-6])/i.test(part.elementName.toString())){
for (j=0; j < part.modifiers.length; j++){
if (part.modifiers[j].type == "pseudo"){
pseudo = true;
break;
}
}
if (!pseudo){
headings[RegExp.$1]++;
if (headings[RegExp.$1] > 1) {
reporter.report("Heading (" + part.elementName + ") has already been defined.", part.line, part.col, rule);
}
}
}
}
});
parser.addListener("endstylesheet", function(event){
var prop,
messages = [];
for (prop in headings){
if (headings.hasOwnProperty(prop)){
if (headings[prop] > 1){
messages.push(headings[prop] + " " + prop + "s");
}
}
}
if (messages.length){
reporter.rollupWarn("You have " + messages.join(", ") + " defined in this stylesheet.", rule);
}
});
}
});
/*
* Rule: Don't use universal selector because it's slow.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "universal-selector",
name: "Disallow universal selector",
desc: "The universal selector (*) is known to be slow.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
part = selector.parts[selector.parts.length-1];
if (part.elementName == "*"){
reporter.report(rule.desc, part.line, part.col, rule);
}
}
});
}
});
/*
* Rule: Don't use unqualified attribute selectors because they're just like universal selectors.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "unqualified-attributes",
name: "Disallow unqualified attribute selectors",
desc: "Unqualified attribute selectors are known to be slow.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
part = selector.parts[selector.parts.length-1];
if (part.type == parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type == "attribute" && (!part.elementName || part.elementName == "*")){
reporter.report(rule.desc, part.line, part.col, rule);
}
}
}
}
});
}
});
/*
* Rule: When using a vendor-prefixed property, make sure to
* include the standard one.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "vendor-prefix",
name: "Require standard property with vendor prefix",
desc: "When using a vendor-prefixed property, make sure to include the standard one.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
properties,
num,
propertiesToCheck = {
"-webkit-border-radius": "border-radius",
"-webkit-border-top-left-radius": "border-top-left-radius",
"-webkit-border-top-right-radius": "border-top-right-radius",
"-webkit-border-bottom-left-radius": "border-bottom-left-radius",
"-webkit-border-bottom-right-radius": "border-bottom-right-radius",
"-o-border-radius": "border-radius",
"-o-border-top-left-radius": "border-top-left-radius",
"-o-border-top-right-radius": "border-top-right-radius",
"-o-border-bottom-left-radius": "border-bottom-left-radius",
"-o-border-bottom-right-radius": "border-bottom-right-radius",
"-moz-border-radius": "border-radius",
"-moz-border-radius-topleft": "border-top-left-radius",
"-moz-border-radius-topright": "border-top-right-radius",
"-moz-border-radius-bottomleft": "border-bottom-left-radius",
"-moz-border-radius-bottomright": "border-bottom-right-radius",
"-moz-column-count": "column-count",
"-webkit-column-count": "column-count",
"-moz-column-gap": "column-gap",
"-webkit-column-gap": "column-gap",
"-moz-column-rule": "column-rule",
"-webkit-column-rule": "column-rule",
"-moz-column-rule-style": "column-rule-style",
"-webkit-column-rule-style": "column-rule-style",
"-moz-column-rule-color": "column-rule-color",
"-webkit-column-rule-color": "column-rule-color",
"-moz-column-rule-width": "column-rule-width",
"-webkit-column-rule-width": "column-rule-width",
"-moz-column-width": "column-width",
"-webkit-column-width": "column-width",
"-webkit-column-span": "column-span",
"-webkit-columns": "columns",
"-moz-box-shadow": "box-shadow",
"-webkit-box-shadow": "box-shadow",
"-moz-transform" : "transform",
"-webkit-transform" : "transform",
"-o-transform" : "transform",
"-ms-transform" : "transform",
"-moz-transform-origin" : "transform-origin",
"-webkit-transform-origin" : "transform-origin",
"-o-transform-origin" : "transform-origin",
"-ms-transform-origin" : "transform-origin",
"-moz-box-sizing" : "box-sizing",
"-webkit-box-sizing" : "box-sizing",
"-moz-user-select" : "user-select",
"-khtml-user-select" : "user-select",
"-webkit-user-select" : "user-select"
};
//event handler for beginning of rules
function startRule(){
properties = {};
num=1;
}
//event handler for end of rules
function endRule(event){
var prop,
i, len,
standard,
needed,
actual,
needsStandard = [];
for (prop in properties){
if (propertiesToCheck[prop]){
needsStandard.push({ actual: prop, needed: propertiesToCheck[prop]});
}
}
for (i=0, len=needsStandard.length; i < len; i++){
needed = needsStandard[i].needed;
actual = needsStandard[i].actual;
if (!properties[needed]){
reporter.report("Missing standard property '" + needed + "' to go along with '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule);
} else {
//make sure standard property is last
if (properties[needed][0].pos < properties[actual][0].pos){
reporter.report("Standard property '" + needed + "' should come after vendor-prefixed property '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule);
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (!properties[name]){
properties[name] = [];
}
properties[name].push({ name: event.property, value : event.value, pos:num++ });
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endpage", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endkeyframerule", endRule);
}
});
/*
* Rule: You don't need to specify units when a value is 0.
*/
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "zero-units",
name: "Disallow units for 0 values",
desc: "You don't need to specify units when a value is 0.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
//count how many times "float" is used
parser.addListener("property", function(event){
var parts = event.value.parts,
i = 0,
len = parts.length;
while(i < len){
if ((parts[i].units || parts[i].type == "percentage") && parts[i].value === 0 && parts[i].type != "time"){
reporter.report("Values of 0 shouldn't have units specified.", parts[i].line, parts[i].col, rule);
}
i++;
}
});
}
});
/*global CSSLint*/
(function() {
/**
* Replace special characters before write to output.
*
* Rules:
* - single quotes is the escape sequence for double-quotes
* - & is the escape sequence for &
* - < is the escape sequence for <
* - > is the escape sequence for >
*
* @param {String} message to escape
* @return escaped message as {String}
*/
var xmlEscape = function(str) {
if (!str || str.constructor !== String) {
return "";
}
return str.replace(/[\"&><]/g, function(match) {
switch (match) {
case "\"":
return """;
case "&":
return "&";
case "<":
return "<";
case ">":
return ">";
}
});
};
CSSLint.addFormatter({
//format information
id: "checkstyle-xml",
name: "Checkstyle XML format",
/**
* Return opening root XML tag.
* @return {String} to prepend before all results
*/
startFormat: function(){
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><checkstyle>";
},
/**
* Return closing root XML tag.
* @return {String} to append after all results
*/
endFormat: function(){
return "</checkstyle>";
},
/**
* Returns message when there is a file read error.
* @param {String} filename The name of the file that caused the error.
* @param {String} message The error message
* @return {String} The error message.
*/
readError: function(filename, message) {
return "<file name=\"" + xmlEscape(filename) + "\"><error line=\"0\" column=\"0\" severty=\"error\" message=\"" + xmlEscape(message) + "\"></error></file>";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (UNUSED for now) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = [];
/**
* Generate a source string for a rule.
* Checkstyle source strings usually resemble Java class names e.g
* net.csslint.SomeRuleName
* @param {Object} rule
* @return rule source as {String}
*/
var generateSource = function(rule) {
if (!rule || !('name' in rule)) {
return "";
}
return 'net.csslint.' + rule.name.replace(/\s/g,'');
};
if (messages.length > 0) {
output.push("<file name=\""+filename+"\">");
CSSLint.Util.forEach(messages, function (message, i) {
//ignore rollups for now
if (!message.rollup) {
output.push("<error line=\"" + message.line + "\" column=\"" + message.col + "\" severity=\"" + message.type + "\"" +
" message=\"" + xmlEscape(message.message) + "\" source=\"" + generateSource(message.rule) +"\"/>");
}
});
output.push("</file>");
}
return output.join("");
}
});
}());
/*global CSSLint*/
CSSLint.addFormatter({
//format information
id: "compact",
name: "Compact, 'porcelain' format",
/**
* Return content to be printed before all file results.
* @return {String} to prepend before all results
*/
startFormat: function() {
return "";
},
/**
* Return content to be printed after all file results.
* @return {String} to append after all results
*/
endFormat: function() {
return "";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (Optional) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = "";
options = options || {};
/**
* Capitalize and return given string.
* @param str {String} to capitalize
* @return {String} capitalized
*/
var capitalize = function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
};
if (messages.length === 0) {
return options.quiet ? "" : filename + ": Lint Free!";
}
CSSLint.Util.forEach(messages, function(message, i) {
if (message.rollup) {
output += filename + ": " + capitalize(message.type) + " - " + message.message + "\n";
} else {
output += filename + ": " + "line " + message.line +
", col " + message.col + ", " + capitalize(message.type) + " - " + message.message + "\n";
}
});
return output;
}
});
/*global CSSLint*/
CSSLint.addFormatter({
//format information
id: "csslint-xml",
name: "CSSLint XML format",
/**
* Return opening root XML tag.
* @return {String} to prepend before all results
*/
startFormat: function(){
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><csslint>";
},
/**
* Return closing root XML tag.
* @return {String} to append after all results
*/
endFormat: function(){
return "</csslint>";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (UNUSED for now) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = [];
/**
* Replace special characters before write to output.
*
* Rules:
* - single quotes is the escape sequence for double-quotes
* - & is the escape sequence for &
* - < is the escape sequence for <
* - > is the escape sequence for >
*
* @param {String} message to escape
* @return escaped message as {String}
*/
var escapeSpecialCharacters = function(str) {
if (!str || str.constructor !== String) {
return "";
}
return str.replace(/\"/g, "'").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
};
if (messages.length > 0) {
output.push("<file name=\""+filename+"\">");
CSSLint.Util.forEach(messages, function (message, i) {
if (message.rollup) {
output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
} else {
output.push("<issue line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" +
" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
}
});
output.push("</file>");
}
return output.join("");
}
});
/*global CSSLint*/
CSSLint.addFormatter({
//format information
id: "junit-xml",
name: "JUNIT XML format",
/**
* Return opening root XML tag.
* @return {String} to prepend before all results
*/
startFormat: function(){
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><testsuites>";
},
/**
* Return closing root XML tag.
* @return {String} to append after all results
*/
endFormat: function() {
return "</testsuites>";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (UNUSED for now) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = [],
tests = {
'error': 0,
'failure': 0
};
/**
* Generate a source string for a rule.
* JUNIT source strings usually resemble Java class names e.g
* net.csslint.SomeRuleName
* @param {Object} rule
* @return rule source as {String}
*/
var generateSource = function(rule) {
if (!rule || !('name' in rule)) {
return "";
}
return 'net.csslint.' + rule.name.replace(/\s/g,'');
};
/**
* Replace special characters before write to output.
*
* Rules:
* - single quotes is the escape sequence for double-quotes
* - < is the escape sequence for <
* - > is the escape sequence for >
*
* @param {String} message to escape
* @return escaped message as {String}
*/
var escapeSpecialCharacters = function(str) {
if (!str || str.constructor !== String) {
return "";
}
return str.replace(/\"/g, "'").replace(/</g, "<").replace(/>/g, ">");
};
if (messages.length > 0) {
messages.forEach(function (message, i) {
// since junit has no warning class
// all issues as errors
var type = message.type === 'warning' ? 'error' : message.type;
//ignore rollups for now
if (!message.rollup) {
// build the test case seperately, once joined
// we'll add it to a custom array filtered by type
output.push("<testcase time=\"0\" name=\"" + generateSource(message.rule) + "\">");
output.push("<" + type + " message=\"" + escapeSpecialCharacters(message.message) + "\"><![CDATA[" + message.line + ':' + message.col + ':' + escapeSpecialCharacters(message.evidence) + "]]></" + type + ">");
output.push("</testcase>");
tests[type] += 1;
}
});
output.unshift("<testsuite time=\"0\" tests=\"" + messages.length + "\" skipped=\"0\" errors=\"" + tests.error + "\" failures=\"" + tests.failure + "\" package=\"net.csslint\" name=\"" + filename + "\">");
output.push("</testsuite>");
}
return output.join("");
}
});
/*global CSSLint*/
CSSLint.addFormatter({
//format information
id: "lint-xml",
name: "Lint XML format",
/**
* Return opening root XML tag.
* @return {String} to prepend before all results
*/
startFormat: function(){
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><lint>";
},
/**
* Return closing root XML tag.
* @return {String} to append after all results
*/
endFormat: function(){
return "</lint>";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (UNUSED for now) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = [];
/**
* Replace special characters before write to output.
*
* Rules:
* - single quotes is the escape sequence for double-quotes
* - & is the escape sequence for &
* - < is the escape sequence for <
* - > is the escape sequence for >
*
* @param {String} message to escape
* @return escaped message as {String}
*/
var escapeSpecialCharacters = function(str) {
if (!str || str.constructor !== String) {
return "";
}
return str.replace(/\"/g, "'").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
};
if (messages.length > 0) {
output.push("<file name=\""+filename+"\">");
CSSLint.Util.forEach(messages, function (message, i) {
if (message.rollup) {
output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
} else {
output.push("<issue line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" +
" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
}
});
output.push("</file>");
}
return output.join("");
}
});
/*global CSSLint*/
CSSLint.addFormatter({
//format information
id: "text",
name: "Plain Text",
/**
* Return content to be printed before all file results.
* @return {String} to prepend before all results
*/
startFormat: function() {
return "";
},
/**
* Return content to be printed after all file results.
* @return {String} to append after all results
*/
endFormat: function() {
return "";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (Optional) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = "";
options = options || {};
if (messages.length === 0) {
return options.quiet ? "" : "\n\ncsslint: No errors in " + filename + ".";
}
output = "\n\ncsslint: There are " + messages.length + " problems in " + filename + ".";
var pos = filename.lastIndexOf("/"),
shortFilename = filename;
if (pos === -1){
pos = filename.lastIndexOf("\\");
}
if (pos > -1){
shortFilename = filename.substring(pos+1);
}
CSSLint.Util.forEach(messages, function (message, i) {
output = output + "\n\n" + shortFilename;
if (message.rollup) {
output += "\n" + (i+1) + ": " + message.type;
output += "\n" + message.message;
} else {
output += "\n" + (i+1) + ": " + message.type + " at line " + message.line + ", col " + message.col;
output += "\n" + message.message;
output += "\n" + message.evidence;
}
});
return output;
}
});
return CSSLint;
})();
|
const exec = require('child_process').exec;
module.exports = {
onLivingRoomLightOn,
onLivingRoomLightOff,
};
function onLivingRoomLightOn() {
return exec(`sudo ${__dirname}/../../lib/scripts/Emetteur 3 ${__dirname}/../../lib/actions/livingRoom/LightOn.csv`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
}
function onLivingRoomLightOff() {
return exec(`sudo ${__dirname}/../../lib/scripts/Emetteur 3 ${__dirname}/../../lib/actions/livingRoom/LightOff.csv`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
}
|
import {StyleSheet} from 'react-native'
const styles = StyleSheet.create({
container: {
flex: 1
}
})
export default styles
|
/* eslint-disable */
() => {
const filterOptions = [
{ id: 'In Stock, Out Of Stock', value: 'In Stock, Out Of Stock' },
{ id: 'In Stock', value: 'In Stock' },
{ id: 'Out Of Stock', value: 'Out Of Stock' },
];
const [activeFilter, setActiveFilter] = React.useState(filterOptions[0].id);
const [searchTerm, setSearchTerm] = React.useState('');
const [records, setRecords] = React.useState([
{
name: 'Red Slippers',
SKU: '0231664667',
price: '$14.00',
inventory: 'In Stock',
},
{
name: 'Velvet Hat',
SKU: '0231664669',
price: '$23.00',
inventory: 'In Stock',
},
{
name: 'Silver Jeans',
SKU: '0231664667',
price: '$69.00',
inventory: 'In Stock',
},
{
name: 'Orange Stocks',
SKU: '0231664671',
price: '$9.00',
inventory: 'Out Of Stock',
},
{
name: 'Black T-shirts',
SKU: '0231664672',
price: '$19.00',
inventory: 'In Stock',
},
]);
const columns = [
{
title: 'Name',
render: row => <Highlighter match={searchTerm}>{row.name}</Highlighter>,
width: '30%',
},
{
title: 'SKU',
render: row => row.SKU,
width: '20%',
},
{
title: 'Price',
render: row => row.price,
width: '20%',
},
{
title: 'Inventory',
render: row => row.inventory,
width: '20%',
},
];
const _getFilteredData = () => {
let filteredData = records.concat(records);
if (activeFilter !== 'In Stock, Out Of Stock') {
filteredData = filteredData.filter(row => row.inventory === activeFilter);
}
if (searchTerm !== '') {
filteredData = filteredData.filter(row =>
row.name.toUpperCase().includes(searchTerm.toUpperCase()),
);
}
return filteredData;
};
const filteredData = _getFilteredData();
const _clearSearch = () => {
setSearchTerm('');
};
const _renderSearch = expandable => {
return (
<Search
expandable={expandable}
onChange={e => {
setSearchTerm(e.target.value);
}}
value={searchTerm}
onClear={_clearSearch}
/>
);
};
const _renderEmptyState = () => (
<Table.EmptyState
title="You haven't added any items yet"
subtitle="Add items to your website so people can buy them"
image={
<Box
height={120}
width={120}
backgroundColor="#dfe5eb"
borderRadius="50%"
/>
}
>
<TextButton suffixIcon={<Icons.ExternalLink />}>
Learn how to add items
</TextButton>
</Table.EmptyState>
);
const _renderMainToolbar = () => {
return (
<Card>
<TableToolbar>
<TableToolbar.ItemGroup position="start">
<TableToolbar.Item>
<TableToolbar.Label>
Status
<span style={{ width: '150px' }}>
<Dropdown
options={filterOptions}
selectedId={activeFilter}
onSelect={selectedOption => {
console.log(selectedOption);
setActiveFilter(selectedOption.value);
}}
roundInput
/>
</span>
</TableToolbar.Label>
</TableToolbar.Item>
<TableToolbar.Item>
<TableToolbar.Label>
Category
<span style={{ width: '150px' }}>
<Dropdown
options={[{ id: 0, value: 'All categories' }]}
selectedId={0}
roundInput
/>
</span>
</TableToolbar.Label>
</TableToolbar.Item>
</TableToolbar.ItemGroup>
<TableToolbar.ItemGroup position="end">
<TableToolbar.Item>{_renderSearch(false)}</TableToolbar.Item>
</TableToolbar.ItemGroup>
</TableToolbar>
</Card>
);
};
return (
<Page height="600px">
<Page.Header
title="Products"
actionsBar={
<Box>
<Box padding="SP1">
<IconButton skin="inverted">
<Icons.More />
</IconButton>{' '}
</Box>
<Box padding="SP1">
<Button prefixIcon={<Icons.Add />}>Add Product</Button>{' '}
</Box>
</Box>
}
/>
<Page.Content>
<Table
data={filteredData}
columns={columns}
onSelectionChange={selectedIds =>
console.log('Table.onSelectionChange(): selectedIds=', selectedIds)
}
showSelection
>
<Page.Sticky>
<Card>
<Table.ToolbarContainer>
{selectionContext =>
selectionContext.selectedCount === 0
? _renderMainToolbar()
: this._renderActionsToolbar({ ...selectionContext })
}
</Table.ToolbarContainer>
<Table.SubToolbar>
<FormField label="Filtered by:" labelPlacement="left">
<TagList
tags={[
{ id: '1', children: 'In Stock' },
{ id: '2', children: 'Out Of Stock' },
]}
maxVisibleTags={2}
actionButton={{ label: 'Clear All', onClick: () => {} }}
/>
</FormField>
</Table.SubToolbar>
{filteredData.length ? <Table.Titlebar /> : _renderEmptyState()}
</Card>
</Page.Sticky>
<Card>
<Table.Content titleBarVisible={false} />
</Card>
</Table>
</Page.Content>
</Page>
);
const _renderActionsToolbar = ({ selectedCount, getSelectedIds }) => {
return (
<TableToolbar>
<TableToolbar.ItemGroup position="start">
<TableToolbar.Item>
<TableToolbar.SelectedCount>{`${selectedCount} Selected`}</TableToolbar.SelectedCount>
</TableToolbar.Item>
</TableToolbar.ItemGroup>
<TableToolbar.ItemGroup position="end">
<TableToolbar.Item layout="button">
<Button
skin="light"
priority="primary"
prefixIcon={<Icons.Upload />}
onClick={() =>
window.alert(`Exporting selectedIds=${getSelectedIds()}`)
}
>
Export
</Button>
</TableToolbar.Item>
<TableToolbar.Item layout="button">
<Button
skin="light"
priority="primary"
prefixIcon={<Icons.Duplicate />}
onClick={() =>
window.alert(`Duplicating selectedIds=${getSelectedIds()}`)
}
>
Duplicate
</Button>
</TableToolbar.Item>
<TableToolbar.Item layout="button">
<Button
skin="light"
priority="primary"
prefixIcon={<Icons.Edit />}
onClick={() =>
window.alert(`Editing selectedIds=${getSelectedIds()}`)
}
>
Edit
</Button>
</TableToolbar.Item>
<TableToolbar.Divider />
<TableToolbar.Item>{this._renderSearch(true)}</TableToolbar.Item>
</TableToolbar.ItemGroup>
</TableToolbar>
);
};
};
|
module.exports = {
test: {
src: [
'test/vendor/assert.js',
'test/test-adapter.js',
'transpiled/tests.cjs.js'
],
options: {
reporter: 'spec'
}
}
}; |
import { Map } from 'immutable';
const BLOCK_MAP = Map({
'header-one': {
element: 'h1',
},
'header-two': {
element: 'h2',
},
'header-three': {
element: 'h3',
},
'header-four': {
element: 'h4',
},
'header-five': {
element: 'h5',
},
'header-six': {
element: 'h6',
},
blockquote: {
element: 'blockquote',
},
'code-block': {
element: 'pre',
},
atomic: {
element: 'figure',
},
'unordered-list-item': {
element: 'li',
},
'ordered-list-item': {
element: 'li',
},
unstyled: {
element: 'div',
},
});
export default BLOCK_MAP;
|
var _base = require('./bog.domain.repositories._base.js');
var StatusDataRepo = require('../../data/repositories/bog.data.repositories.status');
var StatusRepository = function (current_user) {
var self = this;
var user = current_user;
// Return All Items
var All = function (callback) {
var dataRepo = new StatusDataRepo();
dataRepo.all(function (err, coll) {
if (err) {
callback(self.err.wrap(1001, null, err));
} else {
callback(null, coll);
}
});
};
return {
all: All
};
};
StatusRepository.prototype = new _base();
module.exports = StatusRepository; |
/* */
"format cjs";
;
(function(factory) {
var objectTypes = {
'function': true,
'object': true
};
function checkGlobal(value) {
return (value && value.Object === Object) ? value : null;
}
var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null;
var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null;
var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global);
var freeSelf = checkGlobal(objectTypes[typeof self] && self);
var freeWindow = checkGlobal(objectTypes[typeof window] && window);
var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null;
var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')();
if (typeof define === 'function' && define.amd) {
define(['./rx'], function(Rx, exports) {
return factory(root, exports, 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) {
var Observable = Rx.Observable,
observableProto = Observable.prototype,
AnonymousObservable = Rx.AnonymousObservable,
ObservableBase = Rx.ObservableBase,
Subject = Rx.Subject,
AsyncSubject = Rx.AsyncSubject,
Observer = Rx.Observer,
ScheduledObserver = Rx.internals.ScheduledObserver,
disposableCreate = Rx.Disposable.create,
disposableEmpty = Rx.Disposable.empty,
BinaryDisposable = Rx.BinaryDisposable,
currentThreadScheduler = Rx.Scheduler.currentThread,
isFunction = Rx.helpers.isFunction,
inherits = Rx.internals.inherits,
addProperties = Rx.internals.addProperties,
checkDisposed = Rx.Disposable.checkDisposed;
function cloneArray(arr) {
var len = arr.length,
a = new Array(len);
for (var i = 0; i < len; i++) {
a[i] = arr[i];
}
return a;
}
var MulticastObservable = (function(__super__) {
inherits(MulticastObservable, __super__);
function MulticastObservable(source, fn1, fn2) {
this.source = source;
this._fn1 = fn1;
this._fn2 = fn2;
__super__.call(this);
}
MulticastObservable.prototype.subscribeCore = function(o) {
var connectable = this.source.multicast(this._fn1());
return new BinaryDisposable(this._fn2(connectable).subscribe(o), connectable.connect());
};
return MulticastObservable;
}(ObservableBase));
observableProto.multicast = function(subjectOrSubjectSelector, selector) {
return isFunction(subjectOrSubjectSelector) ? new MulticastObservable(this, subjectOrSubjectSelector, selector) : new ConnectableObservable(this, subjectOrSubjectSelector);
};
observableProto.publish = function(selector) {
return selector && isFunction(selector) ? this.multicast(function() {
return new Subject();
}, selector) : this.multicast(new Subject());
};
observableProto.share = function() {
return this.publish().refCount();
};
observableProto.publishLast = function(selector) {
return selector && isFunction(selector) ? this.multicast(function() {
return new AsyncSubject();
}, selector) : this.multicast(new AsyncSubject());
};
observableProto.publishValue = function(initialValueOrSelector, initialValue) {
return arguments.length === 2 ? this.multicast(function() {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector));
};
observableProto.shareValue = function(initialValue) {
return this.publishValue(initialValue).refCount();
};
observableProto.replay = function(selector, bufferSize, windowSize, scheduler) {
return selector && isFunction(selector) ? this.multicast(function() {
return new ReplaySubject(bufferSize, windowSize, scheduler);
}, selector) : this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler));
};
observableProto.shareReplay = function(bufferSize, windowSize, scheduler) {
return this.replay(null, bufferSize, windowSize, scheduler).refCount();
};
var InnerSubscription = function(s, o) {
this._s = s;
this._o = o;
};
InnerSubscription.prototype.dispose = function() {
if (!this._s.isDisposed && this._o !== null) {
var idx = this._s.observers.indexOf(this._o);
this._s.observers.splice(idx, 1);
this._o = null;
}
};
var BehaviorSubject = Rx.BehaviorSubject = (function(__super__) {
inherits(BehaviorSubject, __super__);
function BehaviorSubject(value) {
__super__.call(this);
this.value = value;
this.observers = [];
this.isDisposed = false;
this.isStopped = false;
this.hasError = false;
}
addProperties(BehaviorSubject.prototype, Observer.prototype, {
_subscribe: function(o) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(o);
o.onNext(this.value);
return new InnerSubscription(this, o);
}
if (this.hasError) {
o.onError(this.error);
} else {
o.onCompleted();
}
return disposableEmpty;
},
getValue: function() {
checkDisposed(this);
if (this.hasError) {
thrower(this.error);
}
return this.value;
},
hasObservers: function() {
return this.observers.length > 0;
},
onCompleted: function() {
checkDisposed(this);
if (this.isStopped) {
return;
}
this.isStopped = true;
for (var i = 0,
os = cloneArray(this.observers),
len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
},
onError: function(error) {
checkDisposed(this);
if (this.isStopped) {
return;
}
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0,
os = cloneArray(this.observers),
len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
},
onNext: function(value) {
checkDisposed(this);
if (this.isStopped) {
return;
}
this.value = value;
for (var i = 0,
os = cloneArray(this.observers),
len = os.length; i < len; i++) {
os[i].onNext(value);
}
},
dispose: function() {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.error = null;
}
});
return BehaviorSubject;
}(Observable));
var ReplaySubject = Rx.ReplaySubject = (function(__super__) {
var maxSafeInteger = Math.pow(2, 53) - 1;
function createRemovableDisposable(subject, observer) {
return disposableCreate(function() {
observer.dispose();
!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
});
}
inherits(ReplaySubject, __super__);
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize;
this.windowSize = windowSize == null ? maxSafeInteger : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
__super__.call(this);
}
addProperties(ReplaySubject.prototype, Observer.prototype, {
_subscribe: function(o) {
checkDisposed(this);
var so = new ScheduledObserver(this.scheduler, o),
subscription = createRemovableDisposable(this, so);
this._trim(this.scheduler.now());
this.observers.push(so);
for (var i = 0,
len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
so.onError(this.error);
} else if (this.isStopped) {
so.onCompleted();
}
so.ensureActive();
return subscription;
},
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();
}
},
onNext: function(value) {
checkDisposed(this);
if (this.isStopped) {
return;
}
var now = this.scheduler.now();
this.q.push({
interval: now,
value: value
});
this._trim(now);
for (var i = 0,
os = cloneArray(this.observers),
len = os.length; i < len; i++) {
var observer = os[i];
observer.onNext(value);
observer.ensureActive();
}
},
onError: function(error) {
checkDisposed(this);
if (this.isStopped) {
return;
}
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0,
os = cloneArray(this.observers),
len = os.length; i < len; i++) {
var observer = os[i];
observer.onError(error);
observer.ensureActive();
}
this.observers.length = 0;
},
onCompleted: function() {
checkDisposed(this);
if (this.isStopped) {
return;
}
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0,
os = cloneArray(this.observers),
len = os.length; i < len; i++) {
var observer = os[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers.length = 0;
},
dispose: function() {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
var RefCountObservable = (function(__super__) {
inherits(RefCountObservable, __super__);
function RefCountObservable(source) {
this.source = source;
this._count = 0;
this._connectableSubscription = null;
__super__.call(this);
}
RefCountObservable.prototype.subscribeCore = function(o) {
var subscription = this.source.subscribe(o);
++this._count === 1 && (this._connectableSubscription = this.source.connect());
return new RefCountDisposable(this, subscription);
};
function RefCountDisposable(p, s) {
this._p = p;
this._s = s;
this.isDisposed = false;
}
RefCountDisposable.prototype.dispose = function() {
if (!this.isDisposed) {
this.isDisposed = true;
this._s.dispose();
--this._p._count === 0 && this._p._connectableSubscription.dispose();
}
};
return RefCountObservable;
}(ObservableBase));
var ConnectableObservable = Rx.ConnectableObservable = (function(__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
this.source = source;
this._connection = null;
this._source = source.asObservable();
this._subject = subject;
__super__.call(this);
}
function ConnectDisposable(parent, subscription) {
this._p = parent;
this._s = subscription;
}
ConnectDisposable.prototype.dispose = function() {
if (this._s) {
this._s.dispose();
this._s = null;
this._p._connection = null;
}
};
ConnectableObservable.prototype.connect = function() {
if (!this._connection) {
var subscription = this._source.subscribe(this._subject);
this._connection = new ConnectDisposable(this, subscription);
}
return this._connection;
};
ConnectableObservable.prototype._subscribe = function(o) {
return this._subject.subscribe(o);
};
ConnectableObservable.prototype.refCount = function() {
return new RefCountObservable(this);
};
return ConnectableObservable;
}(Observable));
observableProto.singleInstance = function() {
var source = this,
hasObservable = false,
observable;
function getObservable() {
if (!hasObservable) {
hasObservable = true;
observable = source['finally'](function() {
hasObservable = false;
}).publish().refCount();
}
return observable;
}
return new AnonymousObservable(function(o) {
return getObservable().subscribe(o);
});
};
return Rx;
}));
|
var utils = {
handleError: function(dataToLogToConsole, errorMessage, errorObj) {
console.log(dataToLogToConsole || errorMessage);
if (errorMessage) {
var alertMessage = errorMessage;
// if error object is passed, then append error message in the error object
if (errorObj && errorObj.hasOwnProperty('message')) {
// message returned from the server is actually stringified json. Try to parse it as json
// It contains code and message
var errorJSON = JSON.parse(errorObj.message);
if (errorJSON.hasOwnProperty('message')) {
alertMessage += ". " + errorJSON.message;
}
else {
alertMessage += ". " + errorObj.message;
}
}
alert(alertMessage);
}
}
}
module.exports = utils;
|
(function($){
$(function(){
triggerNavigation();
triggerScrollTop();
triggerTooltips();
initMQ();
});
function autoplayVideo(video, autoplay) {
autoplay = autoplay || false;
var $carousel = $('.carousel');
$carousel.on('slide.bs.carousel', function(e) {
video.pause();
});
$(video).on('ended', function (e) {
setTimeout(function () {
$carousel.carousel('next');
$carousel.carousel('cycle');
}, 1000);
});
if (autoplay) {
$(window).on('scroll.video.trigger resize.video.trigger', function () {
if ($(video).isOnScreen(0.8)) {
$(window).off('scroll.video.trigger resize.video.trigger');
video.play();
}
});
}
}
function triggerNavigation() {
var $nav_trigger = $('.js-navi-trigger');
$nav_trigger.on('mouseenter', function (e) {
$('#'+$(this).data('trigger')).addClass('navi-open-icons');
});
$nav_trigger.on('mouseleave', function (e) {
$('#'+$(this).data('trigger')).removeClass('navi-open-icons');
});
$nav = $('.js-nav');
$nav.on('mouseenter', function (e) {
$(this).addClass('navi-open-full');
});
$nav.on('mouseleave', function (e) {
$(this).removeClass('navi-open-full');
});
}
function triggerScrollTop() {
var $up_trigger = $('.js-up-trigger');
$up_trigger.hide().on('click', function (e) {
e.preventDefault();
$('html, body').animate({ scrollTop: 0 }, 500);
});
$(window).on('scroll.up.trigger resize.up.trigger', function () {
if ($(this).scrollTop() > $(this).outerHeight() / 2) {
$up_trigger.fadeIn();
} else {
$up_trigger.fadeOut();
}
});
}
function triggerTooltips() {
$('[data-toggle="tooltip"]').tooltip();
}
function initMQ() {
var queries = [
{
context: 'default',
match: function() {
$('img').each(function() {
if (typeof $(this).data('default') == 'undefined') $(this).attr('data-default', $(this).attr('src'));
var small = $(this).data('default');
if (small) $(this).attr('src', small);
});
}
},
{
context: 'medium',
match: function() {
$('img').each(function() {
if (typeof $(this).data('default') == 'undefined') $(this).attr('data-default', $(this).attr('src'));
var medium = $(this).data('medium');
if (medium) $(this).attr('src', medium);
});
}
},
{
context: 'wide',
match: function() {
$('img').each(function() {
if (typeof $(this).data('default') == 'undefined') $(this).attr('data-default', $(this).attr('src'));
var large = $(this).data('large');
if (large) $(this).attr('src', large);
});
}
}
];
MQ.init(queries);
}
$.fn.isOnScreen = function(percentage) {
percentage = percentage || 0;
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
var height = this.outerHeight();
var width = this.outerWidth();
bounds.right = bounds.left + height;
bounds.bottom = bounds.top + width;
return (!(
viewport.right < bounds.left + width * percentage ||
viewport.left > bounds.right - width * percentage ||
viewport.bottom < bounds.top + height * percentage ||
viewport.top > bounds.bottom - height * percentage
));
};
})(window.jQuery); |
module.exports = MnInputCustomElement()
function MnInputCustomElement() {
const supportsCustomElements = 'customElements' in window
if (!supportsCustomElements) {
require('@webcomponents/custom-elements')
}
if (!window.customElements.get('mn-input')) {
window.customElements.define('mn-input', require('./input.class.js'))
}
return window.customElements.get('mn-input')
}
|
( function () { 'use strict';
function isPlainObject(stuff) {
if (
typeof stuff !== 'object' || stuff === null // Не объект
|| stuff === stuff.window // window
|| stuff.nodeType // DOM node
|| !stuff.constructor
|| !stuff.constructor.prototype.hasOwnProperty('isPrototypeOf')
// Проверка, что прототип объекта равняется "Object.prototype"
) {
return false;
} else {
return true;
}
}
Object.defineProperty( Object, 'isPlainObject', { value: isPlainObject } );
} () );
|
global.SETTINGS = require('./settings');
global.log = require('./lib/log');
let app = require('./lib/server');
app.listen(SETTINGS.PORT, () => {
log.info(`#server Listening on port ${SETTINGS.PORT}`);
});
|
define(['underscore', 'util', 'collection/abstract'],
function(_, Util, AbstractCollection)
{
'use strict';
var _parent = AbstractCollection.prototype;
var ArrayCollection = Util.extend(AbstractCollection, {
_registry: null,
create: function() {
var me = this;
_parent.create.apply(me, arguments);
me._registry = [];
},
add: function(item) {
var me = this;
if (arguments.length > 1) {
_.each(arguments, function(arg) {
me.add(arg)
});
return;
}
if (!_.contains(me._registry, item)) {
me._registry.push(item);
_parent.add.apply(me, arguments);
}
},
remove: function(item) {
var me = this;
if (arguments.length > 1) {
_.each(arguments, function(arg) {
me.remove(arg);
});
return;
}
var index = _.indexOf(me._registry, item);
if (index >= 0) {
me._registry.splice(index, 1);
_parent.remove.apply(me, arguments);
}
},
each: function(iterator) {
_.each(this._registry, iterator);
},
some: function(iterator) {
return _.some(this._registry, iterator);
},
count: function() {
return this._registry.length;
},
getAll: function() {
return this._map.slice();
}
});
return ArrayCollection;
}); |
(function(global) {
var LiteGraph = global.LiteGraph;
function GamepadInput() {
this.addOutput("left_x_axis", "number");
this.addOutput("left_y_axis", "number");
this.addOutput("button_pressed", LiteGraph.EVENT);
this.properties = { gamepad_index: 0, threshold: 0.1 };
this._left_axis = new Float32Array(2);
this._right_axis = new Float32Array(2);
this._triggers = new Float32Array(2);
this._previous_buttons = new Uint8Array(17);
this._current_buttons = new Uint8Array(17);
}
GamepadInput.title = "Gamepad";
GamepadInput.desc = "gets the input of the gamepad";
GamepadInput.CENTER = 0;
GamepadInput.LEFT = 1;
GamepadInput.RIGHT = 2;
GamepadInput.UP = 4;
GamepadInput.DOWN = 8;
GamepadInput.zero = new Float32Array(2);
GamepadInput.buttons = [
"a",
"b",
"x",
"y",
"lb",
"rb",
"lt",
"rt",
"back",
"start",
"ls",
"rs",
"home"
];
GamepadInput.prototype.onExecute = function() {
//get gamepad
var gamepad = this.getGamepad();
var threshold = this.properties.threshold || 0.0;
if (gamepad) {
this._left_axis[0] =
Math.abs(gamepad.xbox.axes["lx"]) > threshold
? gamepad.xbox.axes["lx"]
: 0;
this._left_axis[1] =
Math.abs(gamepad.xbox.axes["ly"]) > threshold
? gamepad.xbox.axes["ly"]
: 0;
this._right_axis[0] =
Math.abs(gamepad.xbox.axes["rx"]) > threshold
? gamepad.xbox.axes["rx"]
: 0;
this._right_axis[1] =
Math.abs(gamepad.xbox.axes["ry"]) > threshold
? gamepad.xbox.axes["ry"]
: 0;
this._triggers[0] =
Math.abs(gamepad.xbox.axes["ltrigger"]) > threshold
? gamepad.xbox.axes["ltrigger"]
: 0;
this._triggers[1] =
Math.abs(gamepad.xbox.axes["rtrigger"]) > threshold
? gamepad.xbox.axes["rtrigger"]
: 0;
}
if (this.outputs) {
for (var i = 0; i < this.outputs.length; i++) {
var output = this.outputs[i];
if (!output.links || !output.links.length) {
continue;
}
var v = null;
if (gamepad) {
switch (output.name) {
case "left_axis":
v = this._left_axis;
break;
case "right_axis":
v = this._right_axis;
break;
case "left_x_axis":
v = this._left_axis[0];
break;
case "left_y_axis":
v = this._left_axis[1];
break;
case "right_x_axis":
v = this._right_axis[0];
break;
case "right_y_axis":
v = this._right_axis[1];
break;
case "trigger_left":
v = this._triggers[0];
break;
case "trigger_right":
v = this._triggers[1];
break;
case "a_button":
v = gamepad.xbox.buttons["a"] ? 1 : 0;
break;
case "b_button":
v = gamepad.xbox.buttons["b"] ? 1 : 0;
break;
case "x_button":
v = gamepad.xbox.buttons["x"] ? 1 : 0;
break;
case "y_button":
v = gamepad.xbox.buttons["y"] ? 1 : 0;
break;
case "lb_button":
v = gamepad.xbox.buttons["lb"] ? 1 : 0;
break;
case "rb_button":
v = gamepad.xbox.buttons["rb"] ? 1 : 0;
break;
case "ls_button":
v = gamepad.xbox.buttons["ls"] ? 1 : 0;
break;
case "rs_button":
v = gamepad.xbox.buttons["rs"] ? 1 : 0;
break;
case "hat_left":
v = gamepad.xbox.hatmap & GamepadInput.LEFT;
break;
case "hat_right":
v = gamepad.xbox.hatmap & GamepadInput.RIGHT;
break;
case "hat_up":
v = gamepad.xbox.hatmap & GamepadInput.UP;
break;
case "hat_down":
v = gamepad.xbox.hatmap & GamepadInput.DOWN;
break;
case "hat":
v = gamepad.xbox.hatmap;
break;
case "start_button":
v = gamepad.xbox.buttons["start"] ? 1 : 0;
break;
case "back_button":
v = gamepad.xbox.buttons["back"] ? 1 : 0;
break;
case "button_pressed":
for (
var j = 0;
j < this._current_buttons.length;
++j
) {
if (
this._current_buttons[j] &&
!this._previous_buttons[j]
) {
this.triggerSlot(
i,
GamepadInput.buttons[j]
);
}
}
break;
default:
break;
}
} else {
//if no gamepad is connected, output 0
switch (output.name) {
case "button_pressed":
break;
case "left_axis":
case "right_axis":
v = GamepadInput.zero;
break;
default:
v = 0;
}
}
this.setOutputData(i, v);
}
}
};
GamepadInput.mapping = {a:0,b:1,x:2,y:3,lb:4,rb:5,lt:6,rt:7,back:8,start:9,ls:10,rs:11 };
GamepadInput.mapping_array = ["a","b","x","y","lb","rb","lt","rt","back","start","ls","rs"];
GamepadInput.prototype.getGamepad = function() {
var getGamepads =
navigator.getGamepads ||
navigator.webkitGetGamepads ||
navigator.mozGetGamepads;
if (!getGamepads) {
return null;
}
var gamepads = getGamepads.call(navigator);
var gamepad = null;
this._previous_buttons.set(this._current_buttons);
//pick the first connected
for (var i = this.properties.gamepad_index; i < 4; i++) {
if (!gamepads[i]) {
continue;
}
gamepad = gamepads[i];
//xbox controller mapping
var xbox = this.xbox_mapping;
if (!xbox) {
xbox = this.xbox_mapping = {
axes: [],
buttons: {},
hat: "",
hatmap: GamepadInput.CENTER
};
}
xbox.axes["lx"] = gamepad.axes[0];
xbox.axes["ly"] = gamepad.axes[1];
xbox.axes["rx"] = gamepad.axes[2];
xbox.axes["ry"] = gamepad.axes[3];
xbox.axes["ltrigger"] = gamepad.buttons[6].value;
xbox.axes["rtrigger"] = gamepad.buttons[7].value;
xbox.hat = "";
xbox.hatmap = GamepadInput.CENTER;
for (var j = 0; j < gamepad.buttons.length; j++) {
this._current_buttons[j] = gamepad.buttons[j].pressed;
if(j < 12)
{
xbox.buttons[ GamepadInput.mapping_array[j] ] = gamepad.buttons[j].pressed;
if(gamepad.buttons[j].was_pressed)
this.trigger( GamepadInput.mapping_array[j] + "_button_event" );
}
else //mapping of XBOX
switch ( j ) //I use a switch to ensure that a player with another gamepad could play
{
case 12:
if (gamepad.buttons[j].pressed) {
xbox.hat += "up";
xbox.hatmap |= GamepadInput.UP;
}
break;
case 13:
if (gamepad.buttons[j].pressed) {
xbox.hat += "down";
xbox.hatmap |= GamepadInput.DOWN;
}
break;
case 14:
if (gamepad.buttons[j].pressed) {
xbox.hat += "left";
xbox.hatmap |= GamepadInput.LEFT;
}
break;
case 15:
if (gamepad.buttons[j].pressed) {
xbox.hat += "right";
xbox.hatmap |= GamepadInput.RIGHT;
}
break;
case 16:
xbox.buttons["home"] = gamepad.buttons[j].pressed;
break;
default:
}
}
gamepad.xbox = xbox;
return gamepad;
}
};
GamepadInput.prototype.onDrawBackground = function(ctx) {
if (this.flags.collapsed) {
return;
}
//render gamepad state?
var la = this._left_axis;
var ra = this._right_axis;
ctx.strokeStyle = "#88A";
ctx.strokeRect(
(la[0] + 1) * 0.5 * this.size[0] - 4,
(la[1] + 1) * 0.5 * this.size[1] - 4,
8,
8
);
ctx.strokeStyle = "#8A8";
ctx.strokeRect(
(ra[0] + 1) * 0.5 * this.size[0] - 4,
(ra[1] + 1) * 0.5 * this.size[1] - 4,
8,
8
);
var h = this.size[1] / this._current_buttons.length;
ctx.fillStyle = "#AEB";
for (var i = 0; i < this._current_buttons.length; ++i) {
if (this._current_buttons[i]) {
ctx.fillRect(0, h * i, 6, h);
}
}
};
GamepadInput.prototype.onGetOutputs = function() {
return [
["left_axis", "vec2"],
["right_axis", "vec2"],
["left_x_axis", "number"],
["left_y_axis", "number"],
["right_x_axis", "number"],
["right_y_axis", "number"],
["trigger_left", "number"],
["trigger_right", "number"],
["a_button", "number"],
["b_button", "number"],
["x_button", "number"],
["y_button", "number"],
["lb_button", "number"],
["rb_button", "number"],
["ls_button", "number"],
["rs_button", "number"],
["start_button", "number"],
["back_button", "number"],
["a_button_event", LiteGraph.EVENT ],
["b_button_event", LiteGraph.EVENT ],
["x_button_event", LiteGraph.EVENT ],
["y_button_event", LiteGraph.EVENT ],
["lb_button_event", LiteGraph.EVENT ],
["rb_button_event", LiteGraph.EVENT ],
["ls_button_event", LiteGraph.EVENT ],
["rs_button_event", LiteGraph.EVENT ],
["start_button_event", LiteGraph.EVENT ],
["back_button_event", LiteGraph.EVENT ],
["hat_left", "number"],
["hat_right", "number"],
["hat_up", "number"],
["hat_down", "number"],
["hat", "number"],
["button_pressed", LiteGraph.EVENT]
];
};
LiteGraph.registerNodeType("input/gamepad", GamepadInput);
})(this);
|
var ViewportContainers = function ( editor ) {
var container = new UI.Panel();
container.setId( 'ViewportContainers' );
return container;
};
|
import view from './views/home'
export { view }
|
/*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* sisane: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Angular.js 1.x & sisane-server
* sisane is distributed under the MIT License (MIT)
* Sources at https://github.com/rafaelaznar/
*
* 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.
*
*/
'use strict';
moduloEstado.controller('EstadoViewController', ['$scope', '$routeParams', 'serverService', '$location', 'estadoService', '$uibModal',
function ($scope, $routeParams, serverService, $location, estadoService, $uibModal) {
$scope.fields = estadoService.getFields();
$scope.obtitle = estadoService.getObTitle();
$scope.icon = estadoService.getIcon();
$scope.ob = estadoService.getTitle();
$scope.title = "Vista de " + $scope.obtitle;
$scope.id = $routeParams.id;
$scope.status = null;
$scope.debugging = serverService.debugging();
serverService.promise_getOne($scope.ob, $scope.id).then(function (response) {
if (response.status == 200) {
if (response.data.status == 200) {
$scope.status = null;
$scope.bean = response.data.message;
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
}).catch(function (data) {
$scope.status = "Error en la recepción de datos del servidor";
});
$scope.close = function () {
$location.path('/home');
};
$scope.plist = function () {
$location.path('/' + $scope.ob + '/plist');
};
$scope.back = function () {
window.history.back();
};
}]); |
// Copyright (c) 2015 Uber Technologies, Inc.
//
// 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.
'use strict';
var DebugLogtron = require('debug-logtron');
var fs = require('fs');
var crypto = require('crypto');
var HyperbahnClient = require('tchannel/hyperbahn/index.js');
module.exports = runTests;
if (require.main === module) {
runTests(require('../lib/hyperbahn-cluster.js'));
}
function runTests(HyperbahnCluster) {
HyperbahnCluster.test('can advertise', {
size: 5
}, function t(cluster, assert) {
var bob = cluster.remotes.bob;
var client = new HyperbahnClient({
serviceName: 'hello-bob',
callerName: 'hello-bob-test',
hostPortList: cluster.hostPortList,
tchannel: bob.channel,
logger: DebugLogtron('hyperbahnClient')
});
client.once('advertised', onResponse);
client.advertise();
function onResponse() {
var result = client.latestAdvertisementResult;
cluster.checkExitPeers(assert, {
serviceName: 'hello-bob',
hostPort: bob.channel.hostPort
});
assert.equal(result.head, null);
// Because of duplicates in a size 5 cluster we know
// that we have at most 5 kValues
assert.ok(result.body.connectionCount <= 5,
'expect to have at most 5 advertise results');
client.destroy();
assert.end();
}
});
HyperbahnCluster.test('can advertise using hostPortFile', {
size: 5
}, function t(cluster, assert) {
var bob = cluster.remotes.bob;
var hostPortFile;
do {
hostPortFile = '/tmp/host-' + crypto.randomBytes(4).readUInt32LE(0) + '.json';
} while (fs.existsSync(hostPortFile));
fs.writeFileSync(hostPortFile, JSON.stringify(cluster.hostPortList), 'utf8');
var client = new HyperbahnClient({
serviceName: 'hello-bob',
callerName: 'hello-bob-test',
hostPortFile: hostPortFile,
tchannel: bob.channel,
logger: DebugLogtron('hyperbahnClient')
});
assert.once('end', function cleanup() {
client.destroy();
if (fs.existsSync(hostPortFile)) {
fs.unlinkSync(hostPortFile);
}
});
client.once('advertised', onResponse);
client.advertise();
function onResponse() {
var result = client.latestAdvertisementResult;
cluster.checkExitPeers(assert, {
serviceName: 'hello-bob',
hostPort: bob.channel.hostPort
});
assert.equal(result.head, null);
// Because of duplicates in a size 5 cluster we know
// that we have at most 5 kValues
assert.ok(result.body.connectionCount <= 5,
'expect to have at most 5 advertise results');
assert.end();
}
});
}
|
module.exports = {
_id: '5731eb718dc033bc69d9660f',
email: '[email protected]',
name: 'New Test User',
password: '09a3fcee233197960eb1bafe82e20021ad2807e8b12c79e9822ba0d5addfdcb7f786a365b2e8de0419f24cf671f2bd8bac9e6aacd5ff5bece1e5e7346fc19c1741e0286659e39577aaa4a6fd4fe0eab30b95d4437f3821838e27f311bda42a70ae47656eea65afd65a856c9079c866d591df466538cfe7abff4578f3d93fb9e6',
passwordSalt: 'a6a465b8c1baf79bb9423c249ef8a523bd7e34600b3b2215562870a35895fdab'
};
|
//you will need an API key from https://developer.voicesignin.com
var https = require('https');
exports.handler = (event, context, callback) => {
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
console.log(JSON.stringify(event));
configureParams();
//validate input
function configureParams() {
var nameRequest = event["body-json"];
hash.update(event["context"]["source-ip"]);
var hashedIpAddress = hash.digest('hex');
var blocking_string = hashedIpAddress;
var session_expiry = 3600;
if (nameRequest.vname) {
var v1ValidationFilter = /^The ([a-z]|[A-Z])+ ([a-z]|[A-Z])+ of ([a-z]|[A-Z]|[0-9]|-| )+([a-z]|[A-Z]|[0-9])$/i;
if (v1ValidationFilter.test(nameRequest.vname)) {
var vname_components = [];
var vname_version = 'v1';
var vnameMacroParts = nameRequest.vname.split(' of ');
var vnameCity = vnameMacroParts[1];
var vnameColorAndAnimal = vnameMacroParts[0];
var vnameMicroParts = vnameColorAndAnimal.split(' ');
var vnameColor = vnameMicroParts[1];
var vnameAnimal = vnameMicroParts[2];
vname_components = [vnameColor, vnameAnimal, vnameCity];
}
else {
context.done(null, { "error": "vname doesn't match current versions" });
return null;
}
/* SAMPLE DATA, uncomment if you want to use it
vname_version = 'v1';
vname_components = ['brown','bear','Chicago'];
blocking_string = 0383176601762cf74cb95607034b9c7712a431325074396e073d7eb4e5206edc; //just a hash of the user's IP address, you could use a cookie or deviceId as well
session_expiry = 600; // 10 minute connection
*/
sendRequestToVoiceSignin(vname_version, vname_components, blocking_string, session_expiry);
}
else {
return null;
}
return null;
}
function sendRequestToVoiceSignin(vname_version, vname_components, blocking_string, session_expiry) {
var payload = { "vname_version": vname_version, "vname_components": vname_components, "blocking_string": blocking_string, "session_expiry_sec": session_expiry };
payload = JSON.stringify(payload);
console.log(payload);
const options = {
hostname: 'api.voicesignin.com',
port: 443,
path: '/ask',
method: 'POST',
headers: {
'Content-Type': 'application/json',
//********************************************************************
'Authorization': '' // add your API key here
//********************************************************************
}
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
// console.log('data:',res.data);
var rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
var requestResponse = JSON.parse(rawData);
console.log('reqresp: ' + JSON.stringify(requestResponse));
if (requestResponse.request_id !== undefined) {
context.done(null, requestResponse);
return null;
}
else {
context.done(null, { "error": "invalid request" });
return null;
}
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(payload);
req.end();
}
};
|
const path = require('path');
const nodeExternals = require('webpack-node-externals'); // 외부 Node.js 모듈들을 포함하지 않기 위해 로드.
const WebpackShellPlugin = require('webpack-shell-plugin');
const OutputFileName = 'aether.agent.package.js';
var serverCfg = {
context: path.resolve(__dirname, 'src'),
entry: './app.js',
target: 'node',
externals: [nodeExternals()],//node_modules는 무시하도록 설정
output: {
path: path.resolve(__dirname, 'dist'),
filename: OutputFileName
},
module: {
rules:[{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
exclude: /node_modules/,
use: [{
loader: 'babel-loader',
options: {
presets: [
['es2016']
],
plugins: [require('babel-plugin-transform-strict-mode')]// 'use strict'가 없어도 별다른 경고 뱉지 않도록 빌드시 페이지마다 'use strict' 자동삽입
}
}]
}]
},
plugins: [
new WebpackShellPlugin({
onBuildStart:['echo "Webpack Start"'],
onBuildEnd:['echo "Build End: ' + path.resolve(__dirname, 'dist') + '/' + OutputFileName + '"'],
})
]
};
module.exports = serverCfg; |
com.chanjet.gzq.aflow.Canvas = draw2d.Canvas.extend({
canvasName: "com.chanjet.gzq.aflow.Canvas",
init: function(id){
this._super(id);
this.setScrollArea("#"+id);
this.id = id;
var MyInterceptorPolicy = draw2d.policy.canvas.ConnectionInterceptorPolicy.extend({
init : function()
{
this._super();
},
delegateDrop: function(draggedFigure, dropTarget){
return this._super(draggedFigure, dropTarget);
}
});
this.installEditPolicy(new MyInterceptorPolicy());
this.userData = {
name: "流程模版",
id: this.id,
type: "FlowDefinition",
formTemplateId: 'uuid',
formTemplateName: '表单模版名称',
};
},
insertTask: function (connection, taskType) {
var shape = eval("new com.chanjet.gzq.aflow."+taskType+"()");
var x = connection.getBoundingBox().getTopLeft().getX() + (connection.getBoundingBox().getWidth() / 2) - 48;
var y = connection.getBoundingBox().getCenter().getY() - shape.getHeight() / 2;
var sourcePort = connection.getSource();
var targetPort = connection.getTarget();
var cmd = new draw2d.command.CommandDelete(connection);
this.getCommandStack().execute(cmd);
var command = new draw2d.command.CommandAdd(this, shape, x, y);
this.getCommandStack().execute(command);
var cmd = new draw2d.command.CommandConnect(this, sourcePort, shape.inputPorts.data[0]);
// cmd.execute();
this.getCommandStack().execute(cmd);
if (sourcePort.parent.cssClass == 'BranchTask') {
connection.showExpression();
}
cmd = new draw2d.command.CommandConnect(this, shape.outputPorts.data[0], targetPort);
// cmd.execute();
this.getCommandStack().execute(cmd);
},
appendTask: function (thisTask, taskType, value, xPos, yPos) {
var emptyPort = null;
thisTask.outputPorts.data.forEach(function (e, i) {
if(e.connections.data.length == 0) {
emptyPort = e;
}
});
if(emptyPort == null) {
return;
}
var x = xPos != null? xPos : thisTask.getBoundingBox().getTopLeft().getX() + 96 + 100;
var y = yPos != null? yPos : thisTask.getBoundingBox().getCenter().getY();
var shape = eval("new com.chanjet.gzq.aflow."+taskType+"()");
if(taskType == "UserTask") {
shape.userData['userIds'] = value;
}
else if(taskType == "RoleTask") {
shape.userData['roleIds'] = value;
}
else {
console.log(value);
}
var command = new draw2d.command.CommandAdd(this, shape, x, y - shape.getHeight() / 2);
this.getCommandStack().execute(command);
var cmd = new draw2d.command.CommandConnect(this, emptyPort, shape.inputPorts.data[0]);
// cmd.execute();
this.getCommandStack().execute(cmd);
if (thisTask.cssClass == 'BranchTask') {
cmd.connection.showExpression();
}
return shape;
},
convertTaskType: function (thisTask, newTaskType, value) {
var shape = eval("new com.chanjet.gzq.aflow."+newTaskType+"()");
if(newTaskType == "UserTask") {
shape.userData['userIds'] = value;
}
else if(newTaskType == "RoleTask") {
shape.userData['roleIds'] = value;
}
else {
console.log(value);
}
var command = new draw2d.command.CommandAdd(this, shape, thisTask.x, thisTask.y);
this.getCommandStack().execute(command);
thisTask.inputPorts.data.forEach(function (port, index) {
port.connections.data.forEach(function (connection, i) {
command = new draw2d.command.CommandReconnect(connection);
command.setNewPorts(connection.sourcePort, shape.inputPorts.data[0]);
app.canvas.getCommandStack().execute(command);
});
});
command = new draw2d.command.CommandDelete(thisTask);
this.getCommandStack().execute(command);
return shape;
},
appendBranchTaskFromWizard: function (thisTask, value) {
var padding = 50;
var heightOfTaskFigure = 32;
var shape = new com.chanjet.gzq.aflow.BranchTask();
var emptyPort = null;
thisTask.outputPorts.data.forEach(function (e, i) {
if(e.connections.data.length == 0) {
emptyPort = e;
}
});
if(emptyPort == null) {
return;
}
var x = thisTask.getBoundingBox().getTopLeft().getX() + 96 + 150;
var y = thisTask.getBoundingBox().getCenter().getY();
var command = new draw2d.command.CommandAdd(this, shape, x, y - shape.getHeight()/2);
this.getCommandStack().execute(command);
var cmd = new draw2d.command.CommandConnect(this, emptyPort, shape.inputPorts.data[0]);
// cmd.execute();
this.getCommandStack().execute(cmd);
if (thisTask.cssClass == 'BranchTask') {
cmd.connection.showExpression();
}
for(var i = value.length - 2; i > 0; i--) {
shape.addCase();
}
var totalHeight = (heightOfTaskFigure + padding) * value.length;
value.forEach(function (element, index) {
app.canvas.appendTask(shape, 'UserTask', "", shape.getBoundingBox().getTopLeft().getX() + 250,
shape.getBoundingBox().getTopLeft().getY() + totalHeight/2 - (heightOfTaskFigure + padding) * index);
});
shape.outputPorts.data.forEach(function (port, index) {
port.connections.data.forEach(function (connection, i) {
connection.userData['expression'] = value[index];
connection.showExpression();
return;
});
});
return shape;
},
getLastTask: function () {
var sourcePort;
app.canvas.figures.data.forEach(function (e, i) {
if (e.cssClass != "Connection") {
e.getOutputPorts().each( function (i, p) {
p.setMaxFanOut(1);
if(p.connections.data.length==0) {
sourcePort = p;
}
});
}
});
return sourcePort.parent;
},
}); |
import explicitElementToString from './elementToString';
import * as util from './util';
/**
* converts an explicit dataSet to a javascript object
* @param dataSet
* @param options
*/
export default function explicitDataSetToJS (dataSet, options) {
if (dataSet === undefined) {
throw 'dicomParser.explicitDataSetToJS: missing required parameter dataSet';
}
options = options || {
omitPrivateAttibutes: true, // true if private elements should be omitted
maxElementLength: 128 // maximum element length to try and convert to string format
};
var result = {
};
for (var tag in dataSet.elements) {
var element = dataSet.elements[tag];
// skip this element if it a private element and our options specify that we should
if (options.omitPrivateAttibutes === true && util.isPrivateTag(tag)) {
continue;
}
if (element.items) {
// handle sequences
var sequenceItems = [];
for (var i = 0; i < element.items.length; i++) {
sequenceItems.push(explicitDataSetToJS(element.items[i].dataSet, options));
}
result[tag] = sequenceItems;
} else {
var asString;
asString = undefined;
if (element.length < options.maxElementLength) {
asString = explicitElementToString(dataSet, element);
}
if (asString !== undefined) {
result[tag] = asString;
} else {
result[tag] = {
dataOffset: element.dataOffset,
length: element.length
};
}
}
}
return result;
}
|
'use strict';
var _ = require('lodash');
var Bacon = require('baconjs');
var logger = require('./logger');
var bus = new Bacon.Bus();
var dirtyStores = [];
var dispatching = false;
function dispatch(type, payload) {
if (dispatching) {
return Promise.reject('Cascading dispatches are prohibited. Fix your flux.');
}
return new Promise(function (resolve, reject) {
dispatching = true;
logger.logMessage(type, payload);
try {
bus.push({type: type, payload: payload});
pushChanges();
resolve();
} finally {
logger.logMessageEnd();
dispatching = false;
}
});
}
function input(type) {
var payloads = bus.filter(function (msg) {
return msg.type === type;
}).map('.payload');
return payloads;
}
function markStoreAsDirty(store) {
if (!_.contains(dirtyStores, store)) {
dirtyStores.push(store);
}
}
function pushChangesOnce() {
var stores = dirtyStores;
dirtyStores = [];
_.each(stores, function (store) {
store.changes.push(store.output);
});
}
function pushChanges() {
if (!dirtyStores.length) {
logger.logNoDirtyStores();
return;
}
var also = false;
while(dirtyStores.length > 0) {
logger.logDirtyStores(dirtyStores, also);
pushChangesOnce();
also = true;
}
}
module.exports = {
dispatch: dispatch,
input: input,
markStoreAsDirty: markStoreAsDirty
};
|
import * as React from 'react';
// import of a small, pure module in a private demo
// bundle size and module duplication is negligible
/* eslint-disable-next-line no-restricted-imports */
import { convertLength } from '@mui/material/styles/cssUtils';
import { createTheme, responsiveFontSizes } from '@mui/material/styles';
import Box from '@mui/material/Box';
import {
Legend,
Tooltip,
LineChart,
Line,
XAxis,
YAxis,
Label,
ResponsiveContainer,
} from 'recharts';
let theme = createTheme();
theme = responsiveFontSizes(theme);
const colors = [
'#443dc2',
'#2060df',
'#277e91',
'#378153',
'#4d811d',
'#63780d',
'#996600',
];
const variants = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'subtitle1'];
export default function ResponsiveFontSizes() {
const convert = convertLength(theme.typography.htmlFontSize);
const toPx = (rem) => parseFloat(convert(rem, 'px'));
const series = variants.map((variantName) => {
const variant = theme.typography[variantName];
const data = [];
data.push({
viewport: 0,
fontSize: toPx(variant.fontSize),
});
theme.breakpoints.keys.forEach((key) => {
const viewport = theme.breakpoints.values[key];
const value = theme.breakpoints.up(key);
if (variant[value]) {
data.push({
viewport: viewport - 1,
fontSize: data[data.length - 1].fontSize,
});
data.push({
viewport,
fontSize: toPx(variant[value].fontSize),
});
} else if (key === 'xl') {
data.push({
viewport,
fontSize: data[data.length - 1].fontSize,
});
}
});
return {
name: variantName,
data,
};
});
return (
<Box sx={{ height: 380, width: '100%', color: 'black' }}>
<ResponsiveContainer>
<LineChart
margin={{
top: 50,
right: 140,
bottom: 0,
left: 30,
}}
>
<XAxis dataKey="viewport" type="number">
<Label position="right" offset={30}>
viewport (px)
</Label>
</XAxis>
<YAxis dataKey="fontSize" type="number">
<Label position="top" offset={20}>
font-size (rem)
</Label>
</YAxis>
<Tooltip />
<Legend />
{series.map((serie, index) => (
<Line
dataKey="fontSize"
stroke={colors[index % colors.length]}
data={serie.data}
name={serie.name}
key={serie.name}
/>
))}
</LineChart>
</ResponsiveContainer>
</Box>
);
}
|
import Mirage from 'ember-cli-mirage';
import Schema from 'ember-cli-mirage/orm/schema';
import Model from 'ember-cli-mirage/orm/model';
import Db from 'ember-cli-mirage/db';
export default {
setup() {
let db = new Db();
this.schema = new Schema(db);
this.schema.registerModels({
wordSmith: Model.extend({
blogPosts: Mirage.hasMany()
}),
blogPost: Model.extend({
wordSmith: Mirage.belongsTo(),
fineComments: Mirage.hasMany()
}),
fineComment: Model.extend({
blogPost: Mirage.belongsTo()
}),
greatPhoto: Model,
foo: Model.extend({
bar: Mirage.belongsTo()
}),
bar: Model.extend({
baz: Mirage.belongsTo()
}),
baz: Model.extend({
quuxes: Mirage.hasMany()
}),
quux: Model.extend({
zomgs: Mirage.hasMany()
}),
zomg: Model.extend({
lol: Mirage.belongsTo()
}),
lol: Model,
roflCopter: Model
});
return this.schema;
}
};
|
define([
'webgl/createProgram',
'webgl/shader/compileShaderFromFile'
], function(
createProgram,
compileShaderFromFile
) {
/**
* Creates a program from 2 script tags.
*
* @param {!WebGLRenderingContext} gl The WebGL Context.
* @param {string} vertexShaderFileName The file name of the vertex shader.
* @param {string} fragmentShaderFileName The file name of the fragment shader.
* @return {!WebGLProgram} A program
*/
return function createProgramFromScripts(gl, vertexShaderFileName, fragmentShaderFileName, callback) {
var async = !!callback;
if(async) {
compileShaderFromFile(gl, vertexShaderFileName, 'vertex', function(vertexShader) {
compileShaderFromFile(gl, fragmentShaderFileName, 'fragment', function(fragmentShader) {
callback(createProgram(gl, vertexShader, fragmentShader));
});
});
}
else {
return createProgram(gl,
compileShaderFromFile(gl, vertexShaderFileName, 'vertex'),
compileShaderFromFile(gl, fragmentShaderFileName, 'fragment'));
}
};
}); |
import styled from "styled-components"
export const Code = styled.code`
padding: 3px 8px;
background-color: ${({ theme }) => theme.posts.inlineCodeBackground};
color: ${({ theme }) => theme.posts.inlineCodeColor};
border-radius: 6px;
`
|
var searchData=
[
['textobject',['TextObject',['../class_oxy_1_1_framework_1_1_objects_1_1_text_object.html',1,'Oxy::Framework::Objects']]],
['textrenderer',['TextRenderer',['../class_oxy_1_1_framework_1_1_text_renderer.html',1,'Oxy::Framework']]],
['textrenderer',['TextRenderer',['../class_oxy_1_1_framework_1_1_text_renderer.html#aaefdc30b6a2d1b161cf9561092425ea6',1,'Oxy::Framework::TextRenderer']]],
['texture',['Texture',['../class_oxy_1_1_framework_1_1_text_renderer.html#a8f88234b584876dbbdb015c3e1d4636b',1,'Oxy::Framework::TextRenderer']]],
['translate',['Translate',['../class_oxy_1_1_framework_1_1_graphics.html#ac854767976984446279c8cfbc04f2099',1,'Oxy::Framework::Graphics']]]
];
|
'use strict';
angular.module('polaris.directives')
.directive('spinner', [function() {
function link(scope) {
scope.$watch('disappear', function() {
if (scope.disappear) {
scope.hideSpinner = true;
} else {
scope.hideSpinner = false;
}
});
}
var tpl = '<div ng-hide="hideSpinner" class="loading">' +
'<div class="aligner"></div>' +
'<div class="spinner">' +
'<div class="rect1"></div>' +
'<div class="rect2"></div>' +
'<div class="rect3"></div>' +
'<div class="rect4"></div>' +
'<div class="rect5"></div>' +
'</div>' +
'</div>';
return {
restrict: 'E',
template: tpl,
replace: true,
scope: {
'disappear': '='
},
link: link
};
}]);
|
'use strict';
var should = require('chai').should();
describe('Cache', function(){
var Hexo = require('../../../lib/hexo');
var hexo = new Hexo();
var Cache = hexo.model('Cache');
it('_id - required', function(){
return Cache.insert({}).catch(function(err){
err.should.have.property('message', 'ID is not defined');
});
});
}); |
class MenuController {
constructor(translate) {
this.languages = [{locale: 'es', name: 'Español'}, {locale: 'en', name: 'English'}];
this.translate = translate;
this.loc = 'es';
}
changeLocale(loc) {
this.loc = loc || this.loc;
this.translate.use(this.loc);
}
}
MenuController.$inject = ['$translate'];
export { MenuController };
|
(function() {
'use strict';
var mergeModuleExports = require('../../utils/mergemoduleexports');
mergeModuleExports(module.exports, require('./loader'));
mergeModuleExports(module.exports, require('./any'));
})();
|
var Message = function() {
this._data = {
'push_type': 1,
'android': {
'doings': 1
}
};
return this;
};
/*
* Notification bar上显示的标题
* 必须
*/
Message.prototype.title = function(title) {
return this.setAndroid('notification_title', title);
};
/*
* Notification bar上显示的内容
* 必须
*/
Message.prototype.content = function(content) {
return this.setAndroid('notification_content', content);
};
/*
* 系统小图标名称
* 该图标预置在客户端,在通知栏顶部展示
*/
Message.prototype.status_icon = function(status_icon) {
return this.setAndroid('notification_status_icon', status_icon);
};
/*
* 用户自定义 dict
* "extras":{"season":"Spring", "weather":"raining"}]
*/
Message.prototype.extras = function(extras) {
if (!Array.isArray(extras)) {
var extraArray = [];
var keys = Object.keys(extras);
keys.forEach(function(key){
var v = {};
v[key] = extras[key];
extraArray.push(v)
})
extras = extraArray
}
return this.setAndroid('extras', extras);
};
/*
* 推送范围
* 1:指定用户,必须指定tokens字段
* 2:所有人,无需指定tokens,tags,exclude_tags
* 3:一群人,必须指定tags或者exclude_tags字段
*/
Message.prototype.push_type = function(push_type) {
return this.set('push_type', push_type);
};
/*
* 用户标签,目前仅对android用户生效
* 样例:{"tags":[{"location":["ShangHai","GuangZhou"]},}"age":["20","30"]}]}
* 含义:在广州或者上海,并且年龄为20或30岁的用户
*/
Message.prototype.tags = function(tags) {
return this.set('tags', tags);
};
/*
* 需要剔除的用户的标签,目前仅对android用户生效
* 样例:{"exclude_tags":[{"music":["blue"]},{"fruit":["apple"]}]}
* 含义:不给喜欢蓝调音乐的用户,或者喜欢苹果的用户发送消息
*/
Message.prototype.exclude_tags = function(exclude_tags) {
return this.set('exclude_tags', exclude_tags);
};
/*
* 消息生效时间。如果不携带该字段,则表示消息实时生效。实际使用时,该字段精确到分
* 消息发送时间戳,timestamp格式ISO 8601:2013-06-03T17:30:08+08:00
*/
Message.prototype.send_time = function(send_time) {
return this.set('send_time', send_time);
};
/*
* 消息过期删除时间
* 消息过期时间,timestamp格式ISO 8601:2013-06-03T17:30:08+08:00
*/
Message.prototype.expire_time = function(expire_time) {
return this.set('expire_time', expire_time);
};
/*
* 目标设备类型
* 1:android
* 2:ios
* 默认为android
*/
Message.prototype.device_type = function(device_type) {
return this.set('device_type', device_type);
};
/*
* 1:直接打开应用
* 2:通过自定义动作打开应用
* 3:打开URL
* 4:富媒体消息
* 5:短信收件箱广告
* 6:彩信收件箱广告
* 注意:当手机收到短信、彩信收件箱广告后,在收件人一栏显示的是应用在联盟上注册的名字哦~
*/
Message.prototype.doings = function(doings) {
return this.setAndroid('doings', doings);
};
Message.prototype.setAndroid = function(key, value) {
this._data['android'][key] = value;
return this;
};
Message.prototype.set = function(key, value) {
this._data[key] = value;
return this;
};
Message.prototype.getAndroidData = function() {
return this._data;
};
Message.prototype.getData = function() {
return this._data;
};
Message.prototype.toString = function() {
return JSON.stringify(this._data);
};
module.exports = Message;
|
'use strict';
const periodic = require('periodicjs');
const capitalize = require('capitalize');
const pluralize = require('pluralize');
const reactappLocals = periodic.locals.extensions.get('periodicjs.ext.reactapp');
const reactapp = reactappLocals.reactapp();
function userRoleForm(options = {}) {
const { entity } = options;
const entityDisplay = getEntityDisplay(entity);
return reactappLocals.server_manifest.forms.createForm({
method: (options.update) ? 'PUT' : 'POST',
action: (options.update)
? `${reactapp.manifest_prefix}contentdata/standard_${entityDisplay.plural}/:id?format=json`
: `${reactapp.manifest_prefix}contentdata/standard_${entityDisplay.plural}?format=json`,
onSubmit:'closeModal',
onComplete: 'refresh',
// loadingScreen: true,
style: {
paddingTop:'1rem',
},
hiddenFields: [
],
// validations: [ ],
rows: [
{
formElements: [
{
type: 'text',
passProps: {
disabled: true,
state: 'isDisabled',
},
label:'Email',
name:'email',
},
],
},
{
formElements: [
{
type: 'datalist',
name: 'userroles',
label: 'User Roles',
datalist: {
multi: true,
// selector: '_id',
entity:'standard_userrole',
resourceUrl:`${reactapp.manifest_prefix}contentdata/standard_userroles?format=json`
}
// passProps: {
// // multiple:true,
// },
},
],
},
{
formElements: [
{
type: 'submit',
value: (options.update) ? 'Update User Role' : 'Add User Role',
layoutProps: {
style: {
textAlign:'center',
},
},
},
],
},
],
actionParams: (options.update)
? [
{
key: ':id',
val: '_id',
},
]
: undefined,
// hiddenFields
formProps: {
flattenFormData:false,
},
asyncprops: (options.update)
? {
formdata: [ 'accessdata', 'data' ],
}
: {},
});
}
function getEntityDisplay(entity) {
return {
plural: pluralize(entity),
capitalized: capitalize(entity),
pluralCapitalized: pluralize(capitalize(entity)),
};
}
function getPageTitle(options) {
const { entity } = options;
const entityDisplay = getEntityDisplay(entity);
return reactappLocals.server_manifest.helpers.getPageTitle({
styles: {
// ui: {}
},
title: `Manage ${entityDisplay.capitalized} Access`,
// action: {
// type: 'modal',
// title: `Manage ${entityDisplay.capitalized} Access`,
// pathname: `${reactapp.manifest_prefix}edit-${entity}-access`,
// buttonProps: {
// props: {
// color:'isSuccess',
// },
// },
// },
})
}
function getAccessPage(options) {
const { entity } = options;
const entityDisplay = getEntityDisplay(entity);
return {
layout: {
component: 'Container',
props: {
style: {
padding: '6rem 0',
},
},
children: [
getPageTitle({
entity,
}),
reactappLocals.server_manifest.table.getTable({
schemaName: `standard_${entityDisplay.plural}`,
baseUrl: `${reactapp.manifest_prefix}contentdata/standard_${entityDisplay.plural}?format=json`,
asyncdataprops: 'accessdata',
headers: [
{
buttons: [
{
passProps: {
onClick: 'func:this.props.createModal',
onclickThisProp: 'onclickPropObject',
onclickProps: {
title: `Edit ${entityDisplay.capitalized} Access`,
pathname: `${reactapp.manifest_prefix}edit-${entity}-access/:id`,
params: [
{
key: ':id',
val: '_id',
}
],
},
buttonProps: {
color: 'isInfo',
buttonStyle: 'isOutlined',
icon: 'fa fa-pencil',
},
},
}
],
sortid: '_id',
sortable: true,
label: 'ID',
},
{
sortable: true,
sortid: 'email',
label: 'Email',
},
{
sortable: true,
sortid: 'firstname',
label: 'First name',
},
{
sortable: true,
sortid: 'lastname',
label: 'Last Name',
},
{
sortable: true,
sortid: 'userroles',
customCellLayout: {
component: 'DynamicLayout',
// ignoreReduxProps:true,
thisprops: {
items:['cell'],
},
bindprops:true,
props: {
layout: {
bindprops:true,
component: 'Tag',
props: {
color: 'isDark',
style: {
margin:'0.25rem'
}
},
children: [
{
bindprops:true,
component: 'span',
thisprops: {
_children:['name']
}
},
// {
// component: 'span',
// children:': ',
// },
// {
// bindprops:true,
// component: 'span',
// thisprops: {
// _children:['userroleid']
// }
// }
]
}
}
},
label: 'User Roles',
},
],
}),
],
},
resources: {
accessdata: `${reactapp.manifest_prefix}contentdata/standard_${entityDisplay.plural}?format=json`,
},
pageData: {
title: `Manage ${entityDisplay.capitalized} Access`,
},
};
}
function getModalPage(options) {
const { entity } = options;
const entityDisplay = getEntityDisplay(entity);
return {
layout: {
component: 'Content',
children: [
userRoleForm({
update: true,
entity,
}),
],
},
resources: {
accessdata: `${reactapp.manifest_prefix}contentdata/standard_${entityDisplay.plural}/:id?format=json`,
},
pageData: {
title: `Edit ${entityDisplay.capitalized} Access`,
},
};
}
const uacSettings = periodic.settings.extensions[ 'periodicjs.ext.user_access_control' ];
module.exports = {
containers: (uacSettings.use_manifests)
? {
[ `${reactapp.manifest_prefix}ext/uac/account-access` ]: getAccessPage({ entity: 'account' }),
[ `${reactapp.manifest_prefix}ext/uac/user-access` ]: getAccessPage({ entity: 'user' }),
[ `${reactapp.manifest_prefix}edit-account-access/:id` ]: getModalPage({ entity: 'account' }),
[ `${reactapp.manifest_prefix}edit-user-access/:id` ]: getModalPage({ entity: 'user' }),
}
: {},
}; |
var Court = artifacts.require("./Court.sol");
contract('Court', (accounts) => {
it("test kleroterion", () => {})
})
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchWeather } from '../actions/index';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
this.onInputChange = this.onInputChange.bind(this);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onInputChange(event) {
this.setState({ term: event.target.value });
}
onFormSubmit(event) {
event.preventDefault();
//We need to fetch data
this.props.fetchWeather(this.state.term);
//Reset the search bar
this.setState({ term: '' });
}
render() {
return(
<form onSubmit={this.onFormSubmit} className="input-group">
<input
placeholder="Give a five-day forecast in your favorite cities"
className="form-control"
value={this.state.term}
onChange={this.onInputChange}
/>
<span className="input-group-btn">
<button type="submit" className="btn btn-secondary">Search</button>
</span>
</form>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ fetchWeather }, dispatch);
}
//Passing null to connect in first argument (application state or Redux state) is indicating
//that our container or SmartComponent does not care about the application state
export default connect(null, mapDispatchToProps)(SearchBar);
|
/**
* 检查文件名后缀,判断是否为合法的日志文件
*
* @param fileName 文件名字符串
* @returns {bool} 文件名是否合法,true 合法,false 非法
*/
function isValidLogFile(fileName) {
if(fileName === null || fileName === '') throw new Error('file name empty!');
return (lastValid = /.*\.slf$/.test(fileName));
}
var lastValid = false;
function wasLastFileNameValid() {
return lastValid;
}
module.exports.isValidLogFile = isValidLogFile;
module.exports.wasLastFileNameValid = wasLastFileNameValid;
|
version https://git-lfs.github.com/spec/v1
oid sha256:9e6f79a284bf0e25e4a049856c97549792145e4af30916b5044b69d4779caae2
size 23494
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
var u = undefined;
function plural(n) {
var i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
global.ng.common.locales['ur'] = [
'ur',
[['a', 'p'], ['AM', 'PM'], u],
[['AM', 'PM'], u, u],
[
['S', 'M', 'T', 'W', 'T', 'F', 'S'],
['اتوار', 'پیر', 'منگل', 'بدھ', 'جمعرات', 'جمعہ', 'ہفتہ'], u, u
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'جنوری', 'فروری', 'مارچ', 'اپریل', 'مئی', 'جون', 'جولائی',
'اگست', 'ستمبر', 'اکتوبر', 'نومبر', 'دسمبر'
],
u
],
u,
[['قبل مسیح', 'عیسوی'], u, u],
0,
[6, 0],
['d/M/yy', 'd MMM، y', 'd MMMM، y', 'EEEE، d MMMM، y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
['{1} {0}', u, u, u],
['.', ',', ';', '%', '\u200e+', '\u200e-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'],
'PKR',
'Rs',
'پاکستانی روپیہ',
{'JPY': ['JP¥', '¥'], 'PKR': ['Rs'], 'THB': ['฿'], 'TWD': ['NT$']},
'rtl',
plural,
[
[
['آدھی رات', 'صبح', 'دوپہر', 'سہ پہر', 'شام', 'رات'], u,
[
'آدھی رات', 'صبح میں', 'دوپہر میں', 'سہ پہر', 'شام میں',
'رات میں'
]
],
[['آدھی رات', 'صبح', 'دوپہر', 'سہ پہر', 'شام', 'رات'], u, u],
[
'00:00', ['04:00', '12:00'], ['12:00', '16:00'], ['16:00', '18:00'], ['18:00', '20:00'],
['20:00', '04:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
|
import { Meteor } from 'meteor/meteor'
import { composeWithTracker } from 'react-komposer'
import { Semesters, RegStatuses, Classrooms, Sessions, Categories, Classes, Terms } from '../../api/data/data'
import CourseCreation from '../components/CourseCreation'
import Loading from '../components/loading'
const composer = (params, onData) => {
const subSemesters = Meteor.subscribe('semesters')
const subRegStatuses = Meteor.subscribe('semesters')
const subClassrooms = Meteor.subscribe('classrooms')
const subSessions = Meteor.subscribe('sessions')
const subCategories = Meteor.subscribe('categories')
const subClasses = Meteor.subscribe('classes')
const subTerms = Meteor.subscribe('terms')
if (subSemesters.ready() &&
subRegStatuses.ready() &&
subClassrooms.ready() &&
subSessions.ready() &&
subCategories.ready() &&
subTerms.ready() &&
subClasses.ready()) {
const semesters = Semesters.find().fetch()
const regstatuses = RegStatuses.find().fetch()
const classrooms = Classrooms.find().fetch()
const sessions = Sessions.find().fetch()
const categories = Categories.find().fetch()
const classes = Classes.find().fetch()
const terms = Terms.find().fetch()
onData(null, { semesters, regstatuses, classrooms, sessions, categories, classes, terms })
}
}
export default composeWithTracker(composer, Loading)(CourseCreation)
|
define([
'jquery',
'room-info',
'local-session',
'utils',
'connection',
'mode-list'
], function ($, roomInfo, localSession, Utils, connection, modeList) {
"use strict";
/**
* タブ単体の制御
* @param {String} viewerId
* @param {String} tabId
* @param {String} tabName
*/
var Tab = function (viewerId, tabId, tabName) {
/**
* AceのインスタンスID
* @type {String}
*/
this._aceId = viewerId + '-' + tabId;
/**
* このタブのviewerId
* @type {String}
*/
this._viewerId = viewerId;
/**
* タブID
* @type {String}
*/
this.id = tabId;
/**
* タブ名
* @type {String}
*/
this.tabName = tabName;
/**
* 自身かどうか
* @type {Boolean}
*/
this.isSelf = viewerId === localSession.get(roomInfo.room.id);
/**
* タブHTML要素の初期化
*/
this._initTabElement(viewerId, tabId, tabName);
/**
* エディタのルートHTML要素
* @type {Object}
*/
this._$editor = $('#' + this._aceId);
/**
* Aceのインスタンス
* @type {Object}
*/
this.ace = ace.edit(this._aceId);
/**
* ファイルの更新日時監視タイマー
* @type {Number}
*/
this._FILE_MONITOR_INTERVAL = null;
/**
* ファイルの最終更新日時
* @type {Number}
*/
this._fileLastMod = -1;
var _self = this;
/**
* 受信データ反映時の処理マッピング
* @type {Object}
*/
this._update = {
/**
* 選択範囲
* @param {Range} range
*/
range: function (range) {
_self.ace.selection.setSelectionRange(range);
},
/**
* スクロール位置
* @param {Object} scroll
*/
scroll: function (scroll) {
_self.ace.session.setScrollTop(scroll.top);
_self.ace.session.setScrollLeft(scroll.left);
},
/**
* 言語モード
* @param {String} mode
*/
mode: function (mode) {
_self.ace.session.setMode("ace/mode/" + mode);
},
/**
* カラーテーマ
* @param {String} theme
*/
theme: function (theme) {
_self.ace.setTheme("ace/theme/" + theme);
},
/**
* フォントサイズ
* @param {Number} size
*/
fontsize: function (size) {
_self.ace.setFontSize(size|0);
},
/**
* タブ名
* @param {String} tabName
*/
tabname: function (tabName) {
if (_self.tabName === tabName) return;
_self.tabName = tabName;
_self.$tabLabel.text(decodeURIComponent(tabName));
},
/**
* テキスト
* @param {String} text
*/
text: function (text) {
var range = _self.ace.session.selection.getRange();
var scrollTop = _self.ace.session.getScrollTop();
var scrollLeft = _self.ace.session.getScrollLeft();
_self.ace.setValue(decodeURIComponent(text));
_self.ace.selection.setSelectionRange(range);
_self.ace.session.setScrollTop(scrollTop);
_self.ace.session.setScrollLeft(scrollLeft);
},
/**
* カーソル位置
* @param {Object} cursor
*/
cursor: function (cursor) {
var current = _self.ace.getCursorPosition();
if (cursor.top !== current.top || cursor.left !== current.left) {
_self.ace.moveCursorToPosition(cursor);
}
}
}
/**
* 初期化
*/
this._init();
}
Tab.prototype = {
/**
* タブのHTML要素初期化
* @param {String} viewerId
* @param {String} tabId
* @param {String} tabName
*/
_initTabElement: function (viewerId, tabId, tabName) {
var $root = $('#' + viewerId);
var editorRegion = $('#editor-region');
var tabItemText = '<li class="tab-item" data-tab-id="%s"><a class="label" title="">%s</a><a class="close" data-tab-id="%s">x</a></li>';
var editorText = '<div id="%s" data-tab-id="%s"></div>';
// data属性がうまく反映されず、テンプレート化いったん断念
$(Utils.sprintf(editorText, this._aceId, tabId)).width(editorRegion.width()).height(editorRegion.height() - 37).appendTo($root.find('.editor-list:first'));
$(Utils.sprintf(tabItemText, tabId, tabName, tabId)).appendTo($root.find('.tab-list'));
this.$tabLabel = $root.find('.tab-list').find('[data-tab-id="' + this.id + '"] > .label');
},
/**
* 初期化
*/
_init: function () {
this.ace.session.setUseSoftTabs(true);
this.ace.setAnimatedScroll(true);
this.applyData({
theme: 'cobalt',
mode: 'text',
fontsize: 12
});
this.isSelf ? this._initSelf() : this.ace.setReadOnly(true);
},
/**
* 自身の初期化(エディタが操作されたらメンバーに送信など)
*/
_initSelf: function () {
var sendActionList = [
'insertText',
'removeText',
'insertLines',
'removeLines'
];
var _self = this;
var sendState = (function () {
var timer = null;
return function () {
clearTimeout(timer);
timer = setTimeout(function () {
_self._sendData('state', _self.getState());
}, 10);
}
}());
this.ace.session.on('changeScrollLeft', sendState);
this.ace.session.on('changeScrollTop', sendState);
this.ace.session.selection.on('changeSelection', sendState);
this.ace.session.selection.on('changeCursor', sendState);
this.ace.session.on('change', function (e) {
if (sendActionList.indexOf(e.data.action) == -1) {
return;
}
this._sendData('text', { text: this.getText() });
}.bind(this));
},
/**
* データを送信する
* @param {String} type - 送信タイプ
* @param {Object} data
* @param {Boolean} toServer - サーバに送信するならtrue
* @param {String} command
*/
_sendData: function (type, data, toServer, command) {
// TODO: この中をもっと整える
var tmpData = {
viewerId: this._viewerId,
tabId: this.id,
tabName: encodeURIComponent(this.tabName),
data: data
};
if (command) tmpData.command = command;
var editorData = {
type: 'editor_change_' + type,
data: JSON.stringify(tmpData)
};
if (toServer) {
connection.send(editorData);
return;
}
var sendData = {};
sendData.updated = true;
sendData[editorData.type] = {
type: '',
data: [editorData]
};
connection.sendRTC(sendData);
},
/**
* タブの情報を送信. 複数ファイルを一度にドラッグ&ドロップされたときなど
* @param {Object} textData
* @param {Boolean} toServer - サーバに送信するならtrue
* @return {Tab} 自身
*/
send: function (textData, toServer) {
// サーバー側のremoveTabを上書きするためchange_state
this._sendData('state', this.getState(), toServer);
this._sendData('text', textData, toServer);
return this;
},
/**
* タブの情報をサーバに送信
* @param {Object} textData
*/
saveToServer: function (textData) {
this.send(textData, true);
},
/**
* タブの状態をまとめた送信用オブジェクト生成
* @return {Object} 送信用オブジェクト
*/
serialize: function () {
var data = this.getState();
data.text = this.getText();
return {
"viewer_id": this._viewerId,
"tab_id": this.id,
"data": JSON.stringify({
viewerId: this._viewerId,
tabId: this.id,
tabName: encodeURIComponent(this.tabName),
data: data
})
};
},
/**
* ドロップされたファイルの更新日時を監視。外部で更新されたらエディタに反映。
* @param {File} file
*/
startMonitoringFile: function (file) {
this._fileLastMod = file.lastModifiedDate;
clearInterval(this._FILE_MONITOR_INTERVAL);
this._FILE_MONITOR_INTERVAL = setInterval(function () {
if (this._fileLastMod.getTime() === file.lastModifiedDate.getTime()) {
return;
}
this._fileLastMod = file.lastModifiedDate;
var reader = new FileReader();
reader.onload = function (e) {
this.applyData({
text: Utils.arrayBufferToString(e.target.result)
});
}.bind(this);
reader.readAsArrayBuffer(file);
}.bind(this), 1000);
return this;
},
/**
* タブを表示する
* @return {Tab} 自身
*/
show: function () {
this._$editor.removeClass('hidden');
return this;
},
/**
* タブを非表示にする
* @return {Tab} 自身
*/
hide: function () {
this._$editor.addClass('hidden');
return this;
},
/**
* リサイズ
* @return {Tab} 自身
*/
resize: function () {
this.ace.resize();
return this;
},
/**
* タブを点滅させる
* @param {Boolean} flashing
* @return {Tab} self
*/
setFlashing: function (flashing) {
$('#' + this._viewerId).find('[data-tab-id="' + this.id + '"]')[flashing ? 'addClass' : 'removeClass']('flashing');
return this;
},
/**
* エディタのテキストをURIencodeして取得(送信用)
* @return {String} 送信用テキスト
*/
getText: function () {
return encodeURIComponent(this.ace.getValue());
},
/**
* エディタの状態をまとめたオブジェクト生成
* @return {Object}
*/
getState: function () {
return {
tabname: this.tabName,
scroll: {
top: this.ace.session.getScrollTop(),
left: this.ace.session.getScrollLeft()
},
cursor: this.ace.getCursorPosition(),
range: this.ace.session.selection.getRange(),
theme: this.ace.getTheme().substr(10),
mode: this.ace.session.getMode().$id.substr(9),
fontsize: this.ace.getFontSize()
};
},
/**
* 受信データを反映する
* @param {Object} data
* @return {Tab} 自身
*/
applyData: function (data) {
// textだったら言語モード再取得. 言語モードが正しく反映されない問題の仮対応.
if (data.mode === 'text') {
data.mode = modeList.getModeForPath(data.tabname || this.tabName).name;
}
// 入ってきたプロパティだけ反映する
for (var prop in data) if (data.hasOwnProperty(prop)) {
if (prop in this._update) {
this._update[prop](data[prop]);
} else {
console.warn('無効なプロパティ: ', data);
}
}
return this;
},
/**
* タブ削除
* @return {Tab} 自身
*/
remove: function () {
clearInterval(this._FILE_MONITOR_INTERVAL);
this.ace.destroy();
if (this.isSelf) {
this._sendData('state', {}, true, 'removeTab');
}
return this;
}
}
return Tab;
});
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'toolbar', 'zh', {
toolbarCollapse: '摺疊工具列',
toolbarExpand: '展開工具列',
toolbarGroups: {
document: '文件',
clipboard: '剪貼簿/復原',
editing: '編輯選項',
forms: '格式',
basicstyles: '基本樣式',
paragraph: '段落',
links: '連結',
insert: '插入',
styles: '樣式',
colors: '顏色',
tools: '工具'
},
toolbars: '編輯器工具列'
} );
|
/** @constructor */
Libraries.SyntaxHighlighter = function (){};
/** @type {Function} */
Libraries.SyntaxHighlighter.all;
/** @type {Object} */
Libraries.SyntaxHighlighter.defaults;
/** @type {Function} */
Libraries.SyntaxHighlighter.highlight;
/** @type {Object} */
Libraries.SyntaxHighlighter.Highlighter;
/** @type {Object} */
Libraries.SyntaxHighlighter.brushes;
/** @type {Object} */
Libraries.SyntaxHighlighter.regexLib;
/** @type {RegExp} */
SyntaxHighlighter.regexLib.aspScriptTags
/** @type {RegExp} */
SyntaxHighlighter.regexLib.doubleQuotedString
/** @type {RegExp} */
SyntaxHighlighter.regexLib.multiLineCComments
/** @type {RegExp} */
SyntaxHighlighter.regexLib.multiLineDoubleQuotedString
/** @type {RegExp} */
SyntaxHighlighter.regexLib.multiLineSingleQuotedString
/** @type {RegExp} */
SyntaxHighlighter.regexLib.phpScriptTags
/** @type {RegExp} */
SyntaxHighlighter.regexLib.scriptScriptTags
/** @type {RegExp} */
SyntaxHighlighter.regexLib.singleLineCComments
/** @type {RegExp} */
SyntaxHighlighter.regexLib.singleLinePerlComments
/** @type {RegExp} */
SyntaxHighlighter.regexLib.singleQuotedString
/** @type {RegExp} */
SyntaxHighlighter.regexLib.xmlComments
|
/**
* @ngdoc controller
* @name NavigationController
* @function
*
* @description
* Handles the section area of the app
*
* @param {navigationService} navigationService A reference to the navigationService
*/
function NavigationController($scope,$rootScope, $location, $log, navigationService, dialogService, historyService, sectionResource, angularHelper) {
//Put the navigation service on this scope so we can use it's methods/properties in the view.
// IMPORTANT: all properties assigned to this scope are generally available on the scope object on dialogs since
// when we create a dialog we pass in this scope to be used for the dialog's scope instead of creating a new one.
$scope.nav = navigationService;
$scope.selectedId = navigationService.currentId;
$scope.sections = navigationService.sections;
sectionResource.getSections()
.then(function(result) {
$scope.sections = result;
});
//This reacts to clicks passed to the body element which emits a global call to close all dialogs
$rootScope.$on("closeDialogs", function (event) {
if (navigationService.ui.stickyNavigation && (!event.target || $(event.target).parents(".umb-modalcolumn").size() == 0)) {
navigationService.hideNavigation();
angularHelper.safeApply($scope);
}
});
//this reacts to the options item in the tree
$scope.$on("treeOptionsClick", function (ev, args) {
$scope.currentNode = args.node;
args.scope = $scope;
navigationService.showMenu(ev, args);
});
//this reacts to tree items themselves being clicked
//the tree directive should not contain any handling, simply just bubble events
$scope.$on("treeNodeSelect", function (ev, args) {
var n = args.node;
//here we need to check for some legacy tree code
if (n.jsClickCallback && n.jsClickCallback !== "") {
//this is a legacy tree node!
var jsPrefix = "javascript:";
var js;
if (n.jsClickCallback.startsWith(jsPrefix)) {
js = n.jsClickCallback.substr(jsPrefix.length);
}
else {
js = n.jsClickCallback;
}
try {
var func = eval(js);
//this is normally not necessary since the eval above should execute the method and will return nothing.
if (func != null && (typeof func === "function")) {
func.call();
}
}
catch(ex) {
$log.error("Error evaluating js callback from legacy tree node: " + ex);
}
}
else {
//add action to the history service
historyService.add({name: n.name, link: n.view, icon: n.icon});
//not legacy, lets just set the route value and clear the query string if there is one.
$location.path(n.view).search(null);
}
});
/** Opens a dialog but passes in this scope instance to be used for the dialog */
$scope.openDialog = function (currentNode, action, currentSection) {
navigationService.showDialog({
scope: $scope,
node: currentNode,
action: action,
section: currentSection
});
};
}
//register it
angular.module('umbraco').controller("NavigationController", NavigationController);
|
import { remove, attempt, isError } from 'lodash';
import uuid from 'uuid/v4';
import { fileExtension } from 'Lib/pathHelper'
import AuthenticationPage from './AuthenticationPage';
window.repoFiles = window.repoFiles || {};
function getFile(path) {
const segments = path.split('/');
let obj = window.repoFiles;
while (obj && segments.length) {
obj = obj[segments.shift()];
}
return obj || {};
}
export default class TestRepo {
constructor(config) {
this.config = config;
this.assets = [];
}
authComponent() {
return AuthenticationPage;
}
restoreUser(user) {
return this.authenticate(user);
}
authenticate() {
return Promise.resolve();
}
logout() {
return null;
}
getToken() {
return Promise.resolve('');
}
entriesByFolder(collection, extension) {
const entries = [];
const folder = collection.get('folder');
if (folder) {
for (const path in window.repoFiles[folder]) {
if (fileExtension(path) !== extension) {
continue;
}
const file = { path: `${ folder }/${ path }` };
entries.push(
{
file,
data: window.repoFiles[folder][path].content,
}
);
}
}
return Promise.resolve(entries);
}
entriesByFiles(collection) {
const files = collection.get('files').map(collectionFile => ({
path: collectionFile.get('file'),
label: collectionFile.get('label'),
}));
return Promise.all(files.map(file => ({
file,
data: getFile(file.path).content,
})));
}
getEntry(collection, slug, path) {
return Promise.resolve({
file: { path },
data: getFile(path).content,
});
}
persistEntry(entry, mediaFiles = [], options) {
const newEntry = options.newEntry || false;
const folder = entry.path.substring(0, entry.path.lastIndexOf('/'));
const fileName = entry.path.substring(entry.path.lastIndexOf('/') + 1);
window.repoFiles[folder] = window.repoFiles[folder] || {};
window.repoFiles[folder][fileName] = window.repoFiles[folder][fileName] || {};
if (newEntry) {
window.repoFiles[folder][fileName] = { content: entry.raw };
} else {
window.repoFiles[folder][fileName].content = entry.raw;
}
return Promise.resolve();
}
getMedia() {
return Promise.resolve(this.assets);
}
persistMedia({ fileObj }) {
const { name, size } = fileObj;
const objectUrl = attempt(window.URL.createObjectURL, fileObj);
const url = isError(objectUrl) ? '' : objectUrl;
const normalizedAsset = { id: uuid(), name, size, path: url, url };
this.assets.push(normalizedAsset);
return Promise.resolve(normalizedAsset);
}
deleteFile(path, commitMessage) {
const assetIndex = this.assets.findIndex(asset => asset.path === path);
if (assetIndex > -1) {
this.assets.splice(assetIndex, 1);
}
else {
const folder = path.substring(0, path.lastIndexOf('/'));
const fileName = path.substring(path.lastIndexOf('/') + 1);
delete window.repoFiles[folder][fileName];
}
return Promise.resolve();
}
}
|
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import TutorialScreen from '../components/tutorialScreen';
import {
toggleAutoplay,
} from '../actions/audio';
import {
tutorialPageDidChange,
hideTutorial,
} from '../actions/tutorial';
const mapStateToProps = (state) => {
return {
timerActive: state.bottomPlayer.timerActive,
autoplayOn: state.bottomPlayer.autoplayOn,
bluetoothOn: state.beacon.bluetoothOn,
locationServicesStatus: state.beacon.locationServicesStatus,
currentPage: state.tutorial.currentPage,
tutorialHidden: state.tutorial.tutorialHidden,
};
};
const mapDispatchToProps = (dispatch) => {
return {
actions:
bindActionCreators({
toggleAutoplay,
tutorialPageDidChange,
hideTutorial,
}, dispatch),
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(TutorialScreen);
|
/* Copyright Ben Trask and other contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE. */
module.exports = unique;
function unique(array) {
var r = [], l = array.length, x;
for(var i = 0; i < l; ++i) {
x = array[i];
if(-1 === r.indexOf(x)) r.push(x);
}
return r;
}
|
// Karma configuration
// Generated on Sat Jul 04 2015 21:07:22 GMT-0300 (BRT)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.min.js',
'bower_components/angular-mocks/angular-mocks.js',
'node_modules/*',
'src/FormulaOne/DataServices/GERequest.js',
'tests/unit/FormulaOne/DataServices/GERequestSpec.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
|
function onLoaded() {
var csInterface = new CSInterface();
var appName = csInterface.hostEnvironment.appName;
if(appName != "FLPR"){
loadJSX();
}
var appNames = ["PHXS"];
for (var i = 0; i < appNames.length; i++) {
var name = appNames[i];
if (appName.indexOf(name) >= 0) {
var btn = document.getElementById("btn_" + name);
if (btn)
btn.disabled = false;
}
}
updateThemeWithAppSkinInfo(csInterface.hostEnvironment.appSkinInfo);
// Update the color of the panel when the theme color of the product changed.
csInterface.addEventListener(CSInterface.THEME_COLOR_CHANGED_EVENT, onAppThemeColorChanged);
}
/**
* Update the theme with the AppSkinInfo retrieved from the host product.
*/
function updateThemeWithAppSkinInfo(appSkinInfo) {
//Update the background color of the panel
var panelBackgroundColor = appSkinInfo.panelBackgroundColor.color;
document.body.bgColor = toHex(panelBackgroundColor);
var styleId = "ppstyle";
var csInterface = new CSInterface();
var appName = csInterface.hostEnvironment.appName;
if(appName == "PHXS"){
addRule(styleId, "button, select, input[type=button], input[type=submit]", "border-radius:3px;");
}
if(appName == "PHXS" || appName == "PPRO" || appName == "PRLD") {
////////////////////////////////////////////////////////////////////////////////////////////////
// NOTE: Below theme related code are only suitable for Photoshop. //
// If you want to achieve same effect on other products please make your own changes here. //
////////////////////////////////////////////////////////////////////////////////////////////////
var gradientBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, 40) + " , " + toHex(panelBackgroundColor, 10) + ");";
var gradientDisabledBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, 15) + " , " + toHex(panelBackgroundColor, 5) + ");";
var boxShadow = "-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2);";
var boxActiveShadow = "-webkit-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6);";
var isPanelThemeLight = panelBackgroundColor.red > 127;
var fontColor, disabledFontColor;
var borderColor;
var inputBackgroundColor;
var gradientHighlightBg;
if(isPanelThemeLight) {
fontColor = "#000000;";
disabledFontColor = "color:" + toHex(panelBackgroundColor, -70) + ";";
borderColor = "border-color: " + toHex(panelBackgroundColor, -90) + ";";
inputBackgroundColor = toHex(panelBackgroundColor, 54) + ";";
gradientHighlightBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, -40) + " , " + toHex(panelBackgroundColor,-50) + ");";
} else {
fontColor = "#ffffff;";
disabledFontColor = "color:" + toHex(panelBackgroundColor, 100) + ";";
borderColor = "border-color: " + toHex(panelBackgroundColor, -45) + ";";
inputBackgroundColor = toHex(panelBackgroundColor, -20) + ";";
gradientHighlightBg = "background-image: -webkit-linear-gradient(top, " + toHex(panelBackgroundColor, -20) + " , " + toHex(panelBackgroundColor, -30) + ");";
}
//Update the default text style with pp values
addRule(styleId, ".default", "font-size:" + appSkinInfo.baseFontSize + "px" + "; color:" + fontColor + "; background-color:" + toHex(panelBackgroundColor) + ";");
addRule(styleId, "button, select, input[type=text], input[type=button], input[type=submit]", borderColor);
addRule(styleId, "button, select, input[type=button], input[type=submit]", gradientBg);
addRule(styleId, "button, select, input[type=button], input[type=submit]", boxShadow);
addRule(styleId, "button:enabled:active, input[type=button]:enabled:active, input[type=submit]:enabled:active", gradientHighlightBg);
addRule(styleId, "button:enabled:active, input[type=button]:enabled:active, input[type=submit]:enabled:active", boxActiveShadow);
addRule(styleId, "[disabled]", gradientDisabledBg);
addRule(styleId, "[disabled]", disabledFontColor);
addRule(styleId, "input[type=text]", "padding:1px 3px;");
addRule(styleId, "input[type=text]", "background-color: " + inputBackgroundColor) + ";";
addRule(styleId, "input[type=text]:focus", "background-color: #ffffff;");
addRule(styleId, "input[type=text]:focus", "color: #000000;");
} else {
// For AI, ID and FL use old implementation
addRule(styleId, ".default", "font-size:" + appSkinInfo.baseFontSize + "px" + "; color:" + reverseColor(panelBackgroundColor) + "; background-color:" + toHex(panelBackgroundColor, 20));
addRule(styleId, "button", "border-color: " + toHex(panelBgColor, -50));
}
}
function addRule(stylesheetId, selector, rule) {
var stylesheet = document.getElementById(stylesheetId);
if (stylesheet) {
stylesheet = stylesheet.sheet;
if( stylesheet.addRule ){
stylesheet.addRule(selector, rule);
} else if( stylesheet.insertRule ){
stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);
}
}
}
function reverseColor(color, delta) {
return toHex({red:Math.abs(255-color.red), green:Math.abs(255-color.green), blue:Math.abs(255-color.blue)}, delta);
}
/**
* Convert the Color object to string in hexadecimal format;
*/
function toHex(color, delta) {
function computeValue(value, delta) {
var computedValue = !isNaN(delta) ? value + delta : value;
if (computedValue < 0) {
computedValue = 0;
} else if (computedValue > 255) {
computedValue = 255;
}
computedValue = computedValue.toString(16);
return computedValue.length == 1 ? "0" + computedValue : computedValue;
}
var hex = "";
if (color) {
with (color) {
hex = computeValue(red, delta) + computeValue(green, delta) + computeValue(blue, delta);
};
}
return "#" + hex;
}
function onAppThemeColorChanged(event) {
// Should get a latest HostEnvironment object from application.
var skinInfo = JSON.parse(window.__adobe_cep__.getHostEnvironment()).appSkinInfo;
// Gets the style information such as color info from the skinInfo,
// and redraw all UI controls of your extension according to the style info.
updateThemeWithAppSkinInfo(skinInfo);
}
/**
* Load JSX file into the scripting context of the product. All the jsx files in
* folder [ExtensionRoot]/jsx will be loaded.
*/
function loadJSX() {
var csInterface = new CSInterface();
var extensionRoot = csInterface.getSystemPath(SystemPath.EXTENSION) + "/jsx/";
csInterface.evalScript('$._ext.evalFiles("' + extensionRoot + '")');
}
function evalScript(script, callback) {
new CSInterface().evalScript(script, callback);
}
function onClickButton(ppid) {
if(ppid == "FLPR"){
var jsfl = 'fl.createDocument(); fl.getDocumentDOM().addNewText({left:100, top:100, right:300, bottom:300} , "Hello Flash!" ); ';
evalScript(jsfl);
} else {
var extScript = "$._ext_" + ppid + ".run()";
evalScript(extScript);
}
}
|
/*
First Roll
1 2 3 4 5 6
S 1 ! @ # $ % ^
e 2 & * ( ) - =
c 3 + [ ] { } \
o 4 | ` ; : ' "
n 5 < > / ? . ,
d 6 ~ _ 3 5 7 9
*/
var special = {
11: "!",
12: "&",
13: "+",
14: "|",
15: "<",
16: "~",
21: "@",
22: "*",
23: "[",
24: "`",
25: ">",
26: "_",
31: "#",
32: "(",
33: "]",
34: ";",
35: "/",
36: "3",
41: "$",
42: ")",
43: "{",
44: ":",
45: "?",
46: "5",
51: "%",
52: "-",
53: "}",
54: "'",
55: ".",
56: "7",
61: "^",
62: "=",
63: "\\",
64: "\"",
65: ",",
66: "9"
};
|
import Ember from 'ember';
export default Ember.Component.extend({
hasErrors: Ember.computed.notEmpty('model.errors.[]')
});
|
import fetch from '../api'
import config from '../config'
export const login = (source, token) => fetch(
'POST',
`${config.API_URL}/login`,
{},
false,
{'X-Auth-Source': source, 'X-Auth-Token': token}
)
|
var Taco = Taco || {};
Taco.Util = Taco.Util || {};
Taco.Util.HTML = Taco.Util.HTML || {};
Taco.Util.HTML.render = function(str, html) {
html = (typeof html != 'undefined')
? html
: false;
return (html === true)
? str
: Taco.Util.Str.htmlEntities(str);
};
Taco.Util.HTML.attribs = function(attribs, leading_space) {
leading_space = (typeof leading_space != 'undefined')
? leading_space
: true;
if(Taco.Util.Obj.getObjectLength(attribs) < 1) return '';
var out = [];
for(var key in attribs) {
var value = attribs[key];
value = (typeof value == 'object') ? Taco.Util.Obj.objectJoin(' ', value) : value;
out.push(key + '="' + String(value).replace(/\"/, '\"') + '"');
}
return ((leading_space) ? ' ' : '') + out.join(' ');
};
Taco.Util.HTML.getTextInputTypes = function() {
return [
'text',
'image',
'file',
'search',
'email',
'url',
'tel',
'number',
'range',
'date',
'month',
'week',
'time',
'datetime',
'datetime-local',
'color'
];
};
Taco.Util.HTML.tag = function(element_type, body, attribs, close, is_html) {
body = (typeof body == 'undefined' || body === null)
? ''
: body;
attribs = (typeof attribs == 'undefined')
? []
: attribs;
close = (typeof close == 'undefined')
? true
: close;
is_html = (typeof is_html == 'undefined')
? false
: is_html;
var not_self_closing = ['a', 'div', 'iframe', 'textarea'];
var is_self_closing = false;
if(close && Taco.Util.General.empty(body) && !Taco.Util.Arr.inArray(
element_type.toLowerCase(),
not_self_closing
)) {
is_self_closing = true;
}
if(is_self_closing) {
return '<' + element_type + this.attribs(attribs) + ' />';
}
return [
'<' + element_type + this.attribs(attribs) + '>',
this.render(body, is_html),
(close) ? '</' + element_type + '>' : ''
].join('');
};
Taco.Util.HTML.selecty = function(options, selected, attribs) {
selected = (typeof selected != 'undefined')
? selected
: null;
attribs = (typeof attribs != 'undefined')
? attribs
: [];
var htmls = [];
htmls.push(this.tag('select', null, attribs, false));
if(Taco.Util.Obj.isIterable(options)) {
for(var key in options) {
value = options[key];
var option_attribs = { value: key };
if(String(selected) === String(value)) {
option_attribs.selected = 'selected';
}
htmls.push(this.tag('option', value, option_attribs));
}
}
htmls.push('</select>');
return htmls.join("\n");
};
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { emailChanged, passwordChanged, signinUser } from '../core/actions';
import { Container, Content, Form, Item, Input, Grid, Col, Spinner, Toast, Icon, Button, Text } from 'native-base';
class Login extends Component {
static navigationOptions = {
title: 'Login',
header: {
backTitle: null,
visible: false,
}
};
onLogin() {
const { email, password, navigation } = this.props;
this.props.signinUser(navigation, email, password);
}
onRegister() {
this.props.navigation.navigate('Register');
}
componentWillMount() {
}
onEmailChange(text) {
this.props.emailChanged(text);
}
onPasswordChange(text) {
this.props.passwordChanged(text);
}
renderSpinner() {
if (this.props.loading) {
return (<Spinner />);
} else {
return (
<Grid>
<Col>
<Button full rounded onPress={this.onLogin.bind(this)}>
<Text>Login</Text>
</Button>
</Col>
<Col>
<Button full rounded onPress={this.onRegister.bind(this)}>
<Text>Register</Text>
</Button>
</Col>
</Grid>
);
}
}
render() {
const { navigate } = this.props.navigation;
return (
<Container>
<Content>
<Form>
<Item rounded>
<Input placeholder="E-Mail" value={this.props.email} keyboardType='email-address'
onChangeText={this.onEmailChange.bind(this)} />
</Item>
<Item rounded>
<Input placeholder="Password" value={this.props.password} secureTextEntry
onChangeText={this.onPasswordChange.bind(this)} />
</Item>
<Item>
<Text style={styles.errorTextStyle}>
{this.props.loginError}
</Text>
</Item>
<Item last>
{this.renderSpinner()}
</Item>
</Form>
</Content>
</Container>
);
}
}
const styles = {
errorTextStyle: {
fontSize: 20,
alignSelf: 'center',
color: 'red'
},
imageStyle: {
width: 50,
height: 50,
}
};
const mapStateToProps = ({ authReducer }) => {
const { email, password, loginError, loading } = authReducer;
return { email, password, loginError, loading };
};
export default connect(mapStateToProps, {
emailChanged, passwordChanged, signinUser
})(Login);
|
Miogen.require(['Component.BaseComponent',
'Component.Button'], function () {
Miogen.define('Component.Toolbar', Miogen.Component.BaseComponent.extend({
construct: function (cfg) {
this._super(cfg);
},
build: function (cb) {
var t = this;
//
// t.addComponent(new Miogen.Component.Button());
// t.addComponent(new Miogen.Component.Button());
// Render the base widget and newly added components
this._super(function () {
cb.call(this);
this.el.addClass('toolbar');
});
//this.el = $('<div class="miogen-widget"><div class="pad">Collection widget</div></div>');
}
}));
}); |
/**
* syntaxEnvironment.js
* Andrea Tino - 2015
*/
/**
* Main collection point for types to be rendered.
*/
module.exports = function() {
var tsClass = require('./class.js');
var tsInterface = require('./interface.js');
var tsEnum = require('./enum.js');
// Configuration: { classIds = [], interfaceIds = [], enumIds = [] }
var config = null;
// Associative arrays: id -> Typescript mapper (ts[Class|Interface|Enum])
var classes = {};
var interfaces = {};
var enums = {};
return {
/**
* Initializes the module.
* _config: Configuration:
* { classIds = [], interfaceIds = [], enumIds = [] }
*/
initialize: function(_config) {
if (!_config) {
throw 'Error: Configuration cannot be null or undefined!';
}
config = _config;
},
/**
* Builds TypeScript classes.
*/
buildClasses: function() {
},
/**
* Builds TypeScript interfaces.
*/
buildInterfaces: function() {
},
/**
* Build enums.
*/
buildEnums: function() {
}
};
};
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("specialchar","id",{euro:"Tanda Euro",lsquo:"Left single quotation mark",rsquo:"Right single quotation mark",ldquo:"Left double quotation mark",rdquo:"Right double quotation mark",ndash:"En dash",mdash:"Em dash",iexcl:"Inverted exclamation mark",cent:"Cent sign",pound:"Pound sign",curren:"Currency sign",yen:"Tanda Yen",brvbar:"Broken bar",sect:"Section sign",uml:"Diaeresis",copy:"Tanda Hak Cipta",ordf:"Feminine ordinal indicator",laquo:"Left-pointing double angle quotation mark",
not:"Not sign",reg:"Tanda Telah Terdaftar",macr:"Macron",deg:"Degree sign",sup2:"Superscript two",sup3:"Superscript three",acute:"Acute accent",micro:"Micro sign",para:"Pilcrow sign",middot:"Middle dot",cedil:"Cedilla",sup1:"Superscript one",ordm:"Masculine ordinal indicator",raquo:"Right-pointing double angle quotation mark",frac14:"Vulgar fraction one quarter",frac12:"Vulgar fraction one half",frac34:"Vulgar fraction three quarters",iquest:"Inverted question mark",Agrave:"Latin capital letter A with grave accent",
Aacute:"Latin capital letter A with acute accent",Acirc:"Latin capital letter A with circumflex",Atilde:"Latin capital letter A with tilde",Auml:"Latin capital letter A with diaeresis",Aring:"Latin capital letter A with ring above",AElig:"Latin capital letter Æ",Ccedil:"Latin capital letter C with cedilla",Egrave:"Latin capital letter E with grave accent",Eacute:"Latin capital letter E with acute accent",Ecirc:"Latin capital letter E with circumflex",Euml:"Latin capital letter E with diaeresis",Igrave:"Latin capital letter I with grave accent",
Iacute:"Latin capital letter I with acute accent",Icirc:"Latin capital letter I with circumflex",Iuml:"Latin capital letter I with diaeresis",ETH:"Latin capital letter Eth",Ntilde:"Latin capital letter N with tilde",Ograve:"Latin capital letter O with grave accent",Oacute:"Latin capital letter O with acute accent",Ocirc:"Latin capital letter O with circumflex",Otilde:"Latin capital letter O with tilde",Ouml:"Latin capital letter O with diaeresis",times:"Multiplication sign",Oslash:"Latin capital letter O with stroke",
Ugrave:"Latin capital letter U with grave accent",Uacute:"Latin capital letter U with acute accent",Ucirc:"Latin capital letter U with circumflex",Uuml:"Latin capital letter U with diaeresis",Yacute:"Latin capital letter Y with acute accent",THORN:"Latin capital letter Thorn",szlig:"Latin small letter sharp s",agrave:"Latin small letter a with grave accent",aacute:"Latin small letter a with acute accent",acirc:"Latin small letter a with circumflex",atilde:"Latin small letter a with tilde",auml:"Latin small letter a with diaeresis",
aring:"Latin small letter a with ring above",aelig:"Latin small letter æ",ccedil:"Latin small letter c with cedilla",egrave:"Latin small letter e with grave accent",eacute:"Latin small letter e with acute accent",ecirc:"Latin small letter e with circumflex",euml:"Latin small letter e with diaeresis",igrave:"Latin small letter i with grave accent",iacute:"Latin small letter i with acute accent",icirc:"Latin small letter i with circumflex",iuml:"Latin small letter i with diaeresis",eth:"Latin small letter eth",
ntilde:"Latin small letter n with tilde",ograve:"Latin small letter o with grave accent",oacute:"Latin small letter o with acute accent",ocirc:"Latin small letter o with circumflex",otilde:"Latin small letter o with tilde",ouml:"Latin small letter o with diaeresis",divide:"Division sign",oslash:"Latin small letter o with stroke",ugrave:"Latin small letter u with grave accent",uacute:"Latin small letter u with acute accent",ucirc:"Latin small letter u with circumflex",uuml:"Latin small letter u with diaeresis",
yacute:"Latin small letter y with acute accent",thorn:"Latin small letter thorn",yuml:"Latin small letter y with diaeresis",OElig:"Latin capital ligature OE",oelig:"Latin small ligature oe",372:"Latin capital letter W with circumflex",374:"Latin capital letter Y with circumflex",373:"Latin small letter w with circumflex",375:"Latin small letter y with circumflex",sbquo:"Single low-9 quotation mark",8219:"Single high-reversed-9 quotation mark",bdquo:"Double low-9 quotation mark",hellip:"Horizontal ellipsis",
trade:"Trade mark sign",9658:"Black right-pointing pointer",bull:"Bullet",rarr:"Rightwards arrow",rArr:"Rightwards double arrow",hArr:"Left right double arrow",diams:"Black diamond suit",asymp:"Almost equal to"}); |
;(function() {
MozVisibility = {
_MAX_TRIES: 10,
_date: new Date,
_tries: 0,
_timer: null,
_isVisible: undefined,
_proxy: function(fn, context) {
context = context || window;
return function() {
fn.apply(context, arguments);
};
},
_getEvent: function() {
if (!this._event) {
this._event = document.createEvent('HTMLEvents');
this._event.initEvent('mozvisibilitychange', true, true);
this._event.eventName = 'mozvisibilitychange';
}
return this._event;
},
_setVisibilityState: function(state) {
this._isVisible = (state === 'visible');
document.mozVisibilityState = state;
document.mozHidden = !this._isVisible;
document.dispatchEvent(this._getEvent());
},
_visibilityCheck: function() {
this._date = new Date;
this._tries = 0;
this._timer = setTimeout(this._invisibilityCheckTimeout, 0);
},
_invisibilityCheckTimeoutTemplate: function() {
var newdate = new Date;
var delta = newdate - this._date;
this._date = newdate;
this._tries++;
if (delta > 1000) {
this._setVisibilityState('hidden');
} else if (this._tries < this._MAX_TRIES) {
this._timer = setTimeout(this._invisibilityCheckTimeout, 0);
}
},
_onFocus: function() {
clearTimeout(this._timer);
if (!this._isVisible) {
this._setVisibilityState('visible');
}
},
_onBlur: function() {
if (!this._isVisible) {
return;
}
this._visibilityCheck();
},
canBeEmulated: function() {
var rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
ua = navigator.userAgent.toLowerCase();
var match = ua.indexOf('compatible') < 0 && rmozilla.exec(ua) || [];
return (window.top === window && // not in IFRAME
match[2] && parseInt(match[2]) >= 5 && // Firefox 5.0+
!document.visibilityState && !document.MozVisibilityState); // visibility API is not already supported
},
emulate: function() {
if (!this.canBeEmulated()) {
return false;
}
this._invisibilityCheckTimeout = this._proxy(this._invisibilityCheckTimeoutTemplate, this);
window.addEventListener("focus", this._proxy(this._onFocus, this), false);
window.addEventListener("blur", this._proxy(this._onBlur, this), false);
this._visibilityCheck();
return true;
}
};
MozVisibility.emulate();
})(); |
const {
createCompileTsFilesTask,
createDeleteDistFolderTask,
createLintTsFilesTask,
createRunIntegrationTestsTask,
createRunUnitTestsTask,
} = require("../tasks");
const {parallel, series} = require("gulp");
const failAfterError = true;
exports.createBuildWorkflow = (moduleName) =>
series(
createDeleteDistFolderTask(moduleName),
parallel(
createCompileTsFilesTask(moduleName, "main.js", failAfterError),
createCompileTsFilesTask(moduleName, "unit.js", failAfterError),
createCompileTsFilesTask(moduleName, "integration.js", failAfterError)
),
createLintTsFilesTask(moduleName, failAfterError),
createRunUnitTestsTask(moduleName, failAfterError),
createRunIntegrationTestsTask(moduleName, failAfterError)
);
|
/* jQuery OSM field
2014 by Thomas netAction Schmidt for Sinnwerkstatt
https://www.sinnwerkstatt.com/
MIT License */
(function ($) {
$.fn.osmfield = function () {
return this.each(function () {
// Create HTML elements for osmfield
var lang, map, marker, tile_url,
idAttribute = $(this).attr('id'),
idLatElement = $(this).data('lat-field'),
idLonElement = $(this).data('lon-field'),
idDataElement = $(this).data('data-field'),
osmfieldElement = $(this);
if (idLatElement === undefined) {
idLatElement = '#' + idAttribute + '_lat';
} else {
idLatElement = '#id_' + idLatElement;
}
if (idLonElement === undefined) {
idLonElement = '#' + idAttribute + '_lon';
} else {
idLonElement = '#id_' + idLonElement;
}
if (idDataElement === undefined) {
idDataElement = '#' + idAttribute + '_data';
} else {
idDataElement = '#id_' + idDataElement;
}
$(this).addClass('osmfield-input');
// Create map container when not existent.
// Wrapper is only for CSS.
if (!$('#' + idAttribute + '-map').length) {
$(this).before('<div class="osmfield-wrapper"><div id="' + idAttribute + '-map"></div></div>');
}
$(this).data('lat-element', $(idLatElement));
$(this).data('lng-element', $(idLonElement));
$(this).data('data-element', $(idDataElement));
$(this).data('map-element', $('#' + idAttribute + '-map'));
$(this).data('map-element').addClass('osmfield-map');
// initialize Leaflet map, tile layer and marker
map = L.map(osmfieldElement.data('map-element')[0]).setView([0, 0], 15);
tile_url = (window.location.protocol === 'http:') ?
'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}@2x.png' :
'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png';
L.tileLayer(tile_url, {
attribution: 'CartoDB | Open Streetmap',
maxZoom: 18
}).addTo(map);
marker = L.marker([0, 0], {draggable: true}).addTo(map);
// bubble up the dom to find out language or use 'en' as default
lang = osmfieldElement.closest('[lang]').attr('lang');
if (lang) {
lang = lang.split('-');
lang = lang[0];
} else {
lang = 'en';
}
osmfieldElement.data('language', lang);
// magic that happens when marker in map is dragged
(function (osmfieldElement) {
marker.on('dragend', function (event) {
var language = osmfieldElement.data('language'),
position = event.target.getLatLng(),
url = 'https://nominatim.openstreetmap.org/reverse?json_callback=?',
zoom = map.getZoom();
map.panTo(position);
osmfieldElement.data('lat-element').val(position.lat);
osmfieldElement.data('lng-element').val(position.lng);
$.getJSON(
url,
{
format: 'json',
lat: position.lat,
lon: position.lng,
zoom: zoom,
addressdetails: 1,
'accept-language': language
},
function (data) {
osmfieldElement.val(data.display_name);
osmfieldElement.data('data-element').val(JSON.stringify(data));
}
);
});
})(osmfieldElement);
// User enters something in INPUT field
osmfieldElement.on('propertychange keyup input paste change', function () {
if ($(this).data('oldvalue') === $(this).val()) {
return;
}
$(this).data('oldvalue', $(this).val());
function search(nameInputElement) {
var language = nameInputElement.data('language'),
url = 'https://nominatim.openstreetmap.org/search?json_callback=?';
(function (osmfieldElement) {
// We could kill previous ajax requests here.
$.getJSON(
url,
{
format: 'json',
q: nameInputElement.val(),
addressdetails: 1,
'accept-language': language
},
function (data) {
// coordinates found for this address?
if (data.length) {
var lat = data[0].lat,
lng = data[0].lon,
// name = data[0].display_name,
newLatLng = new L.LatLng(lat, lng),
eldata = JSON.stringify(data[0]);
osmfieldElement.data('lat-element').val(lat);
osmfieldElement.data('lng-element').val(lng);
osmfieldElement.data('data-element').val(eldata);
marker.setLatLng(newLatLng);
map.panTo(newLatLng);
} else {
osmfieldElement.data('map-element').slideUp();
osmfieldElement.data('lat-element').val('');
osmfieldElement.data('lng-element').val('');
osmfieldElement.data('data-element').val('');
}
// Show map when INPUT has focus and coordinates are known
if (
osmfieldElement.is(":focus") &&
osmfieldElement.data('lat-element').val() &&
osmfieldElement.data('lng-element').val()
) {
osmfieldElement.data('map-element').slideDown(function () {
window.dispatchEvent(new Event('resize'));
});
} else {
osmfieldElement.data('map-element').slideUp();
}
}
);
})(nameInputElement);
}
// Wait 500ms for INPUT updates until Ajax request
clearTimeout($.data(this, 'timer'));
var nameInputElement = $(this),
wait = setTimeout(function () { search(nameInputElement); }, 500);
$(this).data('timer', wait);
});
// Initialize INPUT, map and data attributes
osmfieldElement.data('map-element').hide();
// Use start values if given
if (osmfieldElement.data('lat-element').val() &&
osmfieldElement.data('lng-element').val()) {
var newLatLng = new L.LatLng(
osmfieldElement.data('lat-element').val(),
osmfieldElement.data('lng-element').val()
);
marker.setLatLng(newLatLng);
map.panTo(newLatLng);
} else {
// Maybe OpenStreetMap has coordinates or hide the map
osmfieldElement.trigger('change');
}
// Hide map when clicking outside
$(document).click(function (event) {
// A child of INPUT or map was clicked
var thisosmfield = $(event.target).closest('.osmfield-input, .osmfield-map');
if (thisosmfield.length) {
// hide all maps except of this
if (thisosmfield.hasClass('osmfield-input')) {
thisosmfield = thisosmfield.data('map-element');
}
$('.osmfield-map').not(thisosmfield).slideUp();
} else {
// hide all
$('.osmfield-map').slideUp();
}
});
// Show map when INPUT gets focus and position is known
(function (osmfieldElement) {
osmfieldElement.focus(function () {
if (osmfieldElement.data('lat-element').val() &&
osmfieldElement.data('lng-element').val()) {
osmfieldElement.data('map-element').slideDown(function () {
window.dispatchEvent(new Event('resize'));
});
}
});
})(osmfieldElement);
}); // each osmfield element
}; // jQuery plugin end
}(jQuery));
|
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'source-map',
entry: {
app: './src/main.js'
},
output: {
filename: '[name].min.js',
path: path.join(__dirname, 'dist'),
publicPath: ''
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production'),
},
'__DEV_TOOLS__': false
}),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
}),
//new ExtractTextPlugin('app.css', { allChunks: true }),
new HtmlWebpackPlugin({
title: 'Redux Boilerplate',
filename: 'index.html',
template: 'index.template.html',
favicon: path.join(__dirname, 'assets/images/favicon.ico')
})
],
module: {
loaders: [
{ test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader!cssnext-loader') },
{ test: /\.js$/, loaders: ['babel'], exclude: /node_modules/ }
]
},
cssnext: {
browsers: 'last 2 versions'
}
};
|
$(function () {
$.widget("as24.qr", {
_create: function () {
var self = this;
$(self.element).find('[data-description="QR-Code Generation"]').find("p").hide();
$(self.element).find('[data-generate="qr-code"]').click(function () {
$(self.element).find('[data-description="QR-Code Generation"]').find("p").show();
var url = $(self.element).find('[name="urlQRCode"]').val();
var featureName = $(self.element).find('[name="name"]').val();
var featureEnabled = url + "?" + $.param({ "FeatureBee": '#' + featureName + "=true#" });
var featureDisabled = url + "?" + $.param({ "FeatureBee": '#' + featureName + "=false#" });
$(self.element).find('#qrcode_enable').empty();
$(self.element).find('#qrcode_enable').qrcode(featureEnabled);
$(self.element).find('#qrcode_disable').empty();
$(self.element).find('#qrcode_disable').qrcode(featureDisabled);
});
}
});
}) |
(function () {
'use strict';
angular
.module('app.web')
.service('fileUpload', Service);
Service.$inject = ['$http'];
function Service($http) {
this.uploadFile = uploadFile;
////////////////
function uploadFile(file, url, done) {
var fd = new FormData();
fd.append('file',file);
$http.post(url, fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).success(function (response) {
done(null, response);
}).error(function (e) {
done(e, null);
});
}
}
})(); |
function util() {
var self = this;
if (typeof Object.beget !== 'function') {
Object.beget = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
}
};
exports.util = new util(); |
// Heavily influenced by Mike Bostock's Scatter Matrix example
// http://mbostock.github.io/d3/talk/20111116/iris-splom.html
//
ScatterMatrix = function(url, data, dom_id) {
this.__url = url;
if (data === undefined || data === null) {
this.__data = undefined;
} else {
this.__data = data;
}
this.__cell_size = 80;
if (dom_id === undefined) {
this.__dom_id = 'body';
} else {
this.__dom_id = dom_id;
}
};
ScatterMatrix.prototype.cellSize = function(n) {
this.__cell_size = n;
return this;
};
ScatterMatrix.prototype.onData = function(cb) {
if (this.__data) {
cb();
return;
}
var self = this;
d3.csv(self.__url, function(data) {
//self.__data = data;
cb();
});
};
ScatterMatrix.prototype.render = function() {
var self = this;
var container = d3.select(this.__dom_id).append('div')
.attr('class', 'scatter-matrix-container');
var control = container.append('div')
.attr('class', 'scatter-matrix-control toggled')
.style('background-color', '#ffffff');
var svg = container.append('div')
.attr('class', 'scatter-matrix-svg')
.html('<em>Loading data...</em>');
this.onData(function() {
var data = self.__data; //// NOTE: passing raw data to local data
// Divide variables into string and numeric variables
var original_numeric_variables = [];
self.__numeric_variables = [];
for (k in data[0]) {
var is_numeric = true;
data.forEach(function(d) {
var v = d[k];
if (isNaN(+v)) is_numeric = false;
});
if (is_numeric) {
self.__numeric_variables.push(k);
original_numeric_variables.push(k);
}
}
var scid = 0;
data.forEach(function(d) {
d.scid = scid;
scid += 1;
});
//console.log(string_variables);//------------------------------------------------------------------
// Add controls on the left
var size_control = control.append('div').attr('class', 'scatter-matrix-size-control');
var color_control = control.append('div').attr('class', 'scatter-matrix-color-control');
var filter_control = control.append('div').attr('class', 'scatter-matrix-filter-control');
var variable_control = control.append('div').attr('class', 'scatter-matrix-variable-control');
var drill_control = control.append('div').attr('class', 'scatter-matrix-drill-control');
// shared control states
var to_include = self.__numeric_variables.slice(-3, -1);
var color_variable = undefined;
var selected_colors = undefined;
var drill_variables = [];
function set_filter(variable) {
filter_control.selectAll('*').remove();
if (variable) {
// Get unique values for this variable
var values = [];
data.forEach(function(d) {
var v = d[variable];
if (values.indexOf(v) < 0) {
values.push(v);
}
});
selected_colors = values.slice(0, 5);
var filter_li =
filter_control
.append('p').text('Filter by ' + variable + ': ')
.append('ul')
.selectAll('li')
.data(values)
.enter().append('li');
filter_li.append('input')
.attr('type', 'checkbox')
.attr('checked', function(d, i) {
if (selected_colors.indexOf(d) >= 0)
return 'checked';
return null;
})
.on('click', function(d, i) {
var new_selected_colors = [];
for (var j in selected_colors) {
var v = selected_colors[j];
if (v !== d || this.checked) {
new_selected_colors.push(v);
}
}
if (this.checked) {
new_selected_colors.push(d);
}
selected_colors = new_selected_colors;
self.__draw(self.__cell_size, svg, color_variable,
selected_colors, to_include, drill_variables);
});
filter_li.append('label')
.html(function(d) {
return d;
});
}
}
// -----------------------------------Here starts the control menu list-------------------------------------------------------//
size_a = size_control.append('div').attr('class', 'btn-group col-xs-12').style('margin-bottom', '20px');
var orgSize = self.__cell_size;
size_a.append('a')
.attr('class', 'btn btn-default btn-xs')
.attr('href', 'javascript:void(0);')
.html('-')
.on('click', function() {
self.__cell_size -= 50;
self.__draw(self.__cell_size, svg, color_variable, selected_colors, to_include, drill_variables);
});
size_a.append('a')
.attr('class', 'btn btn-default btn-xs')
.attr('href', 'javascript:void(0);')
.html('Change plot size')
.on('click', function() {
self.__cell_size = orgSize;
self.__draw(self.__cell_size, svg, color_variable, selected_colors, to_include, drill_variables);
});
size_a.append('a')
.attr('class', 'btn btn-default btn-xs')
.attr('href', 'javascript:void(0);')
.html('+')
.on('click', function() {
self.__cell_size += 50;
self.__draw(self.__cell_size, svg, color_variable, selected_colors, to_include, drill_variables);
});
//set to full screen mode;-------------------------------------------------------------------------------------------------
var isRightChartFullScreenToggled = false;
var windowHeight = window.innerHeight;
var originalCellSize = self.__cell_size;
$("#scatter-fullscreen-toggle").click(function(e) {
isRightChartFullScreenToggled = !isRightChartFullScreenToggled;
if (isRightChartFullScreenToggled) {
self.__cell_size = (windowHeight - 250) / 2;
d3.selectAll(".cell circle").attr("r", "3");
} else {
self.__cell_size = originalCellSize;
d3.selectAll(".cell circle").attr("r", "1");
}
self.__draw(self.__cell_size, svg, color_variable, selected_colors, to_include, drill_variables);
});
var variable_li =
variable_control
.append('p').text('Vertical Variables: ')
.append('ul')
.selectAll('li')
.data(self.__numeric_variables)
.enter().append('li');
variable_li.append('input')
.attr('type', 'checkbox')
.attr('checked', function(d, i) {
if (to_include.indexOf(d) >= 0) return "checked";
return null;
})
.on('click', function(d, i) {
var new_to_include = [];
for (var j in to_include) {
var v = to_include[j];
if (v !== d || this.checked) {
new_to_include.push(v);
}
}
if (this.checked) {
new_to_include.push(d);
}
to_include = new_to_include;
self.__draw(self.__cell_size, svg, color_variable, selected_colors, to_include, drill_variables);
});
variable_li.append('label')
.html(function(d) {
var i = self.__numeric_variables.indexOf(d) + 1;
return '' + i + ': ' + d;
});
// drill_li =
// drill_control
// .append('p').text('Horizontal Variable:')
// .append('ul')
// .selectAll('li')
// .data(original_numeric_variables)
// .enter().append('li');
//
// drill_li.append('input')
// .attr('type', 'checkbox')
// .on('click', function(d, i) {
// var new_drill_variables = [];
// for (var j in drill_variables) {
// var v = drill_variables[j];
// if (v !== d || this.checked) {
// new_drill_variables.push(v);
// }
// }
// if (this.checked) {
// new_drill_variables.push(d);
// }
// drill_variables = new_drill_variables;
// self.__draw(self.__cell_size, svg, color_variable, selected_colors, to_include, drill_variables);
// });
// drill_li.append('label')
// .html(function(d) {
// return d;
// });
self.__draw(self.__cell_size, svg, color_variable, selected_colors, to_include, drill_variables);
});
};
// NOTE: unique id for each Circle
function getCircleID(d) {
var id = "scatter_" + d.scid;
return id;
}
ScatterMatrix.prototype.__draw = function(cell_size, container_el, color_variable, selected_colors, to_include, drill_variables) {
var self = this;
this.onData(function() {
var data = self.__data;
// filter data by selected colors
if (color_variable && selected_colors) {
data = [];
self.__data.forEach(function(d) {
if (selected_colors.indexOf(d[color_variable]) >= 0) {
data.push(d);
}
});
}
container_el.selectAll('*').remove();
// If no data, don't do anything
if (data.length === 0) {
return;
}
// Parse headers from first row of data
var variables_to_draw = to_include.slice(0);
// Get values of the string variable
var colors = [];
if (color_variable) {
// Using self.__data (all data), instead of data (data to be drawn), so
// our css classes are consistent when we filter by value.
self.__data.forEach(function(d) {
var s = d[color_variable];
if (colors.indexOf(s) < 0) {
colors.push(s);
}
});
}
function color_class(d) {
var c = d;
if (color_variable && d[color_variable]) {
c = d[color_variable];
}
return colors.length > 0 ? 'color-' + colors.indexOf(c) : 'color-2';
}
// Size parameters
var size = cell_size,
padding = 10,
axis_width = 20,
axis_height = 15,
legend_width = 0,
label_height = 15;
// Get x and y scales for each numeric variable
var x = {},
y = {};
variables_to_draw.forEach(function(trait) {
// Coerce values to numbers.
data.forEach(function(d) {
d[trait] = +d[trait];
});
var value = function(d) {
return d[trait];
},
domain = [d3.min(data, value), d3.max(data, value)],
range_x = [padding / 2, size - padding / 2],
range_y = [padding / 2, size - padding / 2];
x[trait] = d3.scale.linear().domain(domain).range(range_x);
y[trait] = d3.scale.linear().domain(domain).range(range_y.reverse());
});
// When drilling, user select one or more variables. The first drilled
// variable becomes the x-axis variable for all columns, and each column
// contains only data points that match specific values for each of the
// drilled variables other than the first.
var drill_values = [];
var drill_degrees = []
drill_variables.forEach(function(variable) {
// Skip first one, since that's just the x axis
if (drill_values.length == 0) {
drill_values.push([]);
drill_degrees.push(1);
} else {
var values = [];
data.forEach(function(d) {
var v = d[variable];
if (v !== undefined && values.indexOf(v) < 0) {
values.push(v);
}
});
values.sort();
drill_values.push(values);
drill_degrees.push(values.length);
}
});
var total_columns = 1;
drill_degrees.forEach(function(d) {
total_columns *= d;
});
// Pick out stuff to draw on horizontal and vertical dimensions
if (drill_variables.length > 0) {
// First drill is now the x-axis variable for all columns
x_variables = [];
for (var i = 0; i < total_columns; i++) {
x_variables.push(drill_variables[0]);
}
} else
x_variables = variables_to_draw.slice(0);
if (drill_variables.length > 0) {
// Don't draw any of the "drilled" variables in vertical dimension
y_variables = [];
variables_to_draw.forEach(function(variable) {
if (drill_variables.indexOf(variable) < 0) {
y_variables.push(variable);
}
});
} else
y_variables = variables_to_draw.slice(0);
y_variables = y_variables.reverse();
var filter_descriptions = 0;
if (drill_variables.length > 1) {
filter_descriptions = drill_variables.length - 1;
}
// Formatting for axis
var intf = d3.format('d');
var fltf = d3.format('.f');
var scif = d3.format('.1e');
// Brush - for highlighting regions of data
var brush = d3.svg.brush()
.on("brushstart", brushstart)
.on("brush", brush)
.on("brushend", brushend);
// Root panel
var svg = container_el.append("svg:svg")
.attr("width", label_height + size * x_variables.length + axis_width + padding + legend_width)
.attr("height", size * y_variables.length + axis_height + label_height + label_height * filter_descriptions)
.append("svg:g")
.attr("transform", "translate(" + label_height + ",0)");
// Push legend to the side
var legend = svg.selectAll("g.legend")
.data(colors)
.enter().append("svg:g")
.attr("class", "legend")
.attr("transform", function(d, i) {
return "translate(" + (label_height + size * x_variables.length + padding) + "," + (i * 20 + 10) + ")";
});
legend.append("svg:text")
.attr("x", 12)
.attr("dy", ".31em")
.text(function(d) {
return d;
});
var shorten = function(s) {
if (s.length > 16)
return s.slice(0, 12) + '...' + s.slice(s.length - 8, s.length);
return s;
};
var reshape_axis = function(axis, k) {
axis.ticks(5)
.tickFormat(function(d) {
if (Math.abs(+d) > 10000 || (Math.abs(d) < 0.001 && Math.abs(d) != 0)) {
return scif(d);
}
if (parseInt(d) == +d) {
return intf(d);
}
return fltf(d);
});
return axis;
};
// Draw X-axis
svg.selectAll("g.x.axis")
.data(x_variables)
.enter().append("svg:g")
.attr("class", "x axis")
.attr("transform", function(d, i) {
return "translate(" + i * size + ",0)";
})
.each(function(k) {
var axis = reshape_axis(d3.svg.axis(), k);
axis.tickSize(size * y_variables.length);
d3.select(this).call(axis.scale(x[k]).orient('bottom'));
});
// Draw Y-axis
svg.selectAll("g.y.axis")
.data(y_variables)
.enter().append("svg:g")
.attr("class", "y axis")
.attr("transform", function(d, i) {
return "translate(0," + i * size + ")";
})
.each(function(k) {
var axis = reshape_axis(d3.svg.axis(), k);
axis.tickSize(size * x_variables.length);
d3.select(this).call(axis.scale(y[k]).orient('right'));
});
// Draw scatter plot
var cell = svg.selectAll("g.cell")
.data(cross(x_variables, y_variables))
.enter().append("svg:g")
.attr("class", "cell")
.attr("transform", function(d) {
return "translate(" + d.i * size + "," + d.j * size + ")";
})
.each(plot);
// Add titles for y variables
cell.filter(function(d) {
return d.i == 0;
}).append("svg:text")
.attr("x", padding - size)
.attr("y", -label_height)
.attr("dy", ".71em")
.attr("transform", function(d) {
return "rotate(-90)";
})
.text(function(d) {
var s = self.__numeric_variables.indexOf(d.y) + 1;
s = '' + s + ': ' + d.y;
return shorten(s);
});
function plot(p) {
var data_to_draw = data;
// If drilling, compute what values of the drill variables correspond to
// this column.
//
var filter = {};
if (drill_variables.length > 1) {
var column = p.i;
var cap = 1;
for (var i = drill_variables.length - 1; i > 0; i--) {
var var_name = drill_variables[i];
var var_value = undefined;
if (i == drill_variables.length - 1) {
// for the last drill variable, we index by %
var_value = drill_values[i][column % drill_degrees[i]];
} else {
// otherwise divide by capacity of subsequent variables to get value array index
var_value = drill_values[i][parseInt(column / cap)];
}
filter[var_name] = var_value;
cap *= drill_degrees[i];
}
data_to_draw = [];
data.forEach(function(d) {
var pass = true;
for (k in filter) {
if (d[k] != filter[k]) {
pass = false;
break;
}
}
if (pass === true) {
data_to_draw.push(d);
}
});
}
var cell = d3.select(this);
// Frame
cell.append("svg:rect")
.attr("class", "frame")
.attr("x", padding / 2)
.attr("y", padding / 2)
.attr("width", size - padding)
.attr("height", size - padding);
// Scatter plot dots
cell.selectAll("circle")
.data(data_to_draw)
.enter().append("svg:circle")
.attr("id", function(d) {
//console.log(d);
return getCircleID(d);
})
// .attr("class", "selected")
.attr("cx", function(d) {
return x[p.x](d[p.x]);
})
.attr("cy", function(d) {
return y[p.y](d[p.y]);
})
.attr("r",function(d){
return isRightChartFullScreenToggled?2:1;
});
// Add titles for x variables and drill variable values
if (p.j == y_variables.length - 1) {
cell.append("svg:text")
.attr("x", padding)
.attr("y", size + axis_height)
.attr("dy", ".71em")
.text(function(d) {
var s = self.__numeric_variables.indexOf(d.x) + 1;
s = '' + s + ': ' + d.x;
return shorten(s);
});
if (drill_variables.length > 1) {
var i = 0;
for (k in filter) {
i += 1;
cell.append("svg:text")
.attr("x", padding)
.attr("y", size + axis_height + label_height * i)
.attr("dy", ".71em")
.text(function(d) {
return shorten(filter[k] + ': ' + k);
});
}
}
}
// Brush
cell.call(brush.x(x[p.x]).y(y[p.y]));
}
// Clear the previously-active brush, if any
function brushstart(p) {
if (brush.data !== p) {
cell.call(brush.clear());
brush.x(x[p.x]).y(y[p.y]).data = p;
}
}
// Highlight selected circles
function brush(p) {
var e = brush.extent();
svg.selectAll(".cell circle").classed("faded", function(d) {
return e[0][0] <= d[p.x] && d[p.x] <= e[1][0] && e[0][1] <= d[p.y] && d[p.y] <= e[1][1] ? false : true;
});
}
// If brush is empty, select all circles
function brushend() {
if (brush.empty()) svg.selectAll(".scatter-matrix-svg .cell circle").classed("faded", true);
}
function cross(a, b) {
var c = [],
n = a.length,
m = b.length,
i, j;
for (i = -1; ++i < n;)
for (j = -1; ++j < m;) c.push({
x: a[i],
i: i,
y: b[j],
j: j
});
return c;
}
});
updateScatterChart(); //for selected data
highlightScatterDot();//for highlighted Data
update_sc_colorsOnly();
};
|
const times = require('lodash/times');
const {GameEngine} = require('../../lib/common/engine');
const {R, G, B, _} = require('../../lib/common/panel-league/util');
module.exports.testAdd = ((test) => {
const game = new GameEngine();
game.addEvent({
time: 0,
type: 'addGarbage',
slab: {x: 0, width: game.width, height: 1}
});
game.step();
const state = game.step();
test.expect(1);
test.strictEqual(state.garbage.length, 1, "No garbage slab found");
test.done();
});
module.exports.testFit = ((test) => {
const game = new GameEngine({initialRows: 0, width: 6});
game.addEvent({
time: 0,
type: 'addGarbage',
slab: {x: 0, width: 2, height: 1}
});
game.addEvent({
time: 1,
type: 'addGarbage',
slab: {x: 2, width: 2, height: 2}
});
times(100, () => game.step());
state = game.step();
test.expect(6);
for (let i = 0; i < 4; ++i) {
test.ok(state.blocks[i + state.width * (state.height - 1)].color, "Empty block found");
}
for (let i = 4; i < 6; ++i) {
test.ok(!state.blocks[i + state.width * (state.height - 1)].color, "Non-empty block found");
}
test.done();
});
module.exports.testOverhang = ((test) => {
const game = new GameEngine({initialRows: 0});
game.addEvent({
time: 0,
type: 'addGarbage',
slab: {x: 0, width: 1, height: 2}
});
game.addEvent({
time: 1,
type: 'addGarbage',
slab: {x: 0, width: game.width, height: 2}
});
times(100, () => game.step());
state = game.step();
test.expect(2 * game.width - 1);
for (let i = 1; i < game.width; ++i) {
test.ok(!state.blocks[i + state.width * (state.height - 1)].color, "Non-empty block found");
}
for (let i = 0; i < game.width; ++i) {
test.ok(state.blocks[i + state.width * (state.height - 3)].color, "Empty block found");
}
test.done();
});
module.exports.testShock = ((test) => {
setup = [
_, _, _, _, _, _,
_, _, _, _, _, _,
_, _, _, _, _, _,
_, _, _, _, _, _,
G, R, G, G, B, B,
];
const game = new GameEngine({width: 6, height: 5, colors: setup});
game.addEvent({
time: 0,
type: 'addGarbage',
slab: {x: 0, width: game.width, height: 2}
});
game.addEvent({
time: 1,
type: 'addGarbage',
slab: {x: 0, width: game.width, height: 2}
});
game.addEvent({
time: 101,
type: 'swap',
index: 24
});
test.expect(2 + 2 * game.width);
times(99, () => game.step());
let state = game.step();
let numGarbage = state.blocks.reduce((sum, block) => sum + block.garbage, 0);
test.strictEqual(numGarbage, game.width * 4, 'Not enough garbage found');
times(99, () => game.step());
state = game.step();
numGarbage = state.blocks.reduce((sum, block) => sum + block.garbage, 0);
test.strictEqual(numGarbage, game.width * 2, 'Garbage not released correctly');
// We don't control RNG here so prepare for rare matches.
const shift = game.width * !state.blocks[0].color;
for (let i = 0; i < game.width; ++i) {
test.ok(state.blocks[i + shift].garbage, "Garbage not preserved");
test.ok(!state.blocks[i + game.width + shift].garbage, "Garbage not released");
}
test.done();
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function () {
let root = arguments.length <= 0 || arguments[0] === undefined ? '.' : arguments[0];
let options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
root = (0, _path.normalize)((0, _path.resolve)(root));
options.routes = clone(options.routes || []);
options = Object.assign({
routes: null,
index: '/index'
}, options);
for (let route of options.routes) {
route.url = (0, _pathToRegexp2.default)(route.url);
}
return function* (next) {
for (let route of options.routes) {
let matched, params;
if (this.path === '/') {
break;
}
if (!(matched = route.url.exec(this.path))) {
continue;
}
params = {};
matched = matched.slice(1);
route.url.keys.forEach((item, index) => {
params[item.name] = matched[index];
});
this.params = params;
this.path = route.controller;
break;
}
if (this.params) {
if (!this.state.renderData) {
this.state.renderData = {};
}
Object.assign(this.state.renderData, this.params);
}
let path = (0, _path.join)(root, (this.path === '/' ? options.index : this.path) + '.js');
try {
if ((yield _coFs2.default.stat(path)).isFile()) {
yield _interopRequireDefault(require(path)).default().call(this);
}
} catch (err) {
if (~['ENOENT', 'ENAMETOOLONG', 'ENOTDIR'].indexOf(err.code)) {
return;
}
}
yield next;
};
};
var _coFs = require('co-fs');
var _coFs2 = _interopRequireDefault2(_coFs);
var _pathToRegexp = require('path-to-regexp');
var _pathToRegexp2 = _interopRequireDefault2(_pathToRegexp);
var _path = require('path');
function _interopRequireDefault2(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function clone(obj) {
return JSON.parse(JSON.stringify(obj));
} |
'use strict';
/**
* Home controller simply lists all the videos
*/
angular.module("nodeVideoCMS.videos").controller("VideosCtrl", function($scope, $routeParams, api){
var videosPerPage = 12,
criteria;
$scope.maxSize = 5;
$scope.currentPage = 1;
$scope.paginationVisible = false;
if($routeParams && $routeParams.categoryID) {
criteria = {
category : parseInt($routeParams.categoryID)
}
}
api.videos.list(0, videosPerPage, criteria).success(function (res) {
$scope.totalItems = res.total_record_count;
$scope.videos = res.records;
$scope.paginationVisible = $scope.totalItems > videosPerPage;
});
api.categories.list().success(function (categories) {
$scope.categories = categories;
});
$scope.pageChanged = function() {
var start = videosPerPage * ($scope.currentPage - 1),
end = videosPerPage * $scope.currentPage;
api.videos.list(start, end, criteria).success(function (res) {
$scope.videos = res.records;
});
};
});
|
/* global window */
import React from 'react'
import NProgress from 'nprogress'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import { Helmet } from 'react-helmet'
import { withRouter } from 'dva/router'
let lastHref
const App = ({ children, dispatch, app, loading, location }) => {
const href = window.location.href
if (lastHref !== href) {
NProgress.start()
if (!loading.global) {
NProgress.done()
lastHref = href
}
}
return (
<div>
<Helmet>
<title>DVA DEMO</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</Helmet>
<div>
{ children }
</div>
</div>
)
}
App.propTypes = {
children: PropTypes.element.isRequired,
location: PropTypes.object,
dispatch: PropTypes.func,
app: PropTypes.object,
loading: PropTypes.object,
}
export default withRouter(connect(({ app, loading }) => ({ app, loading }))(App)) |
'use strict';
describe("Calling the fromTo-function of a moment", function(){
moment.period
.add({name: 'fromTo15Minutes', count: 15, unit: 'minute'})
.add({name: 'fromTo1Month', count: 1, unit: 'month'});
it("should create an object with properties for from and to", function(){
expect(moment().fromTo().from).toBeDefined();
expect(moment().fromTo().to).toBeDefined();
});
it("should return a fromTo where from and to are same as moment if no period is defined", function(){
var testMoment = moment();
expect(testMoment.isSame(testMoment.fromTo().from)).toBe(true);
expect(testMoment.isSame(testMoment.fromTo().to)).toBe(true);
});
it("should return the start and the end of the period of a moment", function() {
var testMoment = moment.utc({ years :2010, months :5, date :5, hours :5, minutes :8, seconds :3, milliseconds : 9 }).period('fromTo15Minutes');
expect(testMoment.clone().period(true).isSame(testMoment.fromTo().from)).toBe(true);
expect(testMoment.clone().period(false).isSame(testMoment.fromTo().to)).toBe(true);
});
it("should return the start and the end of a named period for a moment", function() {
var testMoment = moment.utc({ years :2010, months :5, date :5, hours :5, minutes :8, seconds :3, milliseconds : 9 }).period('fromTo15Minutes');
expect(testMoment.clone().period('fromTo1Month').period(true).isSame(testMoment.fromTo('fromTo1Month').from)).toBe(true);
expect(testMoment.clone().period('fromTo1Month').period(false).isSame(testMoment.fromTo('fromTo1Month').to)).toBe(true);
});
}); |
(function() {
'use strict';
angular.module('journal.component.editor')
.service('EditorService', ['$http', 'AuthService', 'CONFIG', EditorService]);
function EditorService($http, AuthService, CONFIG) {
this.apiUrl = CONFIG.API_URL;
this.checkSlug = function(title, id) {
var url = this.apiUrl + '/posts/check_slug?slug=' + (title || '');
// check if id is set
if (id) {
url += '&post_id=' + id;
}
// do an API request
return $http.get(url);
};
this.getPost = function(id) {
return $http.get(this.apiUrl + '/posts/get_post?post_id=' + id);
};
this.getTags = function() {
return $http.get(this.apiUrl + '/tags/all');
};
this.save = function(post) {
var token = AuthService.getToken(),
url = this.apiUrl + '/posts/save?token=' + token,
authorId = post.author_id || '',
title = post.title || '',
markdown = post.markdown || '',
featuredImage = post.featured_image || '',
slug = post.slug || '',
status = post.status || 2,
tags = post.tags || [],
publishedAt = post.published_at.getTime() / 1000 || Math.floor(Date.now() / 1000);
// check if post_id is set
if (post.id) {
url += '&post_id=' + post.id;
}
// send the request to the API
return $http.post(url, {
author_id : authorId,
title : title,
markdown : markdown,
featured_image : featuredImage,
slug : slug,
status : status,
tags : tags,
published_at : publishedAt});
};
}
})();
|
/*global module, process*/
/*eslint no-use-before-define:0 */
var webpack = require('webpack');
var webpackDevServer = require('webpack-dev-server');
var path = require('path');
// Support for extra commandline arguments
var argv = require('optimist')
//--env=XXX: sets a global ENV variable (i.e. window.ENV='XXX')
.alias('e', 'env').default('e', 'dev')
.argv;
var config = {
context: __dirname,
entry: {'bundle': './main'},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js',
publicPath: isDevServer() ? '/' : ''
},
devServer: {
publicPath: '/'
},
reload: isDevServer() ? 'localhost' : null,
module: {
loaders: [
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.less$/, loader: 'style-loader!css-loader!less-loader' },
{ test: /\.(png|jpg|gif)$/, loader: 'url-loader?limit=5000&name=[path][name].[ext]&context=./src' },
{ test: /\.eot$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' },
{ test: /\.ttf$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' },
{ test: /\.svg$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' },
{ test: /\.woff$/, loader: 'file-loader?name=[path][name].[ext]&context=./src' },
{ test: /index\.html$/, loader: 'file-loader?name=[path][name].[ext]&context=.' }
]
},
resolve: {
alias: {
'famous-flex': 'famous-flex/src'
}
},
plugins: [
new webpack.DefinePlugin({
VERSION: JSON.stringify(require('../package.json').version),
ENV: JSON.stringify(argv.env)
})
]
};
function isDevServer() {
return process.argv.join('').indexOf('webpack-dev-server') > -1;
}
module.exports = config;
|
var hello = function() {
alert("My name is" name)
}; |
var _ = require("lodash-node");
module.exports = function(client) {
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
// 1. clear any previous migrations, db constraints will cascade on theme links and maplayers
//
var query = "DELETE FROM oskari_layergroup; DELETE FROM oskari_resource WHERE resource_mapping LIKE '%_migrated+collection';";
runSQL(client, query, copyLayerGroups, 'could not clear previous migration!');
});
// 2. Create layer groups (organisations)
function copyLayerGroups(client) {
var query = "INSERT INTO oskari_layergroup (id, locale) SELECT id, locale FROM portti_layerclass WHERE parent IS NULL";
runSQL(client, query, fixGroupIdSequence, 'could not copy layer groups');
}
// 3. update serial column sequence value since we inserted ids manually!!
function fixGroupIdSequence(client) {
var fixSequenceSQL = "SELECT setval(pg_get_serial_sequence('oskari_layergroup', 'id'), (SELECT MAX(id) FROM oskari_layergroup));";
runSQL(client, fixSequenceSQL, copyNormalLayers, 'could not fix sequence for oskari_layergroup.id');
}
// 4. Copy independent/normal layers (that are not sublayers)
function copyNormalLayers(client) {
var selectSQL = "SELECT id, -1 AS parentId, layer_type, false AS base_map, layerclassid AS groupId, wmsname, wmsurl, " +
"locale, opacity, '' AS style, minscale, maxscale, legend_image, dataurl, " +
"tile_matrix_set_id, tile_matrix_set_data, gfi_type, xslt, " +
"created, updated " +
"FROM portti_maplayer WHERE layerclassid IN (SELECT id FROM oskari_layergroup);";
var insertSQL = "INSERT INTO oskari_maplayer(" +
"id, parentid, type, base_map, groupid, name, url," +
"locale, opacity, style, minscale, maxscale, legend_image, metadataid," +
"tile_matrix_set_id, tile_matrix_set_data, gfi_type, gfi_xslt, " +
"created, updated) ";
runSQL(client, insertSQL + selectSQL, copySubLayers, 'could not copy normal layers');
}
// 5. copy layers that are sublayers
function copySubLayers(client) {
// NOTE! sublayers will have groupId=1 and parentId as layerclassid
var selectSQL = "SELECT id, layerclassid AS parentId, layer_type, false AS base_map, 1 AS groupId, wmsname, wmsurl, " +
"locale, opacity, style, minscale, maxscale, legend_image, dataurl, " +
"tile_matrix_set_id, tile_matrix_set_data, gfi_type, xslt, " +
"created, updated " +
"FROM portti_maplayer WHERE layerclassid NOT IN (SELECT id FROM oskari_layergroup);";
var insertSQL = "INSERT INTO oskari_maplayer(" +
"id, parentid, type, base_map, groupid, name, url," +
"locale, opacity, style, minscale, maxscale, legend_image, metadataid," +
"tile_matrix_set_id, tile_matrix_set_data, gfi_type, gfi_xslt, " +
"created, updated) ";
runSQL(client, insertSQL + selectSQL, fixIdSequence, 'could not copy sublayers');
}
// 6. update serial column sequence value since we inserted ids manually!!
function fixIdSequence(client) {
var fixSequenceSQL = "SELECT setval(pg_get_serial_sequence('oskari_maplayer', 'id'), (SELECT MAX(id) FROM oskari_maplayer));";
runSQL(client, fixSequenceSQL, createNewBaseLayers, 'could not fix sequence for oskari_maplayer.id');
}
// 7. establish new rows to oskari_maplayers from portti_layerclass base/group layers
function createNewBaseLayers(client) {
var selectSQL = "SELECT -1 AS parentId, id AS externalId, 'collection' AS type, NOT group_map AS base_map, parent AS groupId, " +
"id || '_migrated' AS name, 'collection' AS url, " +
"locale, 100 AS opacity, '' AS style, -1 AS minscale, -1 AS maxscale, legend_image, dataurl AS metadataId, " +
"'' AS tile_matrix_set_id, '' AS tile_matrix_set_data, '' AS gfi_type, '' AS gfi_xslt " +
"FROM portti_layerclass WHERE parent IS NOT NULL";
var insertSQL = "INSERT INTO oskari_maplayer(" +
"parentid, externalId, type, base_map, groupid, name, url," +
"locale, opacity, style, minscale, maxscale, legend_image, metadataid," +
"tile_matrix_set_id, tile_matrix_set_data, gfi_type, gfi_xslt) ";
runSQL(client, insertSQL + selectSQL, linkSublayers, 'could not establish new collection layers');
}
// 8. link sublayers to new baselayers
function linkSublayers(client) {
var linkSQL = "UPDATE oskari_maplayer SET parentId = m.id FROM oskari_maplayer m " +
"WHERE oskari_maplayer.parentId != -1 AND oskari_maplayer.parentId = m.externalId::integer"
//runSQL(client, linkSQL, updateExternalIds, 'could not link sublayers');
runSQL(client, linkSQL, copyBaseLayerPermissions, 'could not link sublayers');
}
// 8.5 setup base/group layer permissions
function copyBaseLayerPermissions(client) {
var selectGroupsSQL = "SELECT id, name, url, externalId FROM oskari_maplayer WHERE type='collection'";
client.query(selectGroupsSQL, function(err, groupLayers) {
if(err) {
return console.error("Couldn't find collection layers", err);
}
console.log('got collection layers', groupLayers.rows.length);
var count = 0;
var resources = [];
function permissionsCopied(err) {
/*
if(err) {
// if previous layer had no permissions -> an error will occur,
// so skipping any errors since this _should_ work :)
console.log("Permissions with resource ids:", resources);
return console.error("Couldn't insert permissions for resource", err);
}*/
count++;
// after all sqls executed -> go to next step
if(count == groupLayers.rows.length) {
console.log("Inserted new resources/permissions with resource ids:", resources);
updateExternalIds(client);
}
}
_.forEach(groupLayers.rows, function(layer) {
//console.log('Handling layer:', layer);
// insert as new resources
var insertResource = "INSERT INTO oskari_resource (resource_type, resource_mapping) " +
"VALUES ('maplayer', '" + layer.url + "+" + layer.name + "') " +
"RETURNING ID;";
client.query(insertResource, function(err, insertResult) {
if(err) {
count++;
return console.error("Couldn't insert grouplayer as resource", layer, err);
}
var resourceId = insertResult.rows[0].id;
resources.push(resourceId);
// copy permissions from matching layerclass
var copyPermissionsSQL = "INSERT INTO oskari_permission (oskari_resource_id, external_type, permission, external_id) " +
"SELECT " + resourceId + ", p.external_type, p.permission, p.external_id FROM oskari_resource r, oskari_permission p " +
"WHERE r.id = p.oskari_resource_id AND r.resource_type='layerclass' AND r.resource_mapping = 'BASE+" + layer.externalid + "'";
runSQL(client, copyPermissionsSQL, permissionsCopied, 'Could not copy permissions for layer: ' + JSON.stringify(layer));
});
});
});
}
// 9. update externalId with base_ prefix
function updateExternalIds(client) {
var prefixSQL = "UPDATE oskari_maplayer SET externalId = 'base_' || externalId " +
"WHERE externalId IS NOT NULL";
runSQL(client, prefixSQL, linkInspireThemesForNormalLayers, 'could not prefix external ids');
}
// 10. link themes from old db table for layers that exist there (non baselayers)
// TODO: check collection layers inspire themes!
function linkInspireThemesForNormalLayers(client) {
var query = "INSERT INTO oskari_maplayer_themes (maplayerid, themeid) SELECT id, inspire_theme_id FROM portti_maplayer";
runSQL(client, query, linkInspireThemesForCollectionLayers, 'could not link inspire themes');
}
// 11. Add inspire theme links to base/grouplayers
function linkInspireThemesForCollectionLayers(client) {
var selectSQL = "SELECT DISTINCT m1.id AS baseId, t.themeid FROM oskari_maplayer m1, oskari_maplayer m2, " +
"oskari_maplayer_themes t WHERE m1.id = m2.parentId AND t.maplayerid = m2.id;"
var linkSql = "INSERT INTO oskari_maplayer_themes (maplayerid, themeid) ";
runSQL(client, linkSql + selectSQL, updateStylesForWMS, 'could not link inspire themes');
}
// 12. update default styles for wms layers
// TODO: check if wmts needs this!!
function updateStylesForWMS(client) {
var updateSQL = "UPDATE oskari_maplayer SET style = substr(m.style, 1, 100) FROM portti_maplayer m " +
"WHERE oskari_maplayer.id = m.id AND m.layer_type = 'wmslayer'"
runSQL(client, updateSQL, allDone, 'could not update default styles for layers');
}
// 13. all done
function allDone(client) {
console.log("Upgrade complete, you can now remove portti_maplayer and portti_layerclass tables from database");
client.end();
}
function runSQL(client, sql, callback, errorMsg) {
client.query(sql, function(err) {
if(err) {
return console.error(errorMsg, err);
}
callback(client);
});
}
}
|
import React from 'react';
import _ from 'lodash';
import { FlatButton, RaisedButton } from 'material-ui';
const DialogStandardButtons = ({
handleCancel,
handleConfirm,
submitLabel = 'Confirm',
cancelLabel = 'Cancel',
inverted,
disabled,
submitDisabled,
cancelDisabled,
...other
}) => {
const styles = {
rootInverted: {
display: 'flex',
flexDirection: 'row-reverse',
justifyContent: 'flex-end',
marginLeft: -10
},
button: {
marginLeft: 10,
borderRadius: '4px'
}
};
return (
<div style={inverted && styles.rootInverted}>
<FlatButton
key="cancel"
label={cancelLabel}
labelStyle={{ textTransform: 'none' }}
buttonStyle={{ borderRadius: '4px' }}
style={styles.button}
disabled={disabled || cancelDisabled}
onTouchTap={_.debounce(handleCancel, 500, { leading: true })}
data-e2e={other['data-e2e-cancel']}
/>
<RaisedButton
key="confirm"
label={submitLabel}
labelStyle={{ textTransform: 'none', color: '#436E1D' }}
buttonStyle={{ borderRadius: '4px' }}
backgroundColor="#B8E986"
style={styles.button}
disabled={disabled || submitDisabled}
onTouchTap={_.debounce(handleConfirm, 500, { leading: true })}
data-e2e={other['data-e2e-submit']}
/>
</div>
);
};
export default DialogStandardButtons;
|
var mongoose = require('mongoose');
var workLogSchema = mongoose.Schema({
startedAt: {
type: Date,
required: true,
default: Date.now
},
timeSpent: {
type: Number,
required: true,
validate: [ function (value) {
return value > 0;
}, 'Time spent must be greater than zero.' ]
},
task: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Task'
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
workLogSchema.static({
findById: function (id, callback) {
this.findOne({
_id: id
})
.select('-task -user -__v')
.exec(callback);
},
findByIdAndTaskId: function (options, callback) {
this.findOne({
_id: options.id,
task: options.taskId
})
.select('-task -user -__v')
.exec(callback);
},
findByTaskId: function (taskId, callback) {
this.find({
task: taskId
})
.select('-task -user -__v')
.exec(callback);
},
findByUserId: function (userId, callback) {
this.find({
user: userId
})
.select('-task -user -__v')
.exec(callback);
}
});
workLogSchema.set('toJSON', {
transform: function (doc, ret, options) {
ret.id = ret._id;
delete ret._id;
delete ret.__v;
}
});
module.exports = mongoose.model('WorkLog', workLogSchema);
|
import React, {Component} from 'react'
import {findDOMNode} from 'react-dom'
import styles from '../sass/Form'
import {Button, Form, Input, DatePicker, Select} from 'antd'
class FormComponent extends Component {
constructor() {
super()
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit(e) {
e.preventDefault()
const {form, actions} = this.props
form.validateFields((err, values) => {
if (!err) {
actions.getItems(values)
}
})
}
render() {
const {form, schools, cats} = this.props
return (
<Form onSubmit={this.handleSubmit}
className={styles.form}
inline>
<Form.Item
label="学校">
{form.getFieldDecorator('school',{initialValue: schools[0]?schools[0].id:''})(
<Select className={styles.select}>
{schools.map(school =>
<Select.Option key={school.id} value={school.id}>{school.schoolName}</Select.Option>
)}
</Select>
)}
</Form.Item>
<Form.Item
label="分类">
{form.getFieldDecorator('cat',{initialValue: ''})(
<Select className={styles.select}>
<Select.Option value="">全部</Select.Option>
{cats.map(cat =>
<Select.Option key={cat.id} value={cat.id}>{cat.catName}</Select.Option>
)}
</Select>
)}
</Form.Item>
<Form.Item>
<Button htmlType="submit" type="primary">查询</Button>
</Form.Item>
</Form>
)
}
}
export default Form.create()(FormComponent)
|
/**
* Core dependencies.
*/
var path = require('path');
var dirname = path.dirname;
/**
* Create path.
*
* @param {String} pattern
* @returns {Object}
* @api private
*/
function createPattern(pattern) {
return {
pattern: pattern,
included: true,
served: true,
watched: false
};
}
/**
* Insert hydro into the loaded files.
*
* @param {Array} files
* @api public
*/
function init(config) {
var hydroConfig = config.hydro || {};
var hydroJs = hydroConfig.path || dirname(dirname(require.resolve('hydro'))) + '/dist/hydro.js';
var before = hydroConfig.before || [];
config.files.unshift(createPattern(__dirname + '/adapter.js'));
config.files.unshift(createPattern(hydroJs));
before.reverse().forEach(function(file) {
config.files.unshift(createPattern(path.resolve(file)));
});
}
/**
* Inject.
*/
init.$inject = [ 'config' ];
/**
* Primary export.
*/
module.exports = {
'framework:hydro': [ 'factory', init ]
};
|
/*
* This class represent a game paddle
*/
'use strict';
import Vector from 'Vector.js';
export default class {
constructor(x, y, width, height, color = '#FFFFFF', speed = 3) {
this.width = width;
this.height = height;
this.color = color;
this.position = new Vector(x, y);
this.velocity = new Vector(speed, 0);
this.computer = false;
// Control keys.
this.rightPressed = false;
this.leftPressed = false;
}
// Setting the paddle to a specific position.
setPosition(x, y) {
this.position.setCoordinates(x, y);
}
move(doMove) {
if (this.rightPressed || this.leftPressed) {
if (this.rightPressed) {
this.velocity.x = Math.abs(this.velocity.x);
} else if (this.leftPressed) {
this.velocity.x = -Math.abs(this.velocity.x);
}
if (doMove) {
this.position.add(this.velocity);
}
}
}
// Returns relevant drawing information related to
// the paddle.
getDrawInfo() {
return {
drawType: 'rect',
color: this.color,
params: [
this.position.x,
this.position.y,
this.width,
this.height
]
};
}
}
|
//
// resourcetiming-decompression.js
//
// Decompresses ResourceTiming data compressed via resourcetiming-compression.js.
//
// See http://nicj.net/compressing-resourcetiming/
//
// https://github.com/nicjansma/resourcetiming-compression.js
//
(function(window) {
"use strict";
// save old ResourceTimingDecompression object for noConflict()
var root;
var previousObj;
if (typeof window !== "undefined") {
root = window;
previousObj = root.ResourceTimingDecompression;
}
// model
var ResourceTimingDecompression = {};
//
// Functions
//
/**
* Returns the index of the first value in the array such that it is
* greater or equal to x.
* The search is performed using binary search and the array is assumed
* to be sorted in ascending order.
*
* @param {array} arr haystack
* @param {any} x needle
* @param {function} by transform function (optional)
*
* @returns {number} the desired index or arr.length if x is more than all values.
*/
ResourceTimingDecompression.searchSortedFirst = function(arr, x, by) {
if (!arr || arr.length === 0) {
return -1;
}
function ident(a) {
return a;
}
by = by || ident;
x = by(x);
var min = -1;
var max = arr.length;
var m = 0;
while (min < (max - 1)) {
m = (min + max) >>> 1;
if (by(arr[m]) < x) {
min = m;
} else {
max = m;
}
}
return max;
};
/**
* Returns the index of the last value in the array such that is it less
* than or equal to x.
* The search is performed using binary search and the array is assumed
* to be sorted in ascending order.
*
* @param {array} arr haystack
* @param {any} x needle
* @param {function} by transform function (optional)
*
* @returns {number} the desired index or -1 if x is less than all values.
*/
ResourceTimingDecompression.searchSortedLast = function(arr, x, by) {
if (!arr || arr.length === 0) {
return -1;
}
function ident(a) {
return a;
}
by = by || ident;
x = by(x);
var min = -1;
var max = arr.length;
var m = 0;
while (min < (max - 1)) {
m = (min + max) >>> 1;
if (x < by(arr[m])) {
max = m;
} else {
min = m;
}
}
return min;
};
/**
* Changes the value of ResourceTimingDecompression back to its original value, returning
* a reference to the ResourceTimingDecompression object.
*
* @returns {object} Original ResourceTimingDecompression object
*/
ResourceTimingDecompression.noConflict = function() {
root.ResourceTimingDecompression = previousObj;
return ResourceTimingDecompression;
};
/**
* Initiator type map
*/
ResourceTimingDecompression.INITIATOR_TYPES = {
"other": 0,
"img": 1,
"link": 2,
"script": 3,
"css": 4,
"xmlhttprequest": 5,
"html": 6,
// IMAGE element inside a SVG
"image": 7,
"beacon": 8,
"fetch": 9
};
/**
* Dimension name map
*/
ResourceTimingDecompression.DIMENSION_NAMES = {
"height": 0,
"width": 1,
"y": 2,
"x": 3,
"naturalHeight": 4,
"naturalWidth": 5
};
/**
* Script mask map
*/
ResourceTimingDecompression.SCRIPT_ATTRIBUTES = {
"scriptAsync": 1,
"scriptDefer": 2,
"scriptBody": 4
};
/**
* Returns a map with key/value pairs reversed.
*
* @param {object} origMap Map we want to reverse.
*
* @returns {object} New map with reversed mappings.
*/
ResourceTimingDecompression.getRevMap = function(origMap) {
var revMap = {};
for (var key in origMap) {
if (origMap.hasOwnProperty(key)) {
revMap[origMap[key]] = key;
}
}
return revMap;
};
/**
* Reverse initiator type map
*/
ResourceTimingDecompression.REV_INITIATOR_TYPES = ResourceTimingDecompression.
getRevMap(ResourceTimingDecompression.INITIATOR_TYPES);
/**
* Reverse dimension name map
*/
ResourceTimingDecompression.REV_DIMENSION_NAMES = ResourceTimingDecompression.
getRevMap(ResourceTimingDecompression.DIMENSION_NAMES);
/**
* Reverse script attribute map
*/
ResourceTimingDecompression.REV_SCRIPT_ATTRIBUTES = ResourceTimingDecompression.
getRevMap(ResourceTimingDecompression.SCRIPT_ATTRIBUTES);
// Any ResourceTiming data time that starts with this character is not a time,
// but something else (like dimension data)
var SPECIAL_DATA_PREFIX = "*";
// Dimension data special type
var SPECIAL_DATA_DIMENSION_TYPE = "0";
var SPECIAL_DATA_DIMENSION_PREFIX = SPECIAL_DATA_PREFIX + SPECIAL_DATA_DIMENSION_TYPE;
// Dimension data special type
var SPECIAL_DATA_SIZE_TYPE = "1";
// Dimension data special type
var SPECIAL_DATA_SCRIPT_TYPE = "2";
// Regular Expression to parse a URL
var HOSTNAME_REGEX = /^(https?:\/\/)([^\/]+)(.*)/;
/**
* Decompresses a compressed ResourceTiming trie
*
* @param {object} rt ResourceTiming trie
* @param {string} prefix URL prefix for the current node
*
* @returns {ResourceTiming[]} ResourceTiming array
*/
ResourceTimingDecompression.decompressResources = function(rt, prefix) {
var resources = [];
// Dimension data for resources.
var dimensionData;
prefix = prefix || "";
for (var key in rt) {
// skip over inherited properties
if (!rt.hasOwnProperty(key)) {
continue;
}
var node = rt[key];
var nodeKey = prefix + key;
// strip trailing pipe, which is used to designate a node that is a prefix for
// other nodes but has resTiming data
if (nodeKey.indexOf("|", nodeKey.length - 1) !== -1) {
nodeKey = nodeKey.substring(0, nodeKey.length - 1);
}
if (typeof node === "string") {
// add all occurences
var timings = node.split("|");
if (timings.length === 0) {
continue;
}
// Make sure we reset the dimensions before each new resource.
dimensionData = undefined;
if (this.isDimensionData(timings[0])) {
dimensionData = this.decompressDimension(timings[0]);
// Remove the dimension data from our timings array
timings = timings.splice(1);
}
// end-node
for (var i = 0; i < timings.length; i++) {
var resourceData = timings[i];
if (resourceData.length > 0 && resourceData[0] === SPECIAL_DATA_PREFIX) {
// dimensions or sizes for this resource
continue;
}
// Decode resource and add dimension data to it.
resources.push(
this.addDimension(
this.decodeCompressedResource(resourceData, nodeKey),
dimensionData
)
);
}
} else {
// continue down
var nodeResources = this.decompressResources(node, nodeKey);
resources = resources.concat(nodeResources);
}
}
return resources;
};
/*
* Checks that the input contains dimension information.
*
* @param {string} resourceData The string we want to check.
*
* @returns boolean True if resourceData starts with SPECIAL_DATA_DIMENSION_PREFIX, false otherwise.
*/
ResourceTimingDecompression.isDimensionData = function(resourceData) {
return resourceData &&
resourceData.substring(0, SPECIAL_DATA_DIMENSION_PREFIX.length) === SPECIAL_DATA_DIMENSION_PREFIX;
};
/**
* Extract height, width, y and x from a string.
*
* @param {string} resourceData A string containing dimension data.
*
* @returns {object} Dimension data with keys defined by DIMENSION_NAMES.
*/
ResourceTimingDecompression.decompressDimension = function(resourceData) {
var dimensions, i;
var dimensionData = {};
// If the string does not contain dimension information, do nothing.
if (!this.isDimensionData(resourceData)) {
return dimensionData;
}
// Remove special prefix
resourceData = resourceData.substring(SPECIAL_DATA_DIMENSION_PREFIX.length);
dimensions = resourceData.split(",");
// The data should contain at least height/width.
if (dimensions.length < 2) {
return dimensionData;
}
// Base 36 decode and assign to correct keys of dimensionData.
for (i = 0; i < dimensions.length; i++) {
if (dimensions[i] === "") {
dimensionData[this.REV_DIMENSION_NAMES[i]] = 0;
} else {
dimensionData[this.REV_DIMENSION_NAMES[i]] = parseInt(dimensions[i], 36);
}
}
return dimensionData;
};
/**
* Adds dimension data to the given resource.
*
* @param {object} resource The resource we want to edit.
* @param {object} dimensionData The dimension data we want to add.
*
* @returns {object} The resource with added dimensions.
*/
ResourceTimingDecompression.addDimension = function(resource, dimensionData) {
// If the resource or data are not defined, do nothing.
if (!resource || !dimensionData) {
return resource;
}
// Add all the dimensions to our resource.
for (var key in this.DIMENSION_NAMES) {
if (this.DIMENSION_NAMES.hasOwnProperty(key) &&
dimensionData.hasOwnProperty(key)) {
resource[key] = dimensionData[key];
}
}
return resource;
};
/**
* Compute a list of cells based on the start/end times of the
* given array of resources.
* The returned list of cells is sorted in chronological order.
*
* @param {array} rts array of resource timings.
*
* @returns {array} Array of cells.
*/
ResourceTimingDecompression.getSortedCells = function(rts) {
// We have exactly 2 events per resource (start and end).
// var cells = new Array(rts.length * 2);
var cells = [];
for (var i = 0; i < rts.length; i++) {
// Ignore resources with duration <= 0
if (rts[i].responseEnd <= rts[i].startTime) {
continue;
}
// Increment on resource start
cells.push({
ts: rts[i].startTime,
val: 1.0
});
// Decrement on resource end
cells.push({
ts: rts[i].responseEnd,
val: -1.0
});
}
// Sort in chronological order
cells.sort(function(x, y) {
return x.ts - y.ts;
});
return cells;
};
/**
* Add contributions to the array of cells.
*
* @param {array} cells array of cells that need contributions.
*
* @returns {array} Array of cells with their contributions.
*/
ResourceTimingDecompression.addCellContributions = function(cells) {
var tot = 0.0;
var incr = 0.0;
var deleteIdx = [];
var currentSt = cells[0].ts;
var cellLen = cells.length;
var c = {};
for (var i = 0; i < cellLen; i++) {
c = cells[i];
// The next timestamp is the same.
// We don't want to have cells of duration 0, so
// we aggregate them.
if ((i < (cellLen - 1)) && (cells[i + 1].ts === c.ts)) {
cells[i + 1].val += c.val;
deleteIdx.push(i);
continue;
}
incr = c.val;
if (tot > 0) {
// divide time delta by number of active resources.
c.val = (c.ts - currentSt) / tot;
}
currentSt = c.ts;
tot += incr;
}
// Delete timestamps that don't delimit cells.
for (i = deleteIdx.length - 1; i >= 0; i--) {
cells.splice(deleteIdx[i], 1);
}
return cells;
};
/**
* Sum the contributions of a single resource based on an array of cells.
*
* @param {array} cells Array of cells with their contributions.
* @param {ResourceTiming} rt a single resource timing object.
*
* @returns {number} The total contribution for that resource.
*/
ResourceTimingDecompression.sumContributions = function(cells, rt) {
if (!rt || typeof rt.startTime === "undefined" ||
typeof rt.responseEnd === "undefined") {
return 0.0;
}
var startTime = rt.startTime + 1;
var responseEnd = rt.responseEnd;
function getTs(x) {
return x.ts;
}
// Find indices of cells that were affected by our resource.
var low = this.searchSortedFirst(cells, {ts: startTime}, getTs);
var up = this.searchSortedLast(cells, {ts: responseEnd}, getTs);
var tot = 0.0;
// Sum contributions across all those cells
for (var i = low; i <= up; i++) {
tot += cells[i].val;
}
return tot;
};
/**
* Adds contribution scores to all resources in the array.
*
* @param {array} rts array of resource timings.
*
* @returns {array} Array of resource timings with their contributions.
*/
ResourceTimingDecompression.addContribution = function(rts) {
if (!rts || rts.length === 0) {
return rts;
}
// Get cells in chronological order.
var cells = this.getSortedCells(rts);
// We need at least two cells and they need to begin
// with a start event. Furthermore, the last timestamp
// should be > 0.
if (cells.length < 2 ||
cells[0].val < 1.0 ||
cells[cells.length - 1].ts <= 0
) {
return rts;
}
// Compute each cell's contribution.
this.addCellContributions(cells);
// Total load time for this batch of resources.
var loadTime = cells[cells.length - 1].ts;
for (var i = 0; i < rts.length; i++) {
// Compute the contribution of each resource.
// Normalize by total load time.
rts[i].contribution = this.sumContributions(cells, rts[i]) / loadTime;
}
return rts;
};
/**
* Determines the initiatorType from a lookup
*
* @param {number} index Initiator type index
*
* @returns {string} initiatorType, or "other" if not known
*/
ResourceTimingDecompression.getInitiatorTypeFromIndex = function(index) {
if (this.REV_INITIATOR_TYPES.hasOwnProperty(index)) {
return this.REV_INITIATOR_TYPES[index];
} else {
return "other";
}
};
/**
* Decodes a compressed ResourceTiming data string
*
* @param {string} data Compressed timing data
* @param {string} url URL
*
* @returns {ResourceTiming} ResourceTiming pseudo-object (containing all of the properties of a
* ResourceTiming object)
*/
ResourceTimingDecompression.decodeCompressedResource = function(data, url) {
if (!data || !url) {
return {};
}
url = ResourceTimingDecompression.reverseHostname(url);
var initiatorType = parseInt(data[0], 10);
data = data.length > 1 ? data.split(SPECIAL_DATA_PREFIX) : [];
var timings = data.length > 0 && data[0].length > 1 ? data[0].substring(1).split(",") : [];
var sizes = data.length > 1 ? data[1] : "";
var specialData = data.length > 1 ? data[1] : "";
// convert all timings from base36
for (var i = 0; i < timings.length; i++) {
if (timings[i] === "") {
// startTime being 0
timings[i] = 0;
} else {
// de-base36
timings[i] = parseInt(timings[i], 36);
}
}
// special case timestamps
var startTime = timings.length >= 1 ? timings[0] : 0;
// fetchStart is either the redirectEnd time, or startTime
var fetchStart = timings.length < 10 ?
startTime :
this.decodeCompressedResourceTimeStamp(timings, 9, startTime);
// all others are offset from startTime
var res = {
name: url,
initiatorType: this.getInitiatorTypeFromIndex(initiatorType),
startTime: startTime,
redirectStart: this.decodeCompressedResourceTimeStamp(timings, 9, startTime) > 0 ? startTime : 0,
redirectEnd: this.decodeCompressedResourceTimeStamp(timings, 9, startTime),
fetchStart: fetchStart,
domainLookupStart: this.decodeCompressedResourceTimeStamp(timings, 8, startTime),
domainLookupEnd: this.decodeCompressedResourceTimeStamp(timings, 7, startTime),
connectStart: this.decodeCompressedResourceTimeStamp(timings, 6, startTime),
secureConnectionStart: this.decodeCompressedResourceTimeStamp(timings, 5, startTime),
connectEnd: this.decodeCompressedResourceTimeStamp(timings, 4, startTime),
requestStart: this.decodeCompressedResourceTimeStamp(timings, 3, startTime),
responseStart: this.decodeCompressedResourceTimeStamp(timings, 2, startTime),
responseEnd: this.decodeCompressedResourceTimeStamp(timings, 1, startTime)
};
res.duration = res.responseEnd > 0 ? (res.responseEnd - res.startTime) : 0;
// decompress resource size data
if (sizes.length > 0) {
this.decompressSpecialData(specialData, res);
}
return res;
};
/**
* Decodes a timestamp from a compressed RT array
*
* @param {number[]} timings ResourceTiming timings
* @param {number} idx Index into array
* @param {number} startTime NavigationTiming The Resource's startTime
*
* @returns {number} Timestamp, or 0 if unknown or missing
*/
ResourceTimingDecompression.decodeCompressedResourceTimeStamp = function(timings, idx, startTime) {
if (timings && timings.length >= (idx + 1)) {
if (timings[idx] !== 0) {
return timings[idx] + startTime;
}
}
return 0;
};
/**
* Decompresses script load type into the specified resource.
*
* @param {string} compressed String with a single integer.
* @param {ResourceTiming} resource ResourceTiming object.
* @returns {ResourceTiming} ResourceTiming object with decompressed script type.
*/
ResourceTimingDecompression.decompressScriptType = function(compressed, resource) {
var data = parseInt(compressed, 10);
if (!resource) {
resource = {};
}
for (var key in this.SCRIPT_ATTRIBUTES) {
if (this.SCRIPT_ATTRIBUTES.hasOwnProperty(key)) {
resource[key] = (data & this.SCRIPT_ATTRIBUTES[key]) === this.SCRIPT_ATTRIBUTES[key];
}
}
return resource;
};
/**
* Decompresses size information back into the specified resource
*
* @param {string} compressed Compressed string
* @param {ResourceTiming} resource ResourceTiming bject
* @returns {ResourceTiming} ResourceTiming object with decompressed sizes
*/
ResourceTimingDecompression.decompressSize = function(compressed, resource) {
var split, i;
if (typeof resource === "undefined") {
resource = {};
}
split = compressed.split(",");
for (i = 0; i < split.length; i++) {
if (split[i] === "_") {
// special non-delta value
split[i] = 0;
} else {
// fill in missing numbers
if (split[i] === "") {
split[i] = 0;
}
// convert back from Base36
split[i] = parseInt(split[i], 36);
if (i > 0) {
// delta against first number
split[i] += split[0];
}
}
}
// fill in missing
if (split.length === 1) {
// transferSize is a delta from encodedSize
split.push(split[0]);
}
if (split.length === 2) {
// decodedSize is a delta from encodedSize
split.push(split[0]);
}
// re-add attributes to the resource
resource.encodedBodySize = split[0];
resource.transferSize = split[1];
resource.decodedBodySize = split[2];
return resource;
};
/**
* Decompresses special data such as resource size or script type into the given resource.
*
* @param {string} compressed Compressed string
* @param {ResourceTiming} resource ResourceTiming object
* @returns {ResourceTiming} ResourceTiming object with decompressed special data
*/
ResourceTimingDecompression.decompressSpecialData = function(compressed, resource) {
var dataType;
if (!compressed || compressed.length === 0) {
return resource;
}
dataType = compressed[0];
compressed = compressed.substring(1);
if (dataType === SPECIAL_DATA_SIZE_TYPE) {
resource = this.decompressSize(compressed, resource);
} else if (dataType === SPECIAL_DATA_SCRIPT_TYPE) {
resource = this.decompressScriptType(compressed, resource);
}
return resource;
};
/**
* Reverse the hostname portion of a URL
*
* @param {string} url a fully-qualified URL
* @returns {string} the input URL with the hostname portion reversed, if it can be found
*/
ResourceTimingDecompression.reverseHostname = function(url) {
return url.replace(HOSTNAME_REGEX, function(m, p1, p2, p3) {
// p2 is everything after the first `://` and before the next `/`
// which includes `<username>:<password>@` and `:<port-number>`, if present
return p1 + ResourceTimingDecompression.reverseString(p2) + p3;
});
};
/**
* Reverse a string
*
* @param {string} i a string
* @returns {string} the reversed string
*/
ResourceTimingDecompression.reverseString = function(i) {
var l = i.length, o = "";
while (l--) {
o += i[l];
}
return o;
};
//
// Export to the appropriate location
//
if (typeof define === "function" && define.amd) {
//
// AMD / RequireJS
//
define([], function() {
return ResourceTimingDecompression;
});
} else if (typeof module !== "undefined" && module.exports) {
//
// Node.js
//
module.exports = ResourceTimingDecompression;
} else if (typeof root !== "undefined") {
//
// Browser Global
//
root.ResourceTimingDecompression = ResourceTimingDecompression;
}
}(typeof window !== "undefined" ? window : undefined));
|
var through = require('through2');
var escapeStr = require('js-string-escape');
var STYLE_HEADER = '!function(){var a="';
var STYLE_FOOTER = '",b=document.createElement("style");b.type="text/css",b.styleSheet?b.styleSheet.cssText=a:b.appendChild(document.createTextNode(a)),(document.head||document.getElementsByTagName("head")[0]).appendChild(b)}();';
function cssTojs() {
function transform(file, enc, callback) {
var css = file.contents.toString();
var content = STYLE_HEADER + escapeStr(css) + STYLE_FOOTER;
file.contents = new Buffer(content);
callback(null, file);
}
return through.obj(transform);
}
module.exports = cssTojs; |
var angular = require('angular');
// import the hello UI component
require('./hello/main');
// compose the app and the routes
module.exports = angular
.module('myApp', [
'ngRoute',
'hello'
])
.config([
'$routeProvider', function ($routeProvider) {
$routeProvider.when(
'/',
{ templateUrl: 'app/hello/base.html', controller: 'HelloCtrl' }
);
$routeProvider.otherwise({ redirectTo: '/' });
}
]);
// start the application
angular.bootstrap(document, ['myApp']);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.