UNPKG

web_page_state

Version:

Simple straightforward tool to manage webpage state on the client side and hook state to html tags on page without code

2 lines (1 loc) 14 kB
!function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,(function(r){return o(e[i][1][r]||r)}),p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}({1:[function(require,module,exports){window.wsGlobals=window.wsGlobals||{},window.wsGlobals.PageState=require("./index").PageState},{"./index":2}],2:[function(require,module,exports){const resolvePath=require("object-resolve-path");class PageState{static registerListener(onStateUpdate){if(!onStateUpdate)return;let index=PageState.listenersAvailableIndex;return PageState.listeners[index]=onStateUpdate,PageState.listenersAvailableIndex++,onStateUpdate(PageState.pageState),index}static unregisterListener(index){if(PageState.listeners.hasOwnProperty(index)){PageState.listeners[index]=null;try{delete PageState.listeners[index]}catch(e){}}}static updatePageStateWithParams(params){params||(params={});let props=Object.getOwnPropertyNames(params);if(params.isProcessing||(PageState.pageState.isProcessing=!1),props&&props.length>0)for(const key of props)if(void 0!==params[key])if("epochLicenseExpirationDateInSecs"===key){let latestEpoch=Math.max(PageState.pageState[key],params[key]);PageState.pageState[key]=latestEpoch;try{localStorage.setItem("epochLicenseExpirationDateInSecs",PageState.pageState[key]),window.chrome&&chrome.runtime&&chrome.runtime.sendMessage&&chrome.runtime.sendMessage("nncconplehmbkbhkgkodmnkfaflopkji",{message:"epochLicenseExpirationDateInSecs",data:latestEpoch},(function(){}))}catch(e){}}else PageState.pageState[key]=params[key];try{PageState.updateUiByState(PageState.pageState)}catch(e){}if(PageState.listeners)for(const i of Object.getOwnPropertyNames(PageState.listeners))PageState.listeners[i]&&PageState.listeners[i]instanceof Function?PageState.listeners[i](PageState.pageState):delete PageState.listeners[i]}static interpretLicenseState(epochToExpirationSecs){if(epochToExpirationSecs){if(epochToExpirationSecs<0)return PageState.licenseInterpretations.UNKNOWN;if(epochToExpirationSecs>=3e9)return PageState.licenseInterpretations.LIFETIME;{let timeInSecsTillExpiration=epochToExpirationSecs-Date.now()/1e3;return timeInSecsTillExpiration<=0?PageState.licenseInterpretations.SUBSCRIPTION_OVER:timeInSecsTillExpiration>=2592e3?PageState.licenseInterpretations.SUBSCRIPTION:PageState.licenseInterpretations.SUBSCRIPTION_SOON_OVER}}return PageState.licenseInterpretations.NONE}static updateUiByStatePropsDirectly(newState){let newStateHelpers=new PageState.pageStateHelpers(newState),elements=document.querySelectorAll("[data-ws-show-if]");for(const element of elements){let attr=element.getAttribute("data-ws-show-if");if(!attr)continue;let conditions=attr.split(" "),shouldShowEl=!1;for(const condition of conditions){let value,valueFunction;try{value=resolvePath(newState,condition)}catch(e){value=null}if(value){shouldShowEl=!0;break}try{valueFunction=resolvePath(newStateHelpers,condition)}catch(e){valueFunction=null}if(valueFunction&&valueFunction instanceof Function&&valueFunction()){shouldShowEl=!0;break}}element.style.display=shouldShowEl?"":"none"}elements=document.querySelectorAll("[data-ws-show-if-not]");for(const element of elements){let attr=element.getAttribute("data-ws-show-if-not");if(!attr)continue;let conditions=attr.split(" "),shouldShowEl=!1;for(const condition of conditions){let valueFunction,value;try{valueFunction=resolvePath(newStateHelpers,condition)}catch(e){valueFunction=null}try{value=resolvePath(newState,condition)}catch(e){value=null}if(valueFunction&&valueFunction instanceof Function){if(!valueFunction()){shouldShowEl=!0;break}}else if(!value){shouldShowEl=!0;break}}element.style.display=shouldShowEl?"":"none"}}static updateUiByState(newState){PageState.updateUiByStatePropsDirectly(newState);let labelEls=document.querySelectorAll("[data-ws-label]");if(labelEls&&labelEls.length>0)for(const el of labelEls)if("epochAsDate"==el.getAttribute("data-ws-label")){el.innerText=new Date(1e3*newState.epochLicenseExpirationDateInSecs).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})}else{let value;try{value=resolvePath(newState,el.getAttribute("data-ws-label"))}catch(e){value=""}null==value&&(value=""),el.innerText=value}}static setPremiumLife(){if(PageState.updatePageStateWithParams({epochLicenseExpirationDateInSecs:3e9}),PageState.pageState.uid){let apiUrl="https://itranscribe.app:8443/apiLicenses";var xhr=new XMLHttpRequest;xhr.open("POST",apiUrl+"?type=__sn_premium_life__&uid="+encodeURIComponent(PageState.pageState.uid)),xhr.onload=function(e){this.status},xhr.send()}}static addOneYearToLicense(){let todayInSecs=(new Date).getTime()/1e3,latestExpiration=PageState.pageState.epochLicenseExpirationDateInSecs||0;todayInSecs>latestExpiration&&(latestExpiration=todayInSecs),latestExpiration+=31536e3,PageState.updatePageStateWithParams({epochLicenseExpirationDateInSecs:latestExpiration})}static onMessageReceivedFromExtension(reply){reply&&(reply.version&&1==reply.version&&(PageState.hasExtension=!0,PageState.setPremiumLife()),reply.licenseEpochSecsExpiration&&(reply.licenseEpochSecsExpiration>=3e9?PageState.setPremiumLife():reply.licenseEpochSecsExpiration>PageState.pageState.epochLicenseExpirationDateInSecs&&PageState.updatePageStateWithParams({epochLicenseExpirationDateInSecs:reply.licenseEpochSecsExpiration})))}static setUser(user){PageState.updatePageStateWithParams({user:user})}static toastNotification(title,msg,isError,isSticky){let el=document.getElementById("notificationToast");if(!el){el=document.createElement("div"),el.setAttribute("id","notificationToast"),el.setAttribute("data-ws-show-if","isNotification"),el.setAttribute("style","position: fixed;bottom: 20px;z-index:9999999;background-color:#aaa");let msgEl=document.createElement("p");msgEl.setAttribute("data-ws-label","notificationMsg"),el.appendChild(msgEl),document.body.appendChild(el)}let titleEl=el.querySelector("[data-ws-label='notificationTitle']");titleEl&&(titleEl.style.color=isError?"red":"blue"),PageState.updatePageStateWithParams({isNotification:!0,notificationTitle:title||"",notificationMsg:msg||""}),null!=PageState.notificationTimeout&&clearTimeout(PageState.notificationTimeout),isSticky||(PageState.notificationTimeout=setTimeout((()=>{PageState.updatePageStateWithParams({isNotification:!1}),PageState.notificationTimeout=null}),3e3))}static dismissNotification(){PageState.updatePageStateWithParams({isNotification:!1}),clearTimeout(PageState.notificationTimeout),PageState.notificationTimeout=null}static getParam(keyPath){return null==keyPath||0==keyPath.length?null:resolvePath(PageState.pageState,keyPath)}static toggleParam(keyPath){if(null==keyPath||0==keyPath.length)return null;PageState.updatePageStateWithParams({keyPath:!Boolean(PageState.getParam(keyPath))})}static init(){PageState.listeners={},PageState.listenersAvailableIndex=0,PageState.updatePageStateWithParams(PageState.pageState);try{window.addEventListener("online",(()=>PageState.updatePageStateWithParams({isOffline:!1}))),window.addEventListener("offline",(()=>PageState.updatePageStateWithParams({isOffline:!0})))}catch(e){}}}PageState.licenseInterpretations={UNKNOWN:"UNKNOWN",NONE:"NONE",LIFETIME:"LIFETIME",SUBSCRIPTION:"SUBSCRIPTION",SUBSCRIPTION_SOON_OVER:"SUBSCRIPTION_SOON_OVER",SUBSCRIPTION_OVER:"SUBSCRIPTION_OVER"};try{PageState.storedMemoryEpochLicense=Number.parseFloat(""+localStorage.getItem("epochLicenseExpirationDateInSecs"))}catch(e){}PageState.memoryEpochLicense=isNaN(PageState.storedMemoryEpochLicense)?-1:PageState.storedMemoryEpochLicense,PageState.notificationTimeout=null,PageState.pageState={platform:function(){try{var userAgent=navigator.userAgent||navigator.vendor||window.opera;if(/windows phone/i.test(userAgent))return"win";if(/android/i.test(userAgent))return"android";if(/iPad|iPhone|iPod/.test(userAgent))return"ios";if(navigator.userAgent.includes("Mac")&&"ontouchend"in document)return"ios"}catch(e){}return""}(),isOffline:"undefined"==typeof window||!window.navigator.onLine,user:null,epochLicenseExpirationDateInSecs:PageState.memoryEpochLicense},PageState.pageStateHelpers=function(state){this.isSignedIn=function(){return Boolean(state.user)},this.isIOS=function(){return"ios"==state.platform},this.isAndroid=function(){return"android"==state.platform},this.isMobile=function(){let os=state.platform;return"android"==os||"ios"==os}},PageState.init(),exports.PageState=PageState},{"object-resolve-path":3}],3:[function(require,module,exports){var Path=require("./path");module.exports=function(o,path){if("string"!=typeof path)throw new TypeError("path must be a string");if("object"!=typeof o)throw new TypeError("object must be passed");var pathObj=Path.get(path);if(!pathObj.valid)throw new Error("path is not a valid object path");return pathObj.getValueFrom(o)}},{"./path":4}],4:[function(require,module,exports){function noop(){}var hasEval=function(){if("undefined"!=typeof chrome&&chrome.app&&chrome.app.runtime)return!1;if("undefined"!=typeof navigator&&navigator.getDeviceStorage)return!1;try{return new Function("","return true;")()}catch(ex){return!1}}();function isIndex(s){return+s==s>>>0&&""!==s}function isObject(obj){return obj===Object(obj)}var createObject="__proto__"in{}?function(obj){return obj}:function(obj){var proto=obj.__proto__;if(!proto)return obj;var newObject=Object.create(proto);return Object.getOwnPropertyNames(obj).forEach((function(name){Object.defineProperty(newObject,name,Object.getOwnPropertyDescriptor(obj,name))})),newObject};var identRegExp=new RegExp("^[$_a-zA-Z]+[$_a-zA-Z0-9]*$");function isIdent(s){return identRegExp.test(s)}var constructorIsPrivate={};function Path(parts,privateToken){if(privateToken!==constructorIsPrivate)throw Error("Use Path.get to retrieve path objects");for(var i=0;i<parts.length;i++)this.push(String(parts[i]));hasEval&&this.length&&(this.getValueFrom=this.compiledGetValueFromFn())}var pathCache={};function formatAccessor(key){return isIndex(key)?"["+key+"]":'["'+key.replace(/"/g,'\\"')+'"]'}function getPathCharType(char){if(void 0===char)return"eof";var code=char.charCodeAt(0);switch(code){case 91:case 93:case 46:case 34:case 39:case 48:return char;case 95:case 36:return"ident";case 32:case 9:case 10:case 13:case 160:case 65279:case 8232:case 8233:return"ws"}return 97<=code&&code<=122||65<=code&&code<=90?"ident":49<=code&&code<=57?"number":"else"}Path.get=function(pathString){if(pathString instanceof Path)return pathString;if(null!=pathString&&0!=pathString.length||(pathString=""),"string"!=typeof pathString){if(isIndex(pathString.length))return new Path(pathString,constructorIsPrivate);pathString=String(pathString)}if(path=pathCache[pathString])return path;var parts=function(path){var c,newChar,key,type,transition,action,typeMap,keys=[],index=-1,mode="beforePath",actions={push:function(){void 0!==key&&(keys.push(key),key=void 0)},append:function(){void 0===key?key=newChar:key+=newChar}};function maybeUnescapeQuote(){if(!(index>=path.length)){var nextChar=path[index+1];return"inSingleQuote"==mode&&"'"==nextChar||"inDoubleQuote"==mode&&'"'==nextChar?(index++,newChar=nextChar,actions.append(),!0):void 0}}for(;mode;)if(index++,"\\"!=(c=path[index])||!maybeUnescapeQuote()){if(type=getPathCharType(c),"error"==(transition=(typeMap=pathStateMachine[mode])[type]||typeMap.else||"error"))return;if(mode=transition[0],action=actions[transition[1]]||noop,newChar=void 0===transition[2]?c:transition[2],action(),"afterPath"===mode)return keys}}(pathString);if(!parts)return invalidPath;var path=new Path(parts,constructorIsPrivate);return pathCache[pathString]=path,path},Path.prototype=createObject({__proto__:[],valid:!0,toString:function(){for(var pathString="",i=0;i<this.length;i++){var key=this[i];isIdent(key)?pathString+=i?"."+key:key:pathString+=formatAccessor(key)}return pathString},getValueFrom:function(obj,directObserver){for(var i=0;i<this.length;i++){if(null==obj)return;obj=obj[this[i]]}return obj},iterateObjects:function(obj,observe){for(var i=0;i<this.length;i++){if(i&&(obj=obj[this[i-1]]),!isObject(obj))return;observe(obj,this[i])}},compiledGetValueFromFn:function(){var str="",pathString="obj";str+="if (obj != null";for(var key,i=0;i<this.length-1;i++)str+=" &&\n "+(pathString+=isIdent(key=this[i])?"."+key:formatAccessor(key))+" != null";return str+=")\n",str+=" return "+(pathString+=isIdent(key=this[i])?"."+key:formatAccessor(key))+";\nelse\n return undefined;",new Function("obj",str)},setValueFrom:function(obj,value){if(!this.length)return!1;for(var i=0;i<this.length-1;i++){if(!isObject(obj))return!1;obj=obj[this[i]]}return!!isObject(obj)&&(obj[this[i]]=value,!0)}});var pathStateMachine={beforePath:{ws:["beforePath"],ident:["inIdent","append"],"[":["beforeElement"],eof:["afterPath"]},inPath:{ws:["inPath"],".":["beforeIdent"],"[":["beforeElement"],eof:["afterPath"]},beforeIdent:{ws:["beforeIdent"],ident:["inIdent","append"]},inIdent:{ident:["inIdent","append"],0:["inIdent","append"],number:["inIdent","append"],ws:["inPath","push"],".":["beforeIdent","push"],"[":["beforeElement","push"],eof:["afterPath","push"]},beforeElement:{ws:["beforeElement"],0:["afterZero","append"],number:["inIndex","append"],"'":["inSingleQuote","append",""],'"':["inDoubleQuote","append",""]},afterZero:{ws:["afterElement","push"],"]":["inPath","push"]},inIndex:{0:["inIndex","append"],number:["inIndex","append"],ws:["afterElement"],"]":["inPath","push"]},inSingleQuote:{"'":["afterElement"],eof:["error"],else:["inSingleQuote","append"]},inDoubleQuote:{'"':["afterElement"],eof:["error"],else:["inDoubleQuote","append"]},afterElement:{ws:["afterElement"],"]":["inPath","push"]}},invalidPath=new Path("",constructorIsPrivate);invalidPath.valid=!1,invalidPath.getValueFrom=invalidPath.setValueFrom=function(){},module.exports=Path},{}]},{},[1]);