language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class Husky extends Dog {
shed() {
console.log('Husky dog breed has a beautiful');
}
} |
JavaScript | class XMLHttpRequest {
constructor (xhr) {
this.xhr = xhr
this.id = this.xhr.id
this.url = this.xhr.url
this.method = this.xhr.method
this.status = null
this.statusMessage = null
this.request = {}
this.response = null
}
_getXhr () {
this.xhr = this.xhr ?? $errUtils.throwErrByPath('xhr.missing')
return this.xhr
}
_setDuration (timeStart) {
this.duration = (new Date) - timeStart
}
_setStatus () {
this.status = this.xhr.status
this.statusMessage = `${this.xhr.status} (${this.xhr.statusText})`
}
_setRequestBody (requestBody = null) {
this.request.body = parseJSON(requestBody)
}
_setResponseBody () {
if (this.response == null) {
this.response = {}
}
try {
this.response.body = parseJSON(this.xhr.responseText)
} catch (e) {
this.response.body = this.xhr.response
}
}
_setResponseHeaders () {
// parse response header string into object
// https://gist.github.com/monsur/706839
const headerStr = this.xhr.getAllResponseHeaders()
const set = (resp) => {
if (this.response == null) {
this.response = {}
}
this.response.headers = resp
}
const headers = {}
if (!headerStr) {
return set(headers)
}
const headerPairs = headerStr.split('\u000d\u000a')
for (let headerPair of headerPairs) {
// Can't use split() here because it does the wrong thing
// if the header value has the string ": " in it.
const index = headerPair.indexOf('\u003a\u0020')
if (index > 0) {
const key = headerPair.substring(0, index)
const val = headerPair.substring(index + 2)
headers[key] = val
}
}
return set(headers)
}
_getFixtureError () {
const body = this.response && this.response.body
const err = body.__error
if (body && err) {
return err
}
}
_setRequestHeader (key, val) {
if (isCypressHeaderRe.test(key)) {
return
}
if (this.request.headers == null) {
this.request.headers = {}
}
const current = this.request.headers[key]
// if we already have a request header
// then prepend val with ', '
if (current) {
val = `${current}, ${val}`
}
this.request.headers[key] = val
}
setRequestHeader (...args) {
return this.xhr.setRequestHeader.apply(this.xhr, args)
}
getResponseHeader (...args) {
return this.xhr.getResponseHeader.apply(this.xhr, args)
}
getAllResponseHeaders (...args) {
return this.xhr.getAllResponseHeaders.apply(this.xhr, args)
}
static add (xhr) {
return new XMLHttpRequest(xhr)
}
} |
JavaScript | class CW_AdviceContent_Website extends CW_AdviceContent
{
/**
* Create an instance for a finished command and testResult
*
* @param {*} command The command that has finished
* @param {*} testResult A test_result object to parse
* @param {*} configObject A user's config object
*/
constructor( { command = null, testResult = null, configObject = null } )
{
super({
category: "website",
command: command,
testResult: testResult
});
this.configObject = configObject;
}
/**
* Advice content hub for "website" requests.
*
* Once an Advice object has its test results, the parser runs this category-specific method to
* produce an action object
*
* @author costmo
*
*/
advise()
{
// The only PUNT condition is a redirect
if( this.test_result.result == CW_Constants.RESULT_PUNT )
{
// If the redirect points to something other than the user's domain, set the severity
if( this.test_result.raw_response.raw_response.indexOf( this.configObject.domain ) > -1 )
{
this.test_result.result = CW_Constants.RESULT_PASS;
}
}
// Got a direct message back from a system error
if( this.test_result.result == CW_Constants.RESULT_FAIL &&
this.test_result.raw_response.message && this.test_result.raw_response.message.length > 0 )
{
this.severity = CW_Constants.SEVERITY_DIRECT_MESSAGE;
this.content = this.test_result.raw_response.message;
}
else
{
if( this.command == "website-content" )
{
let tags = this.resultTagsForContent( { inputObject: this.test_result.raw_response } );
// Nothing was wrong
if( tags.length < 1 )
{
this.severity = this.resultTagToSeverity( { resultTag: CW_Constants.RESULT_PASS } );
this.content = this.contentForSeverity( { severity: this.severity } );
}
else
{
// handle more complicated severity determinations
this.content = "";
tags.forEach(
tag =>
{
let severity = this.resultTagToSeverity( { resultTag: tag.result_value, extraKey: tag.intermediate_key } );
if( severity > this.severity )
{
this.severity = severity;
this.test_result.result = tag.result_value;
}
this.content += this.contentForSeverity( { severity: severity, extraInput: tag.intermediate_key } ) + "\n";
this.result = tag.result_value;
}
);
}
}
else if( (this.command == "http-response" || this.command == "https-response" ||
this.command == "website" || this.command == "secure-website" )
&&
(this.test_result.raw_response.raw_response == "NO_RESPONSE" || // raw_response for http(s)-response generated objects is an object containing a raw_response
this.test_result.raw_response == "NOT_FOUND" ||
this.test_result.raw_response == "TIMED_OUT" ) )
{
let extraInput = (this.command.indexOf( "http" ) === 0 ) ? this.test_result.raw_response.raw_response : this.test_result.raw_response;
this.severity = this.resultTagToSeverity( { resultTag: this.test_result.result } );
this.content = this.contentForSeverity( { severity: this.severity, extraInput: extraInput } );
}
else if(this.command == "website" || this.command == "secure-website" ) // website command passed useful information from the test back to here
{
let extraInput = this.test_result.raw_response;
this.severity = this.resultTagToSeverity( { resultTag: this.test_result.result, extraKey: "REPLACEMENT" } );
this.content = this.contentForSeverity( { severity: this.severity, extraInput: "REPLACEMENT" } );
this.content = this.content.replace( '%response%', this.test_result.raw_response );
}
else
{
this.severity = this.resultTagToSeverity( { resultTag: this.test_result.result } );
this.content = this.contentForSeverity( { severity: this.severity } );
}
}
}
/**
* Provide the content for the discovered severity on the current instance's command.
*
* Commands in the "local" category only need content for ESSENTIAL and URGENTt
*
* @author costmo
* @param {*} severity The severity for which content is needed
* @param {*} extraInput Extra input needed to form a more precise response
*/
contentForSeverity( { severity = null, extraInput = null } )
{
let strings = require( "./strings/category.website.js" );
switch( severity )
{
case CW_Constants.SEVERITY_NOTICE:
if( extraInput &&
undefined != (strings[ this.command ][ extraInput ][ CW_Constants.NAME_SEVERITY_NOTICE ]) )
{
return strings[ this.command ][ extraInput ][ CW_Constants.NAME_SEVERITY_NOTICE ];
}
else
{
return strings[ this.command ][ CW_Constants.NAME_SEVERITY_NOTICE ];
}
case CW_Constants.SEVERITY_ESSENTIAL:
case CW_Constants.SEVERITY_URGENT:
if( extraInput &&
undefined != (strings[ this.command ][ extraInput ][ CW_Constants.NAME_SEVERITY_URGENT ]) )
{
return strings[ this.command ][ extraInput ][ CW_Constants.NAME_SEVERITY_URGENT ]
}
else
{
return strings[ this.command ][ CW_Constants.NAME_SEVERITY_URGENT ];
}
default:
return "";
}
}
/**
* Override default "tag to severity" mapping for this specific "local" request
*
* Uses the system default for anything other than "FAIL"
*
* @param {*} resultTag The result tag to map
* @param {*} extraKey An optional extra key to help refine the lookup
*/
resultTagToSeverity( { resultTag = null, extraKey = null } )
{
switch( resultTag )
{
// PUNT will happen if there is a redirect and the redirect location domain does not match
case "PUNT":
return CW_Constants.SEVERITY_NOTICE;
case "FAIL":
if( extraKey && extraKey.length > 0 )
{
switch( extraKey )
{
case "HEAD_NONE":
case "H1_NONE":
case "NOINDEX":
case "REPLACEMENT":
return CW_Constants.SEVERITY_NOTICE;
default:
return CW_Constants.SEVERITY_URGENT;
}
}
else // end if( extraKey && extraKey.length > 0 ) for case: FAIL
{
return CW_Constants.SEVERITY_URGENT;
}
default:
return super.resultTagToSeverity( { resultTag: resultTag } );
}
}
/**
* A string of tests to run gathered test info to look for problems.
*
* @returns Array
* @author costmo
* @param {*} inputObject The raw_response from the runner
*/
resultTagsForContent( { inputObject = null } )
{
let returnValue = [];
// We get a DOM tree if there are real results to examine. Otherwise, there was an error getting the DOM
if( typeof inputObject !== "object" )
{
returnValue.push(
{
intermediate_key: inputObject,
result_value: CW_Constants.RESULT_FAIL
}
);
return returnValue;
}
// A series of things that should be present in the HTML
if( (!inputObject.headNode.childNodes) ||
(inputObject.headNode.childNodes.length < 1) )
{
returnValue.push(
{
intermediate_key: "HEAD_NONE",
result_value: CW_Constants.RESULT_FAIL
}
);
}
if( (!inputObject.titleNode.childNodes) ||
(inputObject.titleNode.childNodes.length < 1) ||
(inputObject.titleNode.rawText.length < 1) )
{
returnValue.push(
{
intermediate_key: "TITLE_NONE",
result_value: CW_Constants.RESULT_FAIL
}
);
}
if( (!inputObject.bodyNode.childNodes) ||
(inputObject.bodyNode.childNodes.length < 1) ||
(inputObject.bodyNode.rawText.length < 1) )
{
returnValue.push(
{
intermediate_key: "BODY_NONE",
result_value: CW_Constants.RESULT_FAIL
}
);
}
// We're only checking for 1
if( (!inputObject.h1Node.childNodes) ||
(inputObject.h1Node.childNodes.length < 1) /*|| // requires separate parsing if there's more than one
(inputObject.h1Node.rawText.length < 1)*/ )
{
returnValue.push(
{
intermediate_key: "H1_NONE",
result_value: CW_Constants.RESULT_FAIL
}
);
}
// walk through meta tags to find a "noindex"
if( inputObject.metaNodes &&
inputObject.metaNodes.length > 0 )
{
inputObject.metaNodes.forEach(
node =>
{
if( node.rawAttrs.indexOf( "noindex" ) > -1 )
{
returnValue.push(
{
intermediate_key: "NOINDEX",
result_value: CW_Constants.RESULT_FAIL
}
);
}
}
);
}
return returnValue;
}
/**
* Offers advice while tests are in-progress
*
* @returns mixed Returns an objcet or prints to the screen
* @author costmo
*
* @param {*} testKey A key to identify what is being tested
* @param {*} configObject A constructed configuration object
* @param {*} returnType "screen" to display the results, anything else to get an object
*/
inProgressAdvice( {testKey = null, configObject = null, returnType = "screen"} )
{
let returnValue = {
printAnswer: "",
printSubject: "",
printDetail: ""
};
let severity = 0;
let serverArray = [];
let tags = [];
if( !configObject.be_quiet )
{
// which test to run
switch( testKey )
{
case "SSL":
process.stdout.write( "Finding SSL grade... ".header );
if( this.test_result.raw_response.grade )
{
process.stdout.write( "good\n".ok );
process.stdout.write( "Received grade: ".text );
process.stdout.write( this.test_result.raw_response.grade.ok + "\n\n" );
}
else
{
process.stdout.write( "failed\n".error );
process.stdout.write( this.test_result.raw_response.message.error + "\n\n" );
}
break;
case "SSL_EXPIRATION":
if( this.test_result.result == CW_Constants.RESULT_FAIL )
{
process.stdout.write( "failed\n".error );
process.stdout.write( this.test_result.raw_response.message.error + "\n\n" );
}
else if( this.test_result.raw_response.daysLeft > 30 )
{
process.stdout.write( "good\n".ok );
process.stdout.write( "Days until expiration: ".text );
process.stdout.write( this.test_result.raw_response.daysLeft.toString().result + "\n\n" );
}
else if( this.test_result.raw_response.daysLeft > 0 )
{
process.stdout.write( "warning\n".warn );
process.stdout.write( "Days until expiration: ".warn );
process.stdout.write( this.test_result.raw_response.daysLeft.toString().warn + "\n" );
severity = this.resultTagToSeverity( { resultTag: CW_Constants.RESULT_PUNT } );
let content = this.contentForSeverity( { severity: severity, extraInput: "EXPIRE_SOON" } );
process.stdout.write( content.warn + "\n\n" );
}
else
{
process.stdout.write( "expired\n".error );
severity = this.resultTagToSeverity( { resultTag: CW_Constants.RESULT_FAIL } );
let content = this.contentForSeverity( { severity: severity, extraInput: "EXPIRED" } );
process.stdout.write( content.error + "\n\n" );
}
break;
// TODO: These conditions need to be refactored
case "WEBSITE_CONTENT":
// Show a header
tags = [];
// We got an empty response
if( typeof this.test_result.raw_response !== "object" )
{
tags.push(
{
intermediate_key: this.test_result,
result_value: CW_Constants.RESULT_FAIL
}
);
}
else
{
let content = "";
// These can all be done at once, but are separated here to show "progress"
process.stdout.write( "Looking for HTML \"HEAD\" tag... ".header );
if( (!this.test_result.raw_response.headNode.childNodes) ||
(this.test_result.raw_response.headNode.childNodes.length < 1) )
{
process.stdout.write( "failed\n".error );
severity = this.resultTagToSeverity( { resultTag: CW_Constants.RESULT_FAIL } );
content = this.contentForSeverity( { severity: severity, extraInput: "HEAD_NONE" } );
process.stdout.write( content.error + "\n\n" );
}
else
{
process.stdout.write( "good\n\n".ok );
}
process.stdout.write( "Looking for HTML \"BODY\" tag... ".header );
if( (!this.test_result.raw_response.bodyNode.childNodes) ||
(this.test_result.raw_response.bodyNode.childNodes.length < 1) ||
(this.test_result.raw_response.bodyNode.rawText.length < 1) )
{
process.stdout.write( "failed\n".error );
severity = this.resultTagToSeverity( { resultTag: CW_Constants.RESULT_FAIL } );
content = this.contentForSeverity( { severity: severity, extraInput: "BODY_NONE" } );
process.stdout.write( content.error + "\n\n" );
}
else
{
process.stdout.write( "good\n\n".ok );
}
process.stdout.write( "Looking for HTML \"TITLE\" tag... ".header );
if( (!this.test_result.raw_response.titleNode.childNodes) ||
(this.test_result.raw_response.titleNode.childNodes.length < 1) ||
(this.test_result.raw_response.titleNode.rawText.length < 1) )
{
process.stdout.write( "failed\n".error );
severity = this.resultTagToSeverity( { resultTag: CW_Constants.RESULT_FAIL } );
content = this.contentForSeverity( { severity: severity, extraInput: "TITLE_NONE" } );
process.stdout.write( content.error + "\n\n" );
}
else
{
process.stdout.write( "good\n\n".ok );
}
process.stdout.write( "Looking for HTML \"H1\" tag... ".header );
if( (!this.test_result.raw_response.h1Node.childNodes) ||
(this.test_result.raw_response.h1Node.childNodes.length < 1) )
{
process.stdout.write( "warning\n".warn );
severity = this.resultTagToSeverity( { resultTag: CW_Constants.RESULT_PUNT } );
let content = this.contentForSeverity( { severity: severity, extraInput: "H1_NONE" } );
process.stdout.write( content.warn + "\n\n" );
}
else
{
process.stdout.write( "good\n\n".ok );
}
let foundNoindex = false;
process.stdout.write( "Looking for HTML \"NOINDEX\" tag... ".header );
if( this.test_result.raw_response.metaNodes &&
this.test_result.raw_response.metaNodes.length > 0 )
{
this.test_result.raw_response.metaNodes.forEach(
node =>
{
if( node.rawAttrs.indexOf( "noindex" ) > -1 )
{
foundNoindex = true;
}
}
);
if( foundNoindex )
{
process.stdout.write( "warning\n".warn );
severity = this.resultTagToSeverity( { resultTag: CW_Constants.RESULT_PUNT } );
let content = this.contentForSeverity( { severity: severity, extraInput: "NOINDEX" } );
process.stdout.write( content.warn + "\n\n" );
}
else
{
process.stdout.write( "good\n\n".ok );
}
}
}
break; // case "WEBSITE_CONTENT":
case "WEBSITE_AVAILABILITY":
let extraInput = this.test_result.raw_response;
let CW_PromiseResolver = require( "./CW_PromiseResolver" );
process.stdout.write( "Testing port availability... ".header );
if( parseFloat( extraInput.raw_response.avg ) + "" !== "NaN" )
{
process.stdout.write( "good\n".ok );
if( extraInput.raw_response.avg > CW_PromiseResolver.MAX_HTTTP_RESPONSE_TIME )
{
process.stdout.write( "Response time: ".header + extraInput.raw_response.avg.toString().warn + "ms\n".warn );
process.stdout.write( this.contentForSeverity( { severity: CW_Constants.SEVERITY_NOTICE, extraInput: "TIMED_OUT" } ).warn + "\n" );
}
else
{
process.stdout.write( "Response time: ".header + Math.ceil( extraInput.raw_response.avg ).toString().result + "ms\n".result );
}
}
else
{
process.stdout.write( "good\n\n".ok );
}
break; // case "WEBSITE_AVAILABILITY":
case "WEBSITE_RESPONSE":
let responseInput = this.test_result.raw_response;
process.stdout.write( "Testing site response status code... ".header );
if( responseInput.result == CW_Constants.RESULT_PUNT ) // handle redirect -- 4xx and 5xx responses show up as errors
{
if( responseInput.raw_response.indexOf( configObject.domain ) > -1 )
{
process.stdout.write( "good\n\n".ok );
}
else // Warn/fail on bad response codes
{
process.stdout.write( "warning\n".warn );
process.stdout.write( responseInput.warn + "\n\n" );
}
}
else if( responseInput.result == CW_Constants.RESULT_PASS )
{
process.stdout.write( "good\n\n".ok );
}
else
{
process.stdout.write( "fail\n".error );
process.stdout.write( responseInput.error + "\n\n" );
}
break; // case "WEBSITE_AVAILABILITY":
} // switch( testKey )
} // if( !configObject.be_quiet )
// output of "screen" is handled through the be_quiet flag
if( returnType !== "screen" )
{
return returnValue;
}
}
} |
JavaScript | class Drug {
/**
* Instanciate a drug item.
* @param {string} name The name of the drug.
* @param {number} expiresIn Denotes the number of days we have until the item expires.
* @param {number} benefit Denotes how powerful the drug is.
*/
constructor(name, expiresIn, benefit) {
this.name = name;
this.expiresIn = expiresIn;
this.benefit = benefit;
this.degradationRate = 1;
this.degradationMethod = {};
this.degradationMethod['Doliprane'] = () => this.nomalDrugBenefitUpdate();
this.degradationMethod['Herbal Tea'] = () => this.herbalTeaBenefitUpdate();
this.degradationMethod['Fervex'] = () => this.fervexBenefitUpdate();
this.degradationMethod['Magic Pill'] = () => this.magicPillBenefitUpdate();
this.degradationMethod['Dafalgan'] = () => this.nomalDrugBenefitUpdate();
if (this.name == "Dafalgan") this.degradationRate = 2;
}
/**
* Update the benefit and expiresIn values accordingly with the drugs names.
*/
updateBenefitValue() {
if (this.degradationMethod.hasOwnProperty(this.name)) {
this.degradationMethod[this.name]();
} else {
// If the drug is not known considers it as a normal drug.
this.nomalDrugBenefitUpdate();
}
}
/**
* Once the expiration date has passed, Benefit degrades twice as fast.
* The Benefit of an item is never negative.
*/
nomalDrugBenefitUpdate() {
this.expiresIn--;
if (this.expiresIn < 0) {
this.benefit -= 2 * this.degradationRate;
} else {
this.benefit -= this.degradationRate;
}
this.checkBenefitValue();
}
/**
* "Herbal Tea" actually increases in Benefit the older it gets.
* Benefit increases twice as fast after the expiration date.
* The Benefit of an item is never more than 50.
* The Benefit of an item is never negative.
*/
herbalTeaBenefitUpdate() {
this.expiresIn--;
if (this.expiresIn < 0) {
this.benefit += 2;
} else {
this.benefit++;
}
this.checkBenefitValue();
}
checkBenefitValue() {
if (this.benefit < 0) this.benefit = 0;
if (this.benefit > 50) this.benefit = 50;
}
/**
* "Magic Pill" never expires nor decreases in Benefit.
*/
magicPillBenefitUpdate() {
this.checkBenefitValue();
}
/**
* "Fervex", like Herbal Tea, increases in Benefit as its expiration date approaches.
* Benefit increases by 2 when there are 10 days or less and by 3 when there are 5 days or less
* but Benefit drops to 0 after the expiration date.
*/
fervexBenefitUpdate() {
this.expiresIn--;
if (this.expiresIn < 0) {
this.benefit = 0;
} else {
this.benefit++;
if (this.expiresIn <= 10) this.benefit++;
if (this.expiresIn <= 5) this.benefit++;
}
this.checkBenefitValue();
}
} |
JavaScript | class VectorTilesSource extends TMSSource {
/**
* @param {Object} source - An object that can contain all properties of a
* VectorTilesSource and {@link Source}.
* @param {string|Object} source.style - The URL of the JSON style, of the
* JSON style directly.
* @param {string} [source.sprite] - The base URL to load informations about
* the sprite of the style. If this is set, it overrides the `sprite` value
* of the `source.style`.
* @param {string} [source.url] - The base URL to load the tiles. If no url
* is specified, it reads it from the loaded style. Read [the Mapbox Style
* Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/)
* for more informations.
*
* @constructor
*/
constructor(source) {
source.format = 'application/x-protobuf;type=mapbox-vector';
source.crs = 'EPSG:3857';
source.isInverted = true;
source.url = source.url || '.';
super(source);
const ffilter = source.filter || (() => true);
this.layers = {};
this.styles = {};
let promise;
if (source.style) {
if (typeof source.style == 'string') {
promise = Fetcher.json(source.style, this.networkOptions);
} else {
promise = Promise.resolve(source.style);
}
} else {
throw new Error('New VectorTilesSource: style is required');
}
this.whenReady = promise.then((style) => {
const baseurl = source.sprite || style.sprite;
if (baseurl) {
return Fetcher.json(`${baseurl}.json`, this.networkOptions).then((sprites) => {
this.sprites = sprites;
return Fetcher.texture(`${baseurl}.png`, this.networkOptions).then((texture) => {
this.sprites.img = texture.image;
return style;
});
});
}
return style;
}).then((style) => {
const s = Object.keys(style.sources)[0];
const os = style.sources[s];
style.layers.forEach((layer, order) => {
layer.sourceUid = this.uid;
if (layer.type === 'background') {
this.backgroundLayer = layer;
} else if (ffilter(layer)) {
// TODO: add support for expressions
// https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions
let stops = [];
checkStopsValues(layer.layout, stops);
checkStopsValues(layer.paint, stops);
let minStop = Math.min(...stops);
// if none is found, default to 0
minStop = (minStop == Infinity) ? 0 : minStop;
// compare to layer.minzoom and take the highest
minStop = (layer.minzoom == undefined) ? minStop : Math.max(layer.minzoom, minStop);
stops.push(minStop);
stops.push(layer.maxzoom == undefined ? 24 : layer.maxzoom);
stops.sort((a, b) => (a - b));
// remove all value < minStop
stops = stops.filter(s => s >= minStop);
this.styles[layer.id] = [];
for (let i = 0; i < stops.length - 1; i++) {
if (stops[i] == stops[i + 1]) { continue; }
const style = new Style();
style.zoom.min = stops[i];
style.zoom.max = stops[i + 1];
style.setFromVectorTileLayer(layer, this.sprites, order, this.symbolToCircle);
this.styles[layer.id].push(style);
}
if (!this.layers[layer['source-layer']]) {
this.layers[layer['source-layer']] = [];
}
this.layers[layer['source-layer']].push({
id: layer.id,
order,
filterExpression: featureFilter(layer.filter),
zoom: {
min: stops[0],
max: stops[stops.length - 1],
},
});
}
});
if (this.url == '.') {
if (os.url) {
return Fetcher.json(os.url, this.networkOptions).then((tileJSON) => {
if (tileJSON.tiles[0]) {
this.url = toTMSUrl(tileJSON.tiles[0]);
}
});
} else if (os.tiles[0]) {
this.url = toTMSUrl(os.tiles[0]);
}
}
});
}
} |
JavaScript | class Snake extends GameObject {
constructor(x, y, length, direction) {
super(x, y, false, document.getElementById('snake'));
this.length = length;
// Here we can specify number of lives the snake has
this.lives = Helper.DefaultSnakeProperties.LIVES;
// Snake has the ability to grow, so this field is not constant
this.length = length;
// the snake is green
this.color = 'green';
//Here we are logging positions which were visited by snake's head
// in order to know the way of the rest body parts
this.positionStack = [];
//This array holds snake's body parts - everything but the head
this.bodyArray = [];
//This field must be updated only using enumeration Directions.
// It keeps the direction in which the snake is moving.
this.direction = direction;
//This field holds number of eaten food in order to know when to grow.
// It is reset each time the snake grows.
this.foodEaten = 0;
//This field is holding the total number of eaten food aka the score.
this.totalFood = 0;
}
//This method is called on update instead of GameObject default method
update() {
//Creates new position from the current snake's head position to store in the position stack
var position = {
X: this.position.X,
Y: this.position.Y
}
//adds position to the stack
this.positionStack.unshift(position);
//removes unneeded position from the stack's end
this.positionStack.pop();
//calculates new position depending on the current direction
switch (this.direction) {
case Helper.Directions.DOWN:
this.position.Y += this.size.HEIGHT;
break;
case Helper.Directions.UP:
this.position.Y -= this.size.HEIGHT;
break;
case Helper.Directions.LEFT:
this.position.X -= this.size.WIDTH;
break;
case Helper.Directions.RIGHT:
this.position.X += this.size.WIDTH;
break;
default:
throw new Error('Pease, use Directions enumerations.');
break;
}
//updates all body parts' positions
for (var i = 0; i < this.length; i++) {
this.bodyArray[i].position = this.positionStack[i];
}
//checks if the snake has eaten enough food and if so makes it grow
if (this.foodEaten == Helper.DefaultSnakeProperties.FOOD) {
this.foodEaten = 0;
this.grow();
}
}
//This method can be used with any user interface to change the snake's direction
//(may be it could be made public so the snake could be controlled from outside the engine)
changeDirection(direction) {
this.direction = direction;
}
//This method describes how the snake manages collisions
onCollision(colilisionObject) {
// if the collision object is food it increases its foodEaten and totalFood fields
if (colilisionObject.canBeEaten) {
this.foodEaten++;
this.totalFood++;
} else {
if (this.lives > 0) {
this.lives--;
this.reset();
} else {
Engine.endGame();
}
}
// if the collision object is not food,
// it checks number of lives and if it is equal to 0 - dies,
//if not - decreases number of lives and resets it self
}
// This method makes the snake grow
// It is creating new body element on the top of the last element
// (it is done to avoid difficult calculations)
// on the next update they will have different positions and the snake will be longer
grow() {
// Create new position
var position = {
X: this.bodyArray[this.length - 1].position.X,
Y: this.bodyArray[this.length - 1].position.Y
}
// Create new body part
var bodyPart = new SnakeBody(position.X, position.Y);
// Push body part to bodyArray and position to position stack
this.bodyArray.push(bodyPart);
this.positionStack.push(position);
// increase length
this.length++;
}
//This method is called when the snake dies, but have more lives.
//It wipes the snake and positions it in the left part of the field and sets direction to right
reset() {
// Set direction
this.direction = Helper.Directions.RIGHT;
// Set snake head position (x is calculated, y is random)
var x = (this.length + 2) * this.size.WIDTH;
var y = Helper.getRandomPositionY(0, Helper.FieldSize.HEIGHT - this.size.HEIGHT);
this.position.X = x;
this.position.Y = y;
// Set all body parts positions according to head
for (var i = 0; i < this.length; i++) {
this.bodyArray[i].position.X = (x - (i + 1) * this.size.WIDTH);
this.bodyArray[i].position.Y = y;
this.positionStack[i] = this.bodyArray[i].position;
}
// Update position stack
}
//This method draws the snake, including all it's body parts and some statistics
draw(ctx) {
// Draw the head
super.draw(ctx);
// Draw all body parts
for (var i = 0; i < this.length; i++) {
this.bodyArray[i].draw(ctx);
}
// Output number of lives and score
document.getElementById('lives').innerHTML = this.lives;
document.getElementById('points').innerHTML = this.totalFood;
}
//This method returns true if the snake collides with itself
hasBittenHerSelf() {
var result = false;
for (var i = 0; i < this.length; i++) {
if (this.position.X === this.bodyArray[i].position.X &&
this.position.Y === this.bodyArray[i].position.Y) {
result = true;
break;
}
}
return result;
}
//This method returns true if the snake leaves the game field
isOutOfGameField() {
return this.position.X < 0 ||
this.position.X > Helper.FieldSize.WIDTH ||
this.position.Y < 0 ||
this.position.Y > Helper.FieldSize.HEIGHT;
}
} |
JavaScript | class B2BTimeline extends React.Component {
sortByYearMonth(activities) {
const newActivities = {};
activities.map((activity) => {
const month = new Date(activity.timestamp).getMonth() + 1;
const year = new Date(activity.timestamp).getFullYear();
if (newActivities[year] === undefined) {
newActivities[year] = {};
newActivities[year][month] = [];
return newActivities[year][month].push(activity);
} else if (newActivities[year][month] === undefined) {
newActivities[year][month] = [];
return newActivities[year][month].push(activity);
} else {
return newActivities[year][month].push(activity);
}
});
return newActivities;
}
timeline = (activities, icons, Activity) => {
const sorted = this.sortByYearMonth(activities);
return Object.keys(sorted)
.sort((a, b) => b - a)
.map(function(year) {
return Object.keys(sorted[year])
.sort((a, b) => b - a)
.map(function(month, i) {
return (
<React.Fragment key={`month-${month}-${i}`}>
<div className="raf-b2btimeline__time">
<TimeHeader>{`${MONTHS[month]} ${year}`}</TimeHeader>
</div>
{sorted[year][month].map((post, i) => (
<div className="raf-b2btimeline__post" key={`post-${i}`}>
<div
className="raf-b2btimeline__icon"
dangerouslySetInnerHTML={{
__html: icons[post.verb] || icon,
}}
/>
<div className="raf-b2btimeline__post-content">
{smartRender(
Activity,
post,
<B2BActivity activity={post} />,
)}
</div>
</div>
))}
</React.Fragment>
);
});
});
};
render() {
return (
<div className="raf-b2btimeline">
<div className="raf-b2btimeline__feed">
<div className="raf-b2btimeline__line">
<div className="line" />
</div>
{this.timeline(
this.props.activities,
this.props.icons,
this.props.Activity,
)}
</div>
</div>
);
}
} |
JavaScript | class CalendarPart extends DateComponentBase {
static get metadata() {
return metadata;
}
get _minTimestamp() {
return this._minDate.valueOf() / 1000;
}
get _maxTimestamp() {
return this._maxDate.valueOf() / 1000;
}
/**
* Returns the effective timestamp to be used by the respective calendar part
* @protected
*/
get _timestamp() {
let timestamp = this.timestamp !== undefined ? this.timestamp : getTodayUTCTimestamp(this._primaryCalendarType);
if (timestamp < this._minTimestamp || timestamp > this._maxTimestamp) {
timestamp = this._minTimestamp;
}
return timestamp;
}
get _localDate() {
return new Date(this._timestamp * 1000);
}
/**
* Returns a CalendarDate instance, representing the _timestamp getter - this date is central to all components' rendering logic
* @protected
*/
get _calendarDate() {
return CalendarDate.fromTimestamp(this._localDate.getTime(), this._primaryCalendarType);
}
/**
* Change a timestamp and enforce limits
*
* @param timestamp
* @protected
*/
_safelySetTimestamp(timestamp) {
const min = this._minDate.valueOf() / 1000;
const max = this._maxDate.valueOf() / 1000;
if (timestamp < min) {
timestamp = min;
}
if (timestamp > max) {
timestamp = max;
}
this.timestamp = timestamp;
}
/**
* Modify a timestamp by a certain amount of days/months/years and enforce limits
* @param amount
* @param unit
* @protected
*/
_safelyModifyTimestampBy(amount, unit) {
const newDate = modifyDateBy(this._calendarDate, amount, unit);
this._safelySetTimestamp(newDate.valueOf() / 1000);
}
_getTimestampFromDom(domNode) {
const oMonthDomRef = domNode.getAttribute("data-sap-timestamp");
return parseInt(oMonthDomRef);
}
} |
JavaScript | class MakeTransparentEffectAction extends LeveledEffectAction {
constructor() {
super(...arguments);
this._actionModel = { actionType: 'makeTransparent' };
}
/**
* @description Sets the tolerance used to accommodate variance in the background color.
* @param {number | string} value The tolerance used to accommodate variance in the background color. (Range: 0 to 100, Server default: 10)
*/
tolerance(value) {
this._actionModel.tolerance = value;
const qualifierEffect = this.createEffectQualifier(this.effectType, value);
this.addQualifier(qualifierEffect);
return this;
}
/**
* @description Sets the color to make transparent.
* @param {string} color The HTML name of the color (red, green, etc.) or RGB hex code.
* @return {this}
*/
colorToReplace(color) {
this._actionModel.color = color;
return this.addQualifier(new Qualifier('co', new QualifierValue(prepareColor(color))));
}
static fromJson(actionModel) {
const { actionType, tolerance, color } = actionModel;
// We are using this() to allow inheriting classes to use super.fromJson.apply(this, [actionModel])
// This allows the inheriting classes to determine the class to be created
const result = new this(actionType, tolerance);
tolerance && result.tolerance(tolerance);
color && result.colorToReplace(color);
return result;
}
} |
JavaScript | class ComponentEvents {
constructor(eventHandler) {
this.componentEventsFromEventsMap = new ComponentEventsFromEventsMap(eventHandler);
}
get eventsClass() {
return this.componentEventsInterface || this.componentEventsFromEventsMap;
}
/**
* Collect state and create the API which will be part
* of the return object of the `svelte2tsx` function.
*/
createAPI() {
const entries = [];
const iterableEntries = this.eventsClass.events.entries();
for (const entry of iterableEntries) {
entries.push({ name: entry[0], ...entry[1] });
}
return {
getAll() {
return entries;
}
};
}
setComponentEventsInterface(node) {
this.componentEventsInterface = new ComponentEventsFromInterface(node);
}
hasInterface() {
return !!this.componentEventsInterface;
}
checkIfImportIsEventDispatcher(node) {
this.componentEventsFromEventsMap.checkIfImportIsEventDispatcher(node);
}
checkIfIsStringLiteralDeclaration(node) {
this.componentEventsFromEventsMap.checkIfIsStringLiteralDeclaration(node);
}
checkIfDeclarationInstantiatedEventDispatcher(node) {
this.componentEventsFromEventsMap.checkIfDeclarationInstantiatedEventDispatcher(node);
}
checkIfCallExpressionIsDispatch(node) {
this.componentEventsFromEventsMap.checkIfCallExpressionIsDispatch(node);
}
toDefString() {
return this.eventsClass.toDefString();
}
} |
JavaScript | class ImplicitStoreValues {
constructor(storesResolvedInTemplate = [], renderFunctionStart) {
this.renderFunctionStart = renderFunctionStart;
this.accessedStores = new Set();
this.variableDeclarations = [];
this.reactiveDeclarations = [];
this.importStatements = [];
this.addStoreAcess = this.accessedStores.add.bind(this.accessedStores);
this.addVariableDeclaration = this.variableDeclarations.push.bind(this.variableDeclarations);
this.addReactiveDeclaration = this.reactiveDeclarations.push.bind(this.reactiveDeclarations);
this.addImportStatement = this.importStatements.push.bind(this.importStatements);
storesResolvedInTemplate.forEach(this.addStoreAcess);
}
/**
* All variable declartaions and imports which
* were used as stores are appended with `let $xx = __sveltets_store_get(xx)` to create the store variables.
*/
modifyCode(astOffset, str) {
this.variableDeclarations.forEach((node) => this.attachStoreValueDeclarationToDecl(node, astOffset, str));
this.reactiveDeclarations.forEach((node) => this.attachStoreValueDeclarationToReactiveAssignment(node, astOffset, str));
this.attachStoreValueDeclarationOfImportsToRenderFn(str);
}
getAccessedStores() {
return [...this.accessedStores.keys()];
}
attachStoreValueDeclarationToDecl(node, astOffset, str) {
const storeNames = extractIdentifiers(node.name)
.map((id) => id.text)
.filter((name) => this.accessedStores.has(name));
if (!storeNames.length) {
return;
}
const storeDeclarations = surroundWithIgnoreComments(this.createStoreDeclarations(storeNames));
const nodeEnd = ts__default['default'].isVariableDeclarationList(node.parent) && node.parent.declarations.length > 1
? node.parent.declarations[node.parent.declarations.length - 1].getEnd()
: node.getEnd();
str.appendRight(nodeEnd + astOffset, storeDeclarations);
}
attachStoreValueDeclarationToReactiveAssignment(node, astOffset, str) {
const storeNames = getNamesFromLabeledStatement(node).filter((name) => this.accessedStores.has(name));
if (!storeNames.length) {
return;
}
const storeDeclarations = surroundWithIgnoreComments(this.createStoreDeclarations(storeNames));
const endPos = node.getEnd() + astOffset;
str.appendRight(endPos, storeDeclarations);
}
attachStoreValueDeclarationOfImportsToRenderFn(str) {
const storeNames = this.importStatements
.filter(({ name }) => name && this.accessedStores.has(name.getText()))
.map(({ name }) => name.getText());
if (!storeNames.length) {
return;
}
const storeDeclarations = surroundWithIgnoreComments(this.createStoreDeclarations(storeNames));
str.appendRight(this.renderFunctionStart, storeDeclarations);
}
createStoreDeclarations(storeNames) {
let declarations = '';
for (let i = 0; i < storeNames.length; i++) {
declarations += this.createStoreDeclaration(storeNames[i]);
}
return declarations;
}
createStoreDeclaration(storeName) {
return `;let $${storeName} = __sveltets_store_get(${storeName});`;
}
} |
JavaScript | class SelectAutocomplete extends BaseComponent {
constructor(element, config) {
super(element)
this._config = config
this._enhance()
}
// Getters
static get NAME() {
return NAME
}
// Public
// Private
_enhance() {
accessibleAutocomplete.enhanceSelectElement(Object.assign({}, { selectElement: this._element }, this._config))
}
} |
JavaScript | class BaseVariable {
constructor(vs, children) {
this.vs = vs;
this.children = children || emptySet;
this.parentCount = 0; // we use this for non-recursive topological sort
this.forwardCode = null;
this.backwardCode = null;
this.id = vs.allocateSpace();
this.name = vs.getVariableNameForId(this.id);
this.gradName = vs.getGradientNameForId(this.id);
}
forward() {
this.vs.forward();
}
backward() {
this.vs.backward();
}
compile() {
if (this.vs.isCompiled()) return;
this.vs.compile(this);
}
setBackwardCode(code) {
this.backwardCode = code;
}
setForwardCode(code) {
this.forwardCode = code;
}
getDot(options) {
return getDot(this, options);
}
} |
JavaScript | class DecimalChantaStorer extends AbstractStorer {
#ammount;
/**
* constructor
*
* @param {Mixed} rawAmmount The value to be stored as a DecimalChanta value
*/
constructor(rawAmmount) {
super();
this.#ammount = new DecimalChanta(rawAmmount);
}
get ammount() {
return this.#ammount;
}
/**
* add
*
* Punto de acceso al método add del componente responsable de almacenar el valor
*
* @param {*} value
* @returns
*/
add(value) {
return this.#ammount.add(value);
}
/**
* substract
*
* Punto de acceso al método substract del componente responsable de almacenar el valor
*
* @param {*} value
* @returns
*/
substract(value) {
return this.#ammount.substract(value);
}
/**
* add
*
* Punto de acceso al método multiply del componente responsable de almacenar el valor
*
* @param {*} value
* @returns
*/
multiply(value) {
return this.#ammount.multiply(value);
}
/**
* add
*
* Punto de acceso al método divide del componente responsable de almacenar el valor
*
* @param {*} value
* @returns
*/
divide() {
return this.#ammount.divide(value);
}
toString() {
return this.ammount.toString();
}
} |
JavaScript | class Filter {
/**
* Changes raw nested filters to form Object<path, value>.
*
* @example
* const filters = {
* nested: {field: 'ala'},
* 'dataField~~from': '2019-08-14'
* }
*
* const normalized = Filter.normalizeFilters(filters)
* // {
* // 'nested.filter': 'ala',
* // 'dataField': {from: '2019-08-14'}
* // }
*
*
* @param {Object} filters
*
* @return {Object}
*/
static normalizeKeys(filters) {
return flat.unflatten(flat.flatten(filters), {
delimiter: PARAM_SEPARATOR
});
}
/**
* @param {Object<String,Object | String>} filters selected filters
* @param {BaseResource} resource resource which is filtered
*/
constructor(filters = {}, resource) {
this.resource = resource;
const normalized = Filter.normalizeKeys(filters);
this.filters = Object.keys(normalized).reduce((memo, path) => _objectSpread({
[path]: {
path,
property: this.resource.property(path),
value: normalized[path]
}
}, memo), {});
}
/**
* Returns filter for a given property key
*
* @param {String} key property key
* @returns {Filter.Property | undefined}
*/
get(key) {
return this.filters[key];
}
/**
* Populates all filtered properties which refers to other resources
*/
async populate() {
const keys = Object.keys(this.filters);
for (let index = 0; index < keys.length; index += 1) {
var _this$resource$decora;
const key = keys[index];
const referenceResource = (_this$resource$decora = this.resource.decorate().getPropertyByKey(key)) === null || _this$resource$decora === void 0 ? void 0 : _this$resource$decora.reference();
if (referenceResource) {
this.filters[key].populated = await referenceResource.findOne(this.filters[key].value);
}
}
return this;
}
reduce(callback, initial) {
return Object.values(this.filters).reduce(callback, initial || {});
}
isVisible() {
return !!Object.keys(this.filters).length;
}
} |
JavaScript | class QuoteCurrencyByIdCache extends BaseKitSaasMultiCacheManagement {
/**
* Constructor for quote currency by id cache.
*
* @param {object} params: cache key generation & expiry related params
* @param {array<string/number>} params.quoteCurrencyIds
*
* @augments BaseKitSaasMultiCacheManagement
*
* @constructor
*/
constructor(params) {
super();
const oThis = this;
oThis.quoteCurrencyIds = params.quoteCurrencyIds;
oThis.cacheType = cacheManagementConst.inMemory;
// Call sub class method to set cache level.
oThis._setCacheLevel();
// Call sub class method to set cache keys using params provided.
oThis._setCacheKeys();
// Call sub class method to set inverted cache keys using params provided.
oThis._setInvertedCacheKeys();
// Call sub class method to set cache expiry using params provided.
oThis._setCacheExpiry();
// Call sub class method to set cache implementer using params provided.
oThis._setCacheImplementer();
}
/**
* Set cache level.
*
* @sets oThis.cacheLevel
*
* @private
*/
_setCacheLevel() {
const oThis = this;
oThis.cacheLevel = cacheManagementConst.kitSaasSubEnvLevel;
}
/**
* Set cache keys.
*
* @sets oThis.saasCacheKeys
* @sets oThis.kitCacheKeys
*
* @private
*/
_setCacheKeys() {
const oThis = this;
// It uses shared cache key between company api and saas. Any changes in key here should be synced.
for (let index = 0; index < oThis.quoteCurrencyIds.length; index++) {
oThis.saasCacheKeys[oThis._saasCacheKeyPrefix() + 'c_qt_cur_' + oThis.quoteCurrencyIds[index]] =
oThis.quoteCurrencyIds[index];
oThis.kitCacheKeys[oThis._kitCacheKeyPrefix() + 'c_qt_cur_' + oThis.quoteCurrencyIds[index]] =
oThis.quoteCurrencyIds[index];
}
}
/**
* Set cache expiry.
*
* @sets oThis.cacheExpiry
*
* @private
*/
_setCacheExpiry() {
const oThis = this;
oThis.cacheExpiry = 10 * 24 * 60 * 60; // 10 days
}
/**
* Fetch data from source.
*
* @param {array<string/number>} quoteCurrencyIds
*
* @returns {Promise<*>}
* @private
*/
_fetchDataFromSource(quoteCurrencyIds) {
return new QuoteCurrencyModel().fetchQuoteCurrencyByIds(quoteCurrencyIds);
}
} |
JavaScript | class TestCase {
constructor(t, result) {
this._t = t;
this._result = result;
this._not = false;
}
toBe(value) {
if (this._not) {
this._t.notEquals(this._result, value);
} else {
this._t.equals(this._result, value);
}
}
toEqual(value) {
if (this._not) {
tapeNotEquals(this._t, this._result, value);
} else {
tapeEquals(this._t, this._result, value);
}
}
toEqualEpsilon(value, epsilon) {
tapeEqualsEpsilon(this._t, this._result, value, epsilon);
}
toThrow() {
this._t.throws(() => this._result());
}
get not() {
this._not = !this._not;
return this;
}
} |
JavaScript | class InteractionType {
constructor( interaction ){
if( !interaction ){
throw error(`Can not create interaction type without an 'interaction' reference`);
}
this.interaction = interaction;
}
static allowedParticipantTypes(){
return allowedParticipantTypes();
}
allowedParticipantTypes(){
return allowedParticipantTypes();
}
has( pptType ){
return this.interaction.participantsOfType(pptType).length > 0;
}
isPositive(){
return this.has( PARTICIPANT_TYPE.POSITIVE );
}
isNegative(){
return this.has( PARTICIPANT_TYPE.NEGATIVE );
}
isSigned(){
return this.isPositive() || this.isNegative();
}
getSign() {
let T = PARTICIPANT_TYPE;
if( this.isNegative() ){
return T.NEGATIVE;
} else if ( this.isPositive() ){
return T.POSITIVE;
} else {
return T.UNSIGNED;
}
}
isComplete(){
return false;
}
setParticipantAs( ppt, type ){
let intn = this.interaction;
let signedPpts = intn.participantsNotOfType( PARTICIPANT_TYPE.UNSIGNED ).filter( unsignedPpt => unsignedPpt.id() !== ppt.id() );
let makeUnsigned = ppt => intn.retypeParticipant( ppt, PARTICIPANT_TYPE.UNSIGNED );
return Promise.all([
intn.retypeParticipant( ppt, type ),
signedPpts.map( makeUnsigned )
]);
}
getTarget(){
let intn = this.interaction;
let ppts = intn.participantsNotOfType( PARTICIPANT_TYPE.UNSIGNED );
// assoc. cannot have more than one target,
// but this must be checked somewhere else (no need to throw an exception here)
return( ppts.length > 1 ) ? null : ppts[0];
}
setTarget( ppt ){
if( this.isNegative() ){
return this.setParticipantAs( ppt, PARTICIPANT_TYPE.NEGATIVE );
} else if( this.isPositive() ){
return this.setParticipantAs( ppt, PARTICIPANT_TYPE.POSITIVE );
} else {
throw new Error(`Can not set target of unsigned/undirected interaction`);
}
}
getSource(){
let intn = this.interaction;
let ppts = intn.participantsOfType( PARTICIPANT_TYPE.UNSIGNED );
// assoc. cannot have more than one source,
// but this must be checked somewhere else (no need to throw an exception here)
return ( ppts.length > 1 ) ? null : ppts[0];
}
toBiopaxTemplate() {
throw new Error(`Abstract method toBiopaxTemplate() is not overridden for interaction type of ${this.value}`);
}
toSearchTemplate() {
let source = this.getSource();
let target = this.getTarget();
let ppts;
// if directed list the participants in order
if ( source && target ) {
ppts = [ source, target ];
}
else {
ppts = this.interaction.participants();
}
let id = this.interaction.id();
// For entities id field represents the id of association which is different then
// element id. Therefore, we have the elId field as well which has the same value with
// the id field for the interactions.
let elId = id;
let pptTemplates = ppts.map( p => p.toSearchTemplate() );
// if there is some participants with invalid template skip the interaction
if ( _.includes( ppts, null ) ) {
return null;
}
return { id, ppts: pptTemplates, elId };
}
toString(verbPhrase, post = ''){
let src, tgt;
// covers cases: positive, negative, unsigned-target
src = this.getSource();
tgt = this.getTarget();
if( !src || !tgt ){
if( this.isSigned() ){
throw new Error(`Source or target is undefined for signed interaction type ${this.value}`);
}
// fall back on unordered list
[src, tgt] = this.interaction.participants();
}
if( !verbPhrase ){
verbPhrase = this.getSign().verbPhrase;
}
let srcName = src.name() || '(?)';
let tgtName = tgt.name() || '(?)';
return _.compact([srcName, verbPhrase, tgtName, post]).join(' ');
}
validatePpts( transform = _.identity ){
let intn = this.interaction;
let pptAssocsAllowed = () => this.constructor.isAllowedForInteraction(intn, transform);
let pptTypeAllowed = () => {
// transform function should not be called here since we need the sign of original participants
let pptType = (
intn.participants()
.map(ppt => intn.participantType(ppt))
.filter(type => type.value !== PARTICIPANT_TYPE.UNSIGNED.value)[0] // assume one typed ppt, others unsigned
|| PARTICIPANT_TYPE.UNSIGNED // if no other type found, then it's unsigned overall
);
return this.allowedParticipantTypes().some(type => type.value === pptType.value);
};
return pptAssocsAllowed() && pptTypeAllowed();
}
makeInvalidBiopaxTemplate( transform, omitDbXref ){
let participants = this.interaction.participants();
participants = _.uniqBy( participants.map( transform ), p => p.id() );
let participantTemplates = participants.map( participant => participant.toBiopaxTemplate( omitDbXref ) );
return {
type: BIOPAX_TEMPLATE_TYPE.OTHER_INTERACTION,
participants: participantTemplates
};
}
static isAllowedForInteraction( intn ){ // eslint-disable-line no-unused-vars
return false;
}
static get value(){ return VALUE; }
get value(){ return VALUE; }
static get displayValue(){ return DISPLAY_VALUE; }
get displayValue(){ return DISPLAY_VALUE; }
} |
JavaScript | class User {
constructor(username, fullname, email, permissions, password) {
const key = new auth.ApiKey();
this.username = username;
this.apikey = key.key;
this.apikeys = [key];
this.id = auth.uniqueId();
this.fullname = fullname;
this.permissions = permissions;
this.email = email;
this.hash = bcrypt.hashSync(password, config.auth.saltRounds);
this.emailVerified = false;
if (config.server.emailVerification) {
this.deactivated = true;
mail.sendVerification(this);
} else {
this.deactivated = false;
}
const userFile = new userModel({
username: this.username,
apikeys: this.apikeys,
id: this.id,
fullname: this.fullname,
permissions: this.permissions,
email: this.email,
hash: this.hash,
deactivated: this.deactivated,
emailVerified: this.emailVerified
});
userFile.save();
}
} |
JavaScript | class AddForm extends Component {
constructor(props) {
super(props);
this.addElement = this.addElement.bind(this);
this.removeElement = this.removeElement.bind(this);
this.resetElements = this.resetElements.bind(this);
this.handleChange = this.handleChange.bind(this);
this.submit = this.submit.bind(this);
this.state = {
formElements: [],
formDetails: {
id: "",
version: "",
title: "",
fields: [],
},
};
}
componentDidMount() {
// $(".sortable").sortable();
// (function () {
// let el = document.getElementById("items");
// Sortable.create(el, { animation: 300 });
// })("docReady", window);
(function () {
let el = document.getElementById("items");
Sortable.create(el, { animation: 300 });
})();
if (this.props.formId) {
let addFormItem = document.getElementById("active");
if (addFormItem) {
addFormItem.classList.add("active");
}
FormService.find(this.props.formId).then(
(response) => {
if (response.statusInfo.statusCode === APP.CODE.SUCCESS) {
this.setState({
formDetails: response.responseData,
});
document.getElementById("id").value = response.responseData.id;
document.getElementById("version").value =
response.responseData.version;
if (response.responseData.fields) {
response.responseData.fields.map((element) => {
switch (element.fieldType) {
case LANG.SEPARATOR:
return this.addElement(LANG.SEPARATOR);
case LANG.HEADING:
return this.addElement(LANG.HEADING);
default:
return this.addElement(LANG.FIELD);
}
});
}
} else {
Notify.error(response.statusInfo.errorMessage);
}
},
(error) => {
error.statusInfo
? Notify.error(error.statusInfo.errorMessage)
: Notify.error(error.message);
}
);
} else {
this.props.eraseFormDetails();
}
}
handleChange = (event) => {
event.persist();
this.setState((prevState) => ({
...prevState,
formDetails: {
...prevState.formDetails,
[event.target.name]: event.target.value,
},
}));
let formName = document.getElementById("form-name");
if (event.target.name === "title" && formName) {
formName.innerHTML = event.target.value;
}
};
addElement = (element) => {
this.state.formElements.push(element);
this.setState({
formElements: this.state.formElements,
});
};
removeElement = (index) => {
// console.log(this.state.formElements)
confirmAlert({
title: LANG.CONFIRM_TO_REMOVE,
message: LANG.ARE_YOU_SURE_YOU_WANT_TO_DO_THIS,
buttons: [
{
label: LANG.REMOVE,
onClick: () => {
delete this.state.formElements[index];
this.setState({
formElements: this.state.formElements,
});
},
},
{
label: LANG.CANCEL,
onClick: () => {
return false;
},
},
],
});
};
resetElements = () => {
this.setState({
formElements: [],
formDetails: {},
});
};
submit = () => {
let formData = {};
formData.id = this.state.formDetails.id;
formData.version = this.state.formDetails.version;
formData.title = this.state.formDetails.title;
formData.fields = [];
let cards = document.getElementsByClassName("card");
for (let i = 0; i < cards.length; i++) {
let field = {};
field.refApi = "";
field.logicalGroupCode = "";
field.name = cards[i].querySelector(".fieldName").value;
field.fieldType = cards[i].querySelector(".fieldType").value;
field.values = [];
if (
field.fieldType !== LANG.HEADING ||
field.fieldType !== LANG.SEPARATOR
) {
let tags = cards[i].querySelectorAll(".input-tag__tags li");
for (let j = 0; j < tags.length; j++) {
if (j + 1 < tags.length) {
let tag = tags[j].innerHTML.split("<");
if (tag[0]) {
let option = {};
option.key = tag[0];
option.value = tag[0];
field.values.push(option);
}
}
}
let width = cards[i].querySelector(".width");
if (width) {
field.width = parseInt(width.value);
} else {
field.width = null;
}
let isRequired = cards[i].querySelector(".isRequired");
if (isRequired) {
field.isRequired = cards[i].querySelector(".isRequired").checked;
} else {
field.isRequired = false;
}
}
field.order = i + 1;
if (field.fieldType === LANG.HEADING) {
field.values = [];
let heading = {};
heading.heading = cards[i].querySelector(".heading").value;
heading.subHeading = cards[i].querySelector(".subHeading").value;
field.values.push(heading);
}
formData.fields.push(field);
}
FormService.add(formData).then(
(response) => {
if (response.statusInfo.statusCode === APP.CODE.SUCCESS) {
Notify.success(response.statusInfo.statusMessage);
this.props.updateParent(response.responseData.id);
this.props.history.push(
"/forms/" + response.responseData.id + "/details"
);
} else {
Notify.error(response.statusInfo.errorMessage);
}
},
(error) => {
error.statusInfo
? Notify.error(error.statusInfo.errorMessage)
: Notify.error(error.message);
}
);
console.log(formData);
};
render() {
return (
<form autoComplete="new-password">
<div className="row col-md-12 pt-4">
<div className="col-md-9">
<button
onClick={this.submit}
type="button"
id="submit"
className="btn col-md-2 reportBtn submitBtn action-btn"
>
Save Form
</button>
</div>
<div className="col-md-3 text-center mt-2 pointer">
<i className="fa fa-trash fa-2x"></i> Delete form
</div>
</div>
<div style={{ visibility: "hidden" }}>
<input
type="text"
name="id"
id="id"
value={this.state.formDetails.id || ""}
onChange={this.handleChange}
/>
<input
type="text"
name="version"
id="version"
value={this.state.formDetails.version || ""}
onChange={this.handleChange}
/>
</div>
<div className="row col-md-12 pt-4">
<div className="col-md-4">
<div className="form-group">
<label htmlFor="field-name">Form Title</label>
<input
type="text"
id="title"
name="title"
className="form-control"
placeholder="Type here"
onChange={this.handleChange}
onBlur={this.handleChange}
value={this.state.formDetails.title || ""}
autoComplete="off"
/>
</div>
</div>
</div>
<div className="card-columns row col-md-12 mt-4">
<div className="col-md-12">
<div className="sortable" id="items">
{this.state.formElements &&
this.state.formElements.map((element, index) => {
switch (element) {
case LANG.FIELD:
return (
<Field
key={index}
index={index}
data={
this.state.formDetails.fields
? this.state.formDetails.fields[index]
: null
}
removeElement={this.removeElement}
/>
);
case LANG.SEPARATOR:
return (
<Separator
key={index}
index={index}
data={
this.state.formDetails.fields
? this.state.formDetails.fields[index]
: null
}
removeElement={this.removeElement}
/>
);
case LANG.HEADING:
return (
<Heading
key={index}
index={index}
data={
this.state.formDetails.fields
? this.state.formDetails.fields[index]
: null
}
removeElement={this.removeElement}
/>
);
default:
return <></>;
}
})}
</div>
</div>
</div>
<div className="row col-md-12 mt-4 mb-4 field-options">
<div onClick={() => this.addElement(LANG.FIELD)} className="pointer">
<span className="text-icons">
<i className="fa fa-plus"></i>
</span>
New field
</div>
<div
onClick={() => this.addElement(LANG.SEPARATOR)}
className="pointer"
>
<span className="text-icons">{"="}</span> Add separator
</div>
<div
onClick={() => this.addElement(LANG.HEADING)}
className="pointer"
>
<span className="text-icons">T</span> Add section handling
</div>
</div>
</form>
);
}
} |
JavaScript | class AdapterBase {
constructor (port, host, publicPaths) {
this.port = port;
this.host = host;
this.publicPaths = publicPaths;
this.idleTimeout = 55;
this.socketHandler = new HandlerMap(["channel", "callback", "scope"]);
this.xhrHandler = new HandlerMap(["method", "path", "callback", "scope"]);
this.activeSockets = [];
}
/**
* Generates a new uuid and ensures with the lookup array that there are no colissions.
* @param {string[]} [lookup] The list of generated uuids
* @returns {string} a new unique uuid
*/
_uuid (lookup = []) {
let id = crypto.randomUUID();
while (lookup.includes(id)) {
id = crypto.randomUUID();
}
lookup.push(id);
return id;
}
/**
* Registers a handler to a specific channel
* @param {string} channel
* @param {socketCallback} socketCallback
* @param {object} scope
*/
registerSocketHandler (channel, socketCallback, scope) {
this.socketHandler.set(channel, socketCallback, scope);
}
/**
* Unregisters a handler to a specific channel
* @param {string} channel
* @param {socketCallback} socketCallback
* @param {object} scope
*/
unregisterSocketHandler (channel, socketCallback, scope) {
this.socketHandler.delete(channel, socketCallback, scope);
}
/**
* Registers a handler to a specific XMLHttpRequest
* @param {string} method The method of the XMLHttpRequest
* @param {string} path The path gets matched with startsWith
* @param {xhrCallback} xhrCallback
* @param {object} scope
*/
registerXhrHandler (method, path, xhrCallback, scope) {
this.xhrHandler.set(method, path, xhrCallback, scope);
}
/**
* Unregisters a handler to a specific XMLHttpRequest
* @param {string} method The method of the XMLHttpRequest
* @param {string} path The path gets matched with startsWith
* @param {xhrCallback} xhrCallback
* @param {object} [scope]
*/
unregisterXhrHandler (method, path, xhrCallback, scope) {
this.xhrHandler.delete(method, path, xhrCallback, scope);
}
/**
* Handles socket 'open' event.
* Creates a uuid for this WebSocket and sends a message to the
* WebSocket via the channel 'socketId' with the uuid.
* This uuid might be reused by another WebSocket connection after
* the current one was closed.
* @param {WebSocket} ws
* @returns {string} The uuid of the WebSocket
*/
handleSocketOpen (ws) {
ws.id = this._uuid(this.activeSockets);
this.send(ws, "socketId", {
id: ws.id,
});
return ws.id;
}
/**
* Handles socket 'close' event.
* Depending on the scenario the WebSocket object might be already undefined.
* Therefore this method might also recieve an object containing the property 'id'.
* In addition a fake close message is send to allow server side handlers react upon the close.
* The uuid might now be reused by another WebSocket connection.
* @param {object} ws An object with at least the property id
*/
handleSocketClose (ws) {
this.handleSocketMessage(ws, {
channel: "close",
data: {},
});
this.activeSockets.splice(this.activeSockets.indexOf(ws.id), 1);
}
/**
* Handles socket 'message' event.
* Parses the message and calls callbacks matching the channel
* @param {WebSocket} ws
* @param {string|Buffer} data
*/
handleSocketMessage (ws, data) {
const message = this.parseSocketMessage(data);
this.socketHandler.forEach((channel, socketCallback, scope) => {
if (!message || typeof message !== "object" || message.channel !== channel) {
return;
}
try {
if (scope) {
socketCallback.call(scope, ws, message.data, ws.id);
} else {
socketCallback(ws, message.data, ws.id);
}
} catch (err) {
error(err);
}
});
}
/**
* Handles xhr 'request' event.
* Fetches the token from the header and calls callbacks matching the method and path.
* If no callback was executed or all failed the next callback is called.
* @param {Express.Request} req
* @param {Express.Response} res
* @param {function} next A callback which skips this filter
* @returns {Promise<void>} Resolves after all callbacks were executed
*/
async handleXhr (req, res, next) {
const token = req.get("Authorization") || null;
const handlerPromises = this.xhrHandler.map(async (method, path, xhrCallback, scope) => {
if (req.method !== method.toUpperCase()) {
return;
}
if (!req.path.startsWith(path)) {
return;
}
try {
if (scope) {
await xhrCallback.call(scope, req, res, token);
} else {
await xhrCallback(req, res, token);
}
return true;
} catch (err) {
error(err);
}
});
if (handlerPromises.length === 0) {
next();
return;
}
const results = await Promise.allSettled(handlerPromises);
const requestWasHandled = results.every((res) => {
return !res;
});
if (!requestWasHandled) {
next();
}
}
/**
* Parses the data to an object.
* @param {string|Buffer} data The data recieved by the socket 'message' event
* @returns {object} The parsed data
*/
parseSocketMessage (data) {
// need to be implemented by adapter
}
/**
* Sends a message to a specific WebSocket
* @param {WebSocket} ws
* @param {string} channel
* @param {Object} data
*/
send (ws, channel, data) {
// need to be implemented by adapter
}
/**
* Publishes a message to all websockets subscribed to a message
* @param {string} topic
* @param {string} channel
* @param {object} data
*/
publish (topic, channel, data) {
// need to be implemented by adapter
}
/**
* Subscribes a WebSocket to a topic
* @param {WebSocket} ws
* @param {string} topic
*/
subscribe (ws, topic) {
// need to be implemented by adapter
}
/**
* Unsubscribes a WebSocket to a topic
* @param {WebSocket} ws
* @param {string} topic
*/
unsubscribe (ws, topic) {
// need to be implemented by adapter
}
/**
* Starts the server and binds to the WebSocket and xhr events
*/
startServer () {
// need to be implemented by adapter
}
} |
JavaScript | class PluginManager
{
/**
* Instantiates PluginManager
*
* @param {object} [options] - Provides various configuration options:
*
* @param {TyphonEvents} [options.eventbus] - An instance of 'backbone-esnext-events' used as the plugin eventbus.
*
* @param {string} [options.eventPrepend='plugin'] - A customized name to prepend PluginManager events on the
* eventbus.
*
* @param {boolean} [options.throwNoMethod=false] - If true then when a method fails to be invoked by any plugin
* an exception will be thrown.
*
* @param {boolean} [options.throwNoPlugin=false] - If true then when no plugin is matched to be invoked an
* exception will be thrown.
*
*
* @param {object} [extraEventData] - Provides additional optional data to attach to PluginEvent callbacks.
*/
constructor(options = {}, extraEventData = void 0)
{
if (typeof options !== 'object') { throw new TypeError(`'options' is not an object.`); }
/**
* Stores the plugins by name with an associated PluginEntry.
* @type {Map<string, PluginEntry>}
* @private
*/
this._pluginMap = new Map();
/**
* Stores any associated eventbus.
* @type {TyphonEvents}
* @private
*/
this._eventbus = null;
/**
* Stores any extra options / data to add to PluginEvent callbacks.
* @type {Object}
* @private
*/
this._extraEventData = extraEventData;
/**
* Defines options for throwing exceptions. Turned off by default.
* @type {PluginManagerOptions}
* @private
*/
this._options =
{
pluginsEnabled: true,
noEventAdd: false,
noEventDestroy: false,
noEventOptions: true,
noEventRemoval: false,
throwNoMethod: false,
throwNoPlugin: false
};
if (typeof options.eventbus === 'object') { this.setEventbus(options.eventbus, options.eventPrepend); }
this.setOptions(options);
}
/**
* Adds a plugin by the given configuration parameters. A plugin `name` is always required. If no other options
* are provided then the `name` doubles as the NPM module / local file to load. The loading first checks for an
* existing `instance` to use as the plugin. Then the `target` is chosen as the NPM module / local file to load.
* By passing in `options` this will be stored and accessible to the plugin during all callbacks.
*
* @param {PluginConfig} pluginConfig - Defines the plugin to load.
*
* @param {object} [moduleData] - Optional object hash to associate with plugin.
*
* @returns {PluginData|undefined}
*/
add(pluginConfig, moduleData)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof pluginConfig !== 'object') { throw new TypeError(`'pluginConfig' is not an 'object'.`); }
if (typeof pluginConfig.name !== 'string')
{
throw new TypeError(`'pluginConfig.name' is not a 'string' for entry: ${JSON.stringify(pluginConfig)}.`);
}
if (typeof pluginConfig.target !== 'undefined' && typeof pluginConfig.target !== 'string')
{
throw new TypeError(`'pluginConfig.target' is not a string for entry: ${JSON.stringify(pluginConfig)}.`);
}
if (typeof pluginConfig.options !== 'undefined' && typeof pluginConfig.options !== 'object')
{
throw new TypeError(`'pluginConfig.options' is not an 'object' for entry: ${JSON.stringify(pluginConfig)}.`);
}
if (typeof moduleData !== 'undefined' && typeof moduleData !== 'object')
{
throw new TypeError(`'moduleData' is not an 'object' for entry: ${JSON.stringify(pluginConfig)}.`);
}
// If a plugin with the same name already exists post a warning and exit early.
if (this._pluginMap.has(pluginConfig.name))
{
// Please note that a plugin or other logger must be setup on the associated eventbus.
if (this._eventbus !== null && typeof this._eventbus !== 'undefined')
{
this._eventbus.trigger('log:warn', `A plugin already exists with name: ${pluginConfig.name}.`);
}
return void 0;
}
let instance, target, type;
// Use an existing instance of a plugin; a static class is assumed when instance is a function.
if (typeof pluginConfig.instance === 'object' || typeof pluginConfig.instance === 'function')
{
instance = pluginConfig.instance;
target = pluginConfig.name;
type = 'instance';
}
else
{
// If a target is defined use it instead of the name.
target = pluginConfig.target || pluginConfig.name;
if (target.match(/^[.\/\\]/))
{
instance = require(path.resolve(target)); // eslint-disable global-require
type = 'require-path';
}
else
{
instance = require(target); // eslint-disable global-require
type = 'require-module';
}
}
// Create an object hash with data describing the plugin, manager, and any extra module data.
const pluginData = JSON.parse(JSON.stringify(
{
manager:
{
eventPrepend: this._eventPrepend
},
module: moduleData || {},
plugin:
{
name: pluginConfig.name,
scopedName: `${this._eventPrepend}:${pluginConfig.name}`,
target,
targetEscaped: PluginEntry.escape(target),
type,
options: pluginConfig.options || {}
}
}));
ObjectUtil.deepFreeze(pluginData, ['eventPrepend', 'scopedName']);
const eventProxy = this._eventbus !== null && typeof this._eventbus !== 'undefined' ?
new EventProxy(this._eventbus) : void 0;
const entry = new PluginEntry(pluginConfig.name, pluginData, instance, eventProxy);
this._pluginMap.set(pluginConfig.name, entry);
// Invoke private module method which allows skipping optional error checking.
s_INVOKE_SYNC_EVENTS('onPluginLoad', {}, {}, this._extraEventData, pluginConfig.name, this._pluginMap,
this._options, false);
// Invoke `typhonjs:plugin:manager:plugin:added` allowing external code to react to plugin addition.
if (this._eventbus)
{
this._eventbus.trigger(`typhonjs:plugin:manager:plugin:added`, pluginData);
}
return pluginData;
}
/**
* Adds a plugin by the given configuration parameters. A plugin `name` is always required. If no other options
* are provided then the `name` doubles as the NPM module / local file to load. The loading first checks for an
* existing `instance` to use as the plugin. Then the `target` is chosen as the NPM module / local file to load.
* By passing in `options` this will be stored and accessible to the plugin during all callbacks.
*
* @param {PluginConfig} pluginConfig - Defines the plugin to load.
*
* @param {object} [moduleData] - Optional object hash to associate with plugin.
*
* @returns {Promise<PluginData|undefined>}
*/
async addAsync(pluginConfig, moduleData)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof pluginConfig !== 'object') { throw new TypeError(`'pluginConfig' is not an 'object'.`); }
if (typeof pluginConfig.name !== 'string')
{
throw new TypeError(`'pluginConfig.name' is not a 'string' for entry: ${JSON.stringify(pluginConfig)}.`);
}
if (typeof pluginConfig.target !== 'undefined' && typeof pluginConfig.target !== 'string')
{
throw new TypeError(`'pluginConfig.target' is not a string for entry: ${JSON.stringify(pluginConfig)}.`);
}
if (typeof pluginConfig.options !== 'undefined' && typeof pluginConfig.options !== 'object')
{
throw new TypeError(`'pluginConfig.options' is not an 'object' for entry: ${JSON.stringify(pluginConfig)}.`);
}
if (typeof moduleData !== 'undefined' && typeof moduleData !== 'object')
{
throw new TypeError(`'moduleData' is not an 'object' for entry: ${JSON.stringify(pluginConfig)}.`);
}
// If a plugin with the same name already exists post a warning and exit early.
if (this._pluginMap.has(pluginConfig.name))
{
// Please note that a plugin or other logger must be setup on the associated eventbus.
if (this._eventbus !== null && typeof this._eventbus !== 'undefined')
{
this._eventbus.trigger('log:warn', `A plugin already exists with name: ${pluginConfig.name}.`);
}
return void 0;
}
let instance, target, type;
// Use an existing instance of a plugin; a static class is assumed when instance is a function.
if (typeof pluginConfig.instance === 'object' || typeof pluginConfig.instance === 'function')
{
instance = pluginConfig.instance;
target = pluginConfig.name;
type = 'instance';
}
else
{
// If a target is defined use it instead of the name.
target = pluginConfig.target || pluginConfig.name;
if (target.match(/^[.\/\\]/))
{
instance = require(path.resolve(target)); // eslint-disable global-require
type = 'require-path';
}
else
{
instance = require(target); // eslint-disable global-require
type = 'require-module';
}
}
// Create an object hash with data describing the plugin, manager, and any extra module data.
const pluginData = JSON.parse(JSON.stringify(
{
manager:
{
eventPrepend: this._eventPrepend
},
module: moduleData || {},
plugin:
{
name: pluginConfig.name,
scopedName: `${this._eventPrepend}:${pluginConfig.name}`,
target,
targetEscaped: PluginEntry.escape(target),
type,
options: pluginConfig.options || {}
}
}));
ObjectUtil.deepFreeze(pluginData, ['eventPrepend', 'scopedName']);
const eventProxy = this._eventbus !== null && typeof this._eventbus !== 'undefined' ?
new EventProxy(this._eventbus) : void 0;
const entry = new PluginEntry(pluginConfig.name, pluginData, instance, eventProxy);
this._pluginMap.set(pluginConfig.name, entry);
// Invoke private module method which allows skipping optional error checking.
await s_INVOKE_ASYNC_EVENTS('onPluginLoad', {}, {}, this._extraEventData, pluginConfig.name, this._pluginMap,
this._options, false);
// Invoke `typhonjs:plugin:manager:plugin:added` allowing external code to react to plugin addition.
if (this._eventbus)
{
await this._eventbus.triggerAsync(`typhonjs:plugin:manager:plugin:added`, pluginData);
}
return pluginData;
}
/**
* Initializes multiple plugins in a single call.
*
* @param {Array<PluginConfig>} pluginConfigs - An array of plugin config object hash entries.
*
* @param {object} [moduleData] - Optional object hash to associate with all plugins.
*
* @returns {Array<PluginData>}
*/
addAll(pluginConfigs = [], moduleData)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (!Array.isArray(pluginConfigs)) { throw new TypeError(`'plugins' is not an array.`); }
const pluginsData = [];
for (const pluginConfig of pluginConfigs)
{
const result = this.add(pluginConfig, moduleData);
if (result) { pluginsData.push(result); }
}
return pluginsData;
}
/**
* Initializes multiple plugins in a single call.
*
* @param {Array<PluginConfig>} pluginConfigs - An array of plugin config object hash entries.
*
* @param {object} [moduleData] - Optional object hash to associate with all plugins.
*
* @returns {Promise<Array<PluginData>>}
*/
addAllAsync(pluginConfigs = [], moduleData)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (!Array.isArray(pluginConfigs)) { throw new TypeError(`'plugins' is not an array.`); }
const pluginsData = [];
for (const pluginConfig of pluginConfigs)
{
const result = this.addAsync(pluginConfig, moduleData);
if (result) { pluginsData.push(result); }
}
return Promise.all(pluginsData);
}
/**
* Provides the eventbus callback which may prevent addition if optional `noEventAdd` is enabled. This disables
* the ability for plugins to be added via events preventing any external code adding plugins in this manner.
*
* @param {PluginConfig} pluginConfig - Defines the plugin to load.
*
* @param {object} [moduleData] - Optional object hash to associate with all plugins.
*
* @returns {PluginData|undefined} - Operation success.
* @private
*/
_addEventbus(pluginConfig, moduleData)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
return !this._options.noEventAdd ? this.add(pluginConfig, moduleData) : void 0;
}
/**
* Provides the eventbus callback which may prevent addition if optional `noEventAdd` is enabled. This disables
* the ability for plugins to be added via events preventing any external code adding plugins in this manner.
*
* @param {PluginConfig} pluginConfig - Defines the plugin to load.
*
* @param {object} [moduleData] - Optional object hash to associate with all plugins.
*
* @returns {Promise<PluginData|undefined>} - Operation success.
* @private
*/
_addEventbusAsync(pluginConfig, moduleData)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
return !this._options.noEventAdd ? this.addAsync(pluginConfig, moduleData) : Promise.resolve(void 0);
}
/**
* Provides the eventbus callback which may prevent addition if optional `noEventAdd` is enabled. This disables
* the ability for plugins to be added via events preventing any external code adding plugins in this manner.
*
* @param {Array<PluginConfig>} pluginConfigs - An array of plugin config object hash entries.
*
* @param {object} [moduleData] - Optional object hash to associate with all plugins.
*
* @returns {Array<PluginData>}
* @private
*/
_addAllEventbus(pluginConfigs, moduleData)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (!this._options.noEventAdd) { return this.addAll(pluginConfigs, moduleData); }
}
/**
* Provides the eventbus callback which may prevent addition if optional `noEventAdd` is enabled. This disables
* the ability for plugins to be added via events preventing any external code adding plugins in this manner.
*
* @param {Array<PluginConfig>} pluginConfigs - An array of plugin config object hash entries.
*
* @param {object} [moduleData] - Optional object hash to associate with all plugins.
*
* @returns {Promise<Array<PluginData>>}
* @private
*/
_addAllEventbusAsync(pluginConfigs, moduleData)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (!this._options.noEventAdd) { return this.addAllAsync(pluginConfigs, moduleData); }
}
/**
* If an eventbus is assigned to this plugin manager then a new EventProxy wrapping this eventbus is returned.
*
* @returns {EventProxy}
*/
createEventProxy()
{
return this._eventbus !== null ? new EventProxy(this._eventbus) : void 0;
}
/**
* Destroys all managed plugins after unloading them.
*/
destroy()
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
this.removeAll();
if (this._eventbus !== null && typeof this._eventbus !== 'undefined')
{
this._eventbus.off(`${this._eventPrepend}:add`, this._addEventbus, this);
this._eventbus.off(`${this._eventPrepend}:add:all`, this._addAllEventbus, this);
this._eventbus.off(`${this._eventPrepend}:async:add`, this._addEventbusAsync, this);
this._eventbus.off(`${this._eventPrepend}:async:add:all`, this._addAllEventbusAsync, this);
this._eventbus.off(`${this._eventPrepend}:async:destroy:manager`, this._destroyEventbusAsync, this);
this._eventbus.off(`${this._eventPrepend}:async:invoke`, this.invokeAsync, this);
this._eventbus.off(`${this._eventPrepend}:async:invoke:event`, this.invokeAsyncEvent, this);
this._eventbus.off(`${this._eventPrepend}:async:remove`, this._removeEventbusAsync, this);
this._eventbus.off(`${this._eventPrepend}:async:remove:all`, this._removeAllEventbusAsync, this);
this._eventbus.off(`${this._eventPrepend}:create:event:proxy`, this.createEventProxy, this);
this._eventbus.off(`${this._eventPrepend}:destroy:manager`, this._destroyEventbus, this);
this._eventbus.off(`${this._eventPrepend}:get:all:plugin:data`, this.getAllPluginData, this);
this._eventbus.off(`${this._eventPrepend}:get:extra:event:data`, this.getExtraEventData, this);
this._eventbus.off(`${this._eventPrepend}:get:method:names`, this.getMethodNames, this);
this._eventbus.off(`${this._eventPrepend}:get:options`, this.getOptions, this);
this._eventbus.off(`${this._eventPrepend}:get:plugin:enabled`, this.getPluginEnabled, this);
this._eventbus.off(`${this._eventPrepend}:get:plugin:data`, this.getPluginData, this);
this._eventbus.off(`${this._eventPrepend}:get:plugin:event:names`, this.getPluginEventNames, this);
this._eventbus.off(`${this._eventPrepend}:get:plugin:method:names`, this.getPluginMethodNames, this);
this._eventbus.off(`${this._eventPrepend}:get:plugin:names`, this.getPluginNames, this);
this._eventbus.off(`${this._eventPrepend}:get:plugin:options`, this.getPluginOptions, this);
this._eventbus.off(`${this._eventPrepend}:get:plugins:enabled`, this.getPluginsEnabled, this);
this._eventbus.off(`${this._eventPrepend}:get:plugins:by:event:name`, this.getPluginsByEventName, this);
this._eventbus.off(`${this._eventPrepend}:get:plugins:event:names`, this.getPluginsEventNames, this);
this._eventbus.off(`${this._eventPrepend}:has:method`, this.hasMethod, this);
this._eventbus.off(`${this._eventPrepend}:has:plugin`, this.hasPlugin, this);
this._eventbus.off(`${this._eventPrepend}:has:plugin:method`, this.hasPluginMethod, this);
this._eventbus.off(`${this._eventPrepend}:invoke`, this.invoke, this);
this._eventbus.off(`${this._eventPrepend}:is:valid:config`, this.isValidConfig, this);
this._eventbus.off(`${this._eventPrepend}:remove`, this._removeEventbus, this);
this._eventbus.off(`${this._eventPrepend}:remove:all`, this._removeAllEventbus, this);
this._eventbus.off(`${this._eventPrepend}:set:extra:event:data`, this.setExtraEventData, this);
this._eventbus.off(`${this._eventPrepend}:set:options`, this._setOptionsEventbus, this);
this._eventbus.off(`${this._eventPrepend}:set:plugin:enabled`, this.setPluginEnabled, this);
this._eventbus.off(`${this._eventPrepend}:set:plugins:enabled`, this.setPluginsEnabled, this);
this._eventbus.off(`${this._eventPrepend}:sync:invoke`, this.invokeSync, this);
this._eventbus.off(`${this._eventPrepend}:sync:invoke:event`, this.invokeSyncEvent, this);
}
this._pluginMap = null;
this._eventbus = null;
}
/**
* Destroys all managed plugins after unloading them.
*/
async destroyAsync()
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
await this.removeAll();
if (this._eventbus !== null && typeof this._eventbus !== 'undefined')
{
this._eventbus.off(`${this._eventPrepend}:add`, this._addEventbus, this);
this._eventbus.off(`${this._eventPrepend}:add:all`, this._addAllEventbus, this);
this._eventbus.off(`${this._eventPrepend}:async:add`, this._addEventbusAsync, this);
this._eventbus.off(`${this._eventPrepend}:async:add:all`, this._addAllEventbusAsync, this);
this._eventbus.off(`${this._eventPrepend}:async:destroy:manager`, this._destroyEventbusAsync, this);
this._eventbus.off(`${this._eventPrepend}:async:invoke`, this.invokeAsync, this);
this._eventbus.off(`${this._eventPrepend}:async:invoke:event`, this.invokeAsyncEvent, this);
this._eventbus.off(`${this._eventPrepend}:async:remove`, this._removeEventbusAsync, this);
this._eventbus.off(`${this._eventPrepend}:async:remove:all`, this._removeAllEventbusAsync, this);
this._eventbus.off(`${this._eventPrepend}:create:event:proxy`, this.createEventProxy, this);
this._eventbus.off(`${this._eventPrepend}:destroy:manager`, this._destroyEventbus, this);
this._eventbus.off(`${this._eventPrepend}:get:all:plugin:data`, this.getAllPluginData, this);
this._eventbus.off(`${this._eventPrepend}:get:extra:event:data`, this.getExtraEventData, this);
this._eventbus.off(`${this._eventPrepend}:get:method:names`, this.getMethodNames, this);
this._eventbus.off(`${this._eventPrepend}:get:options`, this.getOptions, this);
this._eventbus.off(`${this._eventPrepend}:get:plugin:enabled`, this.getPluginEnabled, this);
this._eventbus.off(`${this._eventPrepend}:get:plugin:data`, this.getPluginData, this);
this._eventbus.off(`${this._eventPrepend}:get:plugin:event:names`, this.getPluginEventNames, this);
this._eventbus.off(`${this._eventPrepend}:get:plugin:method:names`, this.getPluginMethodNames, this);
this._eventbus.off(`${this._eventPrepend}:get:plugin:names`, this.getPluginNames, this);
this._eventbus.off(`${this._eventPrepend}:get:plugin:options`, this.getPluginOptions, this);
this._eventbus.off(`${this._eventPrepend}:get:plugins:enabled`, this.getPluginsEnabled, this);
this._eventbus.off(`${this._eventPrepend}:get:plugins:by:event:name`, this.getPluginsByEventName, this);
this._eventbus.off(`${this._eventPrepend}:get:plugins:event:names`, this.getPluginsEventNames, this);
this._eventbus.off(`${this._eventPrepend}:has:method`, this.hasMethod, this);
this._eventbus.off(`${this._eventPrepend}:has:plugin`, this.hasPlugin, this);
this._eventbus.off(`${this._eventPrepend}:has:plugin:method`, this.hasPluginMethod, this);
this._eventbus.off(`${this._eventPrepend}:invoke`, this.invoke, this);
this._eventbus.off(`${this._eventPrepend}:is:valid:config`, this.isValidConfig, this);
this._eventbus.off(`${this._eventPrepend}:remove`, this._removeEventbus, this);
this._eventbus.off(`${this._eventPrepend}:remove:all`, this._removeAllEventbus, this);
this._eventbus.off(`${this._eventPrepend}:set:extra:event:data`, this.setExtraEventData, this);
this._eventbus.off(`${this._eventPrepend}:set:options`, this._setOptionsEventbus, this);
this._eventbus.off(`${this._eventPrepend}:set:plugin:enabled`, this.setPluginEnabled, this);
this._eventbus.off(`${this._eventPrepend}:set:plugins:enabled`, this.setPluginsEnabled, this);
this._eventbus.off(`${this._eventPrepend}:sync:invoke`, this.invokeSync, this);
this._eventbus.off(`${this._eventPrepend}:sync:invoke:event`, this.invokeSyncEvent, this);
}
this._pluginMap = null;
this._eventbus = null;
}
/**
* Provides the eventbus callback which may prevent plugin manager destruction if optional `noEventDestroy` is
* enabled. This disables the ability for the plugin manager to be destroyed via events preventing any external
* code removing plugins in this manner.
*
* @private
*/
_destroyEventbus()
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (!this._options.noEventDestroy) { this.destroy(); }
}
/**
* Provides the eventbus callback which may prevent plugin manager destruction if optional `noEventDestroy` is
* enabled. This disables the ability for the plugin manager to be destroyed via events preventing any external
* code removing plugins in this manner.
*
* @private
*/
async _destroyEventbusAsync()
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (!this._options.noEventDestroy) { await this.destroyAsync(); }
}
/**
* Returns the enabled state of a plugin.
*
* @param {string} pluginName - Plugin name to set state.
*
* @returns {boolean} - Operation success.
*/
getPluginEnabled(pluginName)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof pluginName !== 'string') { throw new TypeError(`'pluginName' is not a string.`); }
const entry = this._pluginMap.get(pluginName);
return entry instanceof PluginEntry && entry.enabled;
}
/**
* Returns the event binding names registered on any associated plugin EventProxy.
*
* @param {string} pluginName - Plugin name to set state.
*
* @returns {string[]} - Event binding names registered from the plugin.
*/
getPluginEventNames(pluginName)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof pluginName !== 'string') { throw new TypeError(`'pluginName' is not a string.`); }
const entry = this._pluginMap.get(pluginName);
return entry instanceof PluginEntry && entry._eventProxy ? entry._eventProxy.getEventNames() : [];
}
/**
* Returns the enabled state of a list of plugins.
*
* @param {Array<string>} pluginNames - An array / iterable of plugin names.
*
* @returns {Array<{pluginName: string, enabled: boolean}>} A list of objects with plugin name and enabled state.
*/
getPluginsEnabled(pluginNames)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
const results = [];
for (const pluginName of pluginNames)
{
results.push({ pluginName, enabled: this.getPluginEnabled(pluginName) });
}
return results;
}
/**
* Returns the event binding names registered from each plugin.
*
* @param {string|string[]} [nameOrList] - An array / iterable of plugin names.
*
* @returns {Array<{pluginName: string, events: string[]}>} A list of objects with plugin name and event binding
* names registered from the plugin.
*/
getPluginsEventNames(nameOrList)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof nameOrList === 'undefined') { nameOrList = this._pluginMap.keys(); }
if (typeof nameOrList === 'string') { nameOrList = [nameOrList]; }
const results = [];
for (const pluginName of nameOrList)
{
results.push({ pluginName, events: this.getPluginEventNames(pluginName) });
}
return results;
}
/**
* Returns the plugin names that registered the given event binding name.
*
* @param {string} eventName - An event name that plugins may have registered.
*
* @returns {Array<string[]>} A list of plugin names that has registered the given event name.
*/
getPluginsByEventName(eventName)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof eventName !== 'string') { throw new TypeError(`'eventName' is not a 'string'.`); }
const results = [];
const pluginEventNames = this.getPluginsEventNames();
for (const entry of pluginEventNames)
{
if (entry.events.indexOf(eventName) >= 0) { results.push(entry.pluginName); }
}
return results;
}
/**
* Returns all plugin data or if a boolean is passed in will return plugin data by current enabled state.
*
* @param {boolean|undefined} enabled - If enabled is a boolean it will return plugins given their enabled state.
*
* @returns {Array<PluginData>}
*/
getAllPluginData(enabled = void 0)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof enabled !== 'boolean' && typeof enabled !== 'undefined')
{
throw new TypeError(`'enabled' is not a 'boolean' or 'undefined'.`);
}
const results = [];
// Return all plugin data if enabled is not defined.
const allPlugins = typeof enabled === 'undefined';
for (const entry of this._pluginMap.values())
{
if (allPlugins || entry.enabled === enabled)
{
results.push(this.getPluginData(entry.name));
}
}
return results;
}
/**
* Returns any associated eventbus.
*
* @returns {TyphonEvents|null}
*/
getEventbus()
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
return this._eventbus;
}
/**
* Returns any extra event data associated with PluginEvents.
*
* @returns {*}
*/
getExtraEventData()
{
return this._extraEventData;
}
/**
* Returns all method names or if a boolean is passed in will return method names for plugins by current enabled
* state.
*
* @param {boolean|undefined} enabled - If enabled is a boolean it will return plugin methods names given their
* enabled state.
*
* @param {string|undefined} pluginName - If a string then just this plugins methods names are returned.
*
* @returns {Array<string>}
*/
getMethodNames(enabled = void 0, pluginName = void 0)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof enabled !== 'boolean' && typeof enabled !== 'undefined')
{
throw new TypeError(`'enabled' is not a 'boolean' or 'undefined'.`);
}
const results = {};
const allEnabled = typeof enabled === 'undefined';
const allNames = typeof pluginName === 'undefined';
for (const entry of this._pluginMap.values())
{
if (entry.instance && (allEnabled || entry.enabled === enabled) && (allNames || entry.name === pluginName))
{
for (const name of s_GET_ALL_PROPERTY_NAMES(entry.instance))
{
// Skip any names that are not a function or are the constructor.
if (entry.instance[name] instanceof Function && name !== 'constructor') { results[name] = true; }
}
}
}
return Object.keys(results);
}
/**
* Returns a copy of the plugin manager options.
*
* @returns {PluginManagerOptions}
*/
getOptions()
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
return JSON.parse(JSON.stringify(this._options));
}
/**
* Gets the plugin data for a plugin by name.
*
* @param {string} pluginName - A plugin name.
*
* @returns {PluginData|undefined}
*/
getPluginData(pluginName)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof pluginName !== 'string') { throw new TypeError(`'pluginName' is not a string.`); }
const entry = this._pluginMap.get(pluginName);
if (entry instanceof PluginEntry)
{
return JSON.parse(JSON.stringify(entry.data));
}
return void 0;
}
/**
* Returns all plugin names or if a boolean is passed in will return plugin names by current enabled state.
*
* @param {boolean|undefined} enabled - If enabled is a boolean it will return plugins given their enabled state.
*
* @returns {Array<{plugin: string, method: string}>}
*/
getPluginMethodNames(enabled = void 0)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof enabled !== 'boolean' && typeof enabled !== 'undefined')
{
throw new TypeError(`'enabled' is not a 'boolean' or 'undefined'.`);
}
const results = [];
const allPlugins = typeof enabled === 'undefined';
for (const entry of this._pluginMap.values())
{
if (entry.instance && (allPlugins || entry.enabled === enabled))
{
for (const name of s_GET_ALL_PROPERTY_NAMES(entry.instance))
{
// Skip any names that are not a function or are the constructor.
if (entry.instance[name] instanceof Function && name !== 'constructor')
{
results.push({ plugin: entry.name, method: name });
}
}
}
}
return results;
}
/**
* Returns all plugin names or if a boolean is passed in will return plugin names by current enabled state.
*
* @param {boolean|undefined} enabled - If enabled is a boolean it will return plugins given their enabled state.
*
* @returns {Array<string>}
*/
getPluginNames(enabled = void 0)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof enabled !== 'boolean' && typeof enabled !== 'undefined')
{
throw new TypeError(`'enabled' is not a 'boolean' or 'undefined'.`);
}
// Return all plugin names if enabled is not defined.
if (enabled === void 0) { return Array.from(this._pluginMap.keys()); }
const results = [];
for (const entry of this._pluginMap.values())
{
if (entry.enabled === enabled) { results.push(entry.name); }
}
return results;
}
/**
* Returns a copy of the given plugin options.
*
* @param {string} pluginName - Plugin name to retrieve.
*
* @returns {*}
*/
getPluginOptions(pluginName)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof pluginName !== 'string') { throw new TypeError(`'pluginName' is not a string.`); }
let result;
const entry = this._pluginMap.get(pluginName);
if (entry instanceof PluginEntry) { result = JSON.parse(JSON.stringify(entry.data.plugin.options)); }
return result;
}
/**
* Returns true if there is at least one plugin loaded with the given method name.
*
* @param {string} methodName - Method name to test.
*
* @returns {boolean} - True method is found.
*/
hasMethod(methodName)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof methodName !== 'string') { throw new TypeError(`'methodName' is not a string.`); }
for (const plugin of this._pluginMap.values())
{
if (typeof plugin.instance[methodName] === 'function') { return true; }
}
return false;
}
/**
* Returns true if there is a plugin loaded with the given plugin name.
*
* @param {string} pluginName - Plugin name to test.
*
* @returns {boolean} - True if a plugin exists.
*/
hasPlugin(pluginName)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof pluginName !== 'string') { throw new TypeError(`'pluginName' is not a string.`); }
return this._pluginMap.has(pluginName);
}
/**
* Returns true if there is a plugin loaded with the given plugin name that also has a method with the given
* method name.
*
* @param {string} pluginName - Plugin name to test.
* @param {string} methodName - Method name to test.
*
* @returns {boolean} - True if a plugin and method exists.
*/
hasPluginMethod(pluginName, methodName)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof pluginName !== 'string') { throw new TypeError(`'pluginName' is not a string.`); }
if (typeof methodName !== 'string') { throw new TypeError(`'methodName' is not a string.`); }
const plugin = this._pluginMap.get(pluginName);
return plugin instanceof PluginEntry && typeof plugin[methodName] === 'function';
}
/**
* This dispatch method simply invokes any plugin targets for the given methodName..
*
* @param {string} methodName - Method name to invoke.
*
* @param {*|Array<*>} [args] - Optional arguments. An array will be spread as multiple arguments.
*
* @param {string|Array<string>} [nameOrList] - An optional plugin name or array / iterable of plugin names to
* invoke.
*/
invoke(methodName, args = void 0, nameOrList = void 0)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof methodName !== 'string') { throw new TypeError(`'methodName' is not a string.`); }
if (typeof nameOrList === 'undefined') { nameOrList = this._pluginMap.keys(); }
if (typeof nameOrList !== 'string' && !Array.isArray(nameOrList) &&
typeof nameOrList[Symbol.iterator] !== 'function')
{
throw new TypeError(`'nameOrList' is not a string, array, or iterator.`);
}
// Track if a plugin method is invoked.
let hasMethod = false;
let hasPlugin = false;
// Early out if plugins are not enabled.
if (!this._options.pluginsEnabled) { return; }
if (typeof nameOrList === 'string')
{
const plugin = this._pluginMap.get(nameOrList);
if (plugin instanceof PluginEntry && plugin.enabled && plugin.instance)
{
hasPlugin = true;
if (typeof plugin.instance[methodName] === 'function')
{
Array.isArray(args) ? plugin.instance[methodName](...args) : plugin.instance[methodName](args);
hasMethod = true;
}
}
}
else
{
for (const name of nameOrList)
{
const plugin = this._pluginMap.get(name);
if (plugin instanceof PluginEntry && plugin.enabled && plugin.instance)
{
hasPlugin = true;
if (typeof plugin.instance[methodName] === 'function')
{
Array.isArray(args) ? plugin.instance[methodName](...args) : plugin.instance[methodName](args);
hasMethod = true;
}
}
}
}
if (this._options.throwNoPlugin && !hasPlugin)
{
throw new Error(`PluginManager failed to find any target plugins.`);
}
if (this._options.throwNoMethod && !hasMethod)
{
throw new Error(`PluginManager failed to invoke '${methodName}'.`);
}
}
/**
* This dispatch method uses ES6 Promises and adds any returned results to an array which is added to a Promise.all
* construction which passes back a Promise which waits until all Promises complete. Any target invoked may return a
* Promise or any result. This is very useful to use for any asynchronous operations.
*
* @param {string} methodName - Method name to invoke.
*
* @param {*|Array<*>} [args] - Optional arguments. An array will be spread as multiple arguments.
*
* @param {string|Array<string>} [nameOrList] - An optional plugin name or array / iterable of plugin names to
* invoke.
*
* @returns {Promise<*|Array<*>>}
*/
invokeAsync(methodName, args = void 0, nameOrList = void 0)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof methodName !== 'string') { throw new TypeError(`'methodName' is not a string.`); }
if (typeof nameOrList === 'undefined') { nameOrList = this._pluginMap.keys(); }
if (typeof nameOrList !== 'string' && !Array.isArray(nameOrList) &&
typeof nameOrList[Symbol.iterator] !== 'function')
{
throw new TypeError(`'nameOrList' is not a string, array, or iterator.`);
}
// Track if a plugin method is invoked.
let hasMethod = false;
let hasPlugin = false;
// Capture results.
let result = void 0;
const results = [];
// Early out if plugins are not enabled.
if (!this._options.pluginsEnabled) { return result; }
try
{
if (typeof nameOrList === 'string')
{
const plugin = this._pluginMap.get(nameOrList);
if (plugin instanceof PluginEntry && plugin.enabled && plugin.instance)
{
hasPlugin = true;
if (typeof plugin.instance[methodName] === 'function')
{
result = Array.isArray(args) ? plugin.instance[methodName](...args) :
plugin.instance[methodName](args);
// If we received a valid result return immediately.
if (result !== null || typeof result !== 'undefined') { results.push(result); }
hasMethod = true;
}
}
}
else
{
for (const name of nameOrList)
{
const plugin = this._pluginMap.get(name);
if (plugin instanceof PluginEntry && plugin.enabled && plugin.instance)
{
hasPlugin = true;
if (typeof plugin.instance[methodName] === 'function')
{
result = Array.isArray(args) ? plugin.instance[methodName](...args) :
plugin.instance[methodName](args);
// If we received a valid result return immediately.
if (result !== null || typeof result !== 'undefined') { results.push(result); }
hasMethod = true;
}
}
}
}
if (this._options.throwNoPlugin && !hasPlugin)
{
return Promise.reject(new Error(`PluginManager failed to find any target plugins.`));
}
if (this._options.throwNoMethod && !hasMethod)
{
return Promise.reject(new Error(`PluginManager failed to invoke '${methodName}'.`));
}
}
catch (error)
{
return Promise.reject(error);
}
// If there are multiple results then use Promise.all otherwise Promise.resolve.
return results.length > 1 ? Promise.all(results) : Promise.resolve(result);
}
/**
* This dispatch method synchronously passes to and returns from any invoked targets a PluginEvent.
*
* @param {string} methodName - Method name to invoke.
*
* @param {object} [copyProps={}] - plugin event object.
*
* @param {object} [passthruProps={}] - if true, event has plugin option.
*
* @param {string|Array<string>} [nameOrList] - An optional plugin name or array / iterable of plugin names to
* invoke.
*
* @returns {Promise<PluginEvent>}
*/
invokeAsyncEvent(methodName, copyProps = {}, passthruProps = {}, nameOrList = void 0)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof nameOrList === 'undefined') { nameOrList = this._pluginMap.keys(); }
// Early out if plugins are not enabled.
if (!this._options.pluginsEnabled) { return Promise.resolve(); }
// Invokes the private internal async events method with optional error checking enabled.
return s_INVOKE_ASYNC_EVENTS(methodName, copyProps, passthruProps, this._extraEventData, nameOrList,
this._pluginMap, this._options);
}
/**
* This dispatch method synchronously passes back a single value or an array with all results returned by any
* invoked targets.
*
* @param {string} methodName - Method name to invoke.
*
* @param {*|Array<*>} [args] - Optional arguments. An array will be spread as multiple arguments.
*
* @param {string|Array<string>} [nameOrList] - An optional plugin name or array / iterable of plugin names to
* invoke.
*
* @returns {*|Array<*>}
*/
invokeSync(methodName, args = void 0, nameOrList = void 0)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof methodName !== 'string') { throw new TypeError(`'methodName' is not a string.`); }
if (typeof nameOrList === 'undefined') { nameOrList = this._pluginMap.keys(); }
if (typeof nameOrList !== 'string' && !Array.isArray(nameOrList) &&
typeof nameOrList[Symbol.iterator] !== 'function')
{
throw new TypeError(`'nameOrList' is not a string, array, or iterator.`);
}
// Track if a plugin method is invoked.
let hasMethod = false;
let hasPlugin = false;
// Capture results.
let result = void 0;
const results = [];
// Early out if plugins are not enabled.
if (!this._options.pluginsEnabled) { return result; }
if (typeof nameOrList === 'string')
{
const plugin = this._pluginMap.get(nameOrList);
if (plugin instanceof PluginEntry && plugin.enabled && plugin.instance)
{
hasPlugin = true;
if (typeof plugin.instance[methodName] === 'function')
{
result = Array.isArray(args) ? plugin.instance[methodName](...args) : plugin.instance[methodName](args);
// If we received a valid result return immediately.
if (result !== null || typeof result !== 'undefined') { results.push(result); }
hasMethod = true;
}
}
}
else
{
for (const name of nameOrList)
{
const plugin = this._pluginMap.get(name);
if (plugin instanceof PluginEntry && plugin.enabled && plugin.instance)
{
hasPlugin = true;
if (typeof plugin.instance[methodName] === 'function')
{
result = Array.isArray(args) ? plugin.instance[methodName](...args) :
plugin.instance[methodName](args);
// If we received a valid result return immediately.
if (result !== null || typeof result !== 'undefined') { results.push(result); }
hasMethod = true;
}
}
}
}
if (this._options.throwNoPlugin && !hasPlugin)
{
throw new Error(`PluginManager failed to find any target plugins.`);
}
if (this._options.throwNoMethod && !hasMethod)
{
throw new Error(`PluginManager failed to invoke '${methodName}'.`);
}
// Return the results array if there are more than one or just a single result.
return results.length > 1 ? results : result;
}
/**
* This dispatch method synchronously passes to and returns from any invoked targets a PluginEvent.
*
* @param {string} methodName - Method name to invoke.
*
* @param {object} [copyProps={}] - plugin event object.
*
* @param {object} [passthruProps={}] - if true, event has plugin option.
*
* @param {string|Array<string>} [nameOrList] - An optional plugin name or array / iterable of plugin names to
* invoke.
*
* @returns {PluginEvent|undefined}
*/
invokeSyncEvent(methodName, copyProps = {}, passthruProps = {}, nameOrList = void 0)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof nameOrList === 'undefined') { nameOrList = this._pluginMap.keys(); }
// Early out if plugins are not enabled.
if (!this._options.pluginsEnabled) { return void 0; }
// Invokes the private internal sync events method with optional error checking enabled.
return s_INVOKE_SYNC_EVENTS(methodName, copyProps, passthruProps, this._extraEventData, nameOrList,
this._pluginMap, this._options);
}
/**
* Performs validation of a PluginConfig.
*
* @param {PluginConfig} pluginConfig - A PluginConfig to validate.
*
* @returns {boolean} True if the given PluginConfig is valid.
*/
isValidConfig(pluginConfig)
{
if (typeof pluginConfig !== 'object') { return false; }
if (typeof pluginConfig.name !== 'string') { return false; }
if (typeof pluginConfig.target !== 'undefined' && typeof pluginConfig.target !== 'string') { return false; }
if (typeof pluginConfig.options !== 'undefined' && typeof pluginConfig.options !== 'object') { return false; }
return true;
}
/**
* Sets the eventbus associated with this plugin manager. If any previous eventbus was associated all plugin manager
* events will be removed then added to the new eventbus. If there are any existing plugins being managed their
* events will be removed from the old eventbus and then `onPluginLoad` will be called with the new eventbus.
*
* @param {TyphonEvents} targetEventbus - The target eventbus to associate.
*
* @param {string} [eventPrepend='plugins'] - An optional string to prepend to all of the event binding
* targets.
*
* @returns {PluginManager}
*/
setEventbus(targetEventbus, eventPrepend = 'plugins')
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof targetEventbus !== 'object') { throw new TypeError(`'targetEventbus' is not an 'object'.`); }
if (typeof eventPrepend !== 'string') { throw new TypeError(`'eventPrepend' is not a 'string'.`); }
// Early escape if the targetEventbus is the same as the current eventbus.
if (targetEventbus === this._eventbus) { return this; }
const oldPrepend = this._eventPrepend;
/**
* Stores the prepend string for eventbus registration.
* @type {string}
* @private
*/
this._eventPrepend = eventPrepend;
// Unload and reload any existing plugins from the old eventbus to the target eventbus.
if (this._pluginMap.size > 0)
{
// Invoke private module method which allows skipping optional error checking.
s_INVOKE_SYNC_EVENTS('onPluginUnload', {}, {}, this._extraEventData, this._pluginMap.keys(),
this._pluginMap, this._options, false);
for (const entry of this._pluginMap.values())
{
// Automatically remove any potential reference to a stored event proxy instance.
try
{
entry.instance._eventbus = void 0;
}
catch (err) { /* nop */ }
entry.data.manager.eventPrepend = eventPrepend;
entry.data.plugin.scopedName = `${eventPrepend}:${entry.name}`;
if (entry.eventProxy instanceof EventProxy) { entry.eventProxy.destroy(); }
entry.eventProxy = new EventProxy(targetEventbus);
}
// Invoke private module method which allows skipping optional error checking.
s_INVOKE_SYNC_EVENTS('onPluginLoad', {}, {}, this._extraEventData, this._pluginMap.keys(),
this._pluginMap, this._options, false);
for (const entry of this._pluginMap.values())
{
// Invoke `typhonjs:plugin:manager:eventbus:changed` allowing external code to react to plugin
// changing eventbus.
if (this._eventbus)
{
this._eventbus.trigger(`typhonjs:plugin:manager:eventbus:changed`, Object.assign({
oldEventbus: this._eventbus,
oldManagerEventPrepend: oldPrepend,
oldScopedName: `${oldPrepend}:${entry.name}`,
newEventbus: targetEventbus,
newManagerEventPrepend: eventPrepend,
newScopedName: `${eventPrepend}:${entry.name}`
}, JSON.parse(JSON.stringify(entry.data))));
}
}
}
if (this._eventbus !== null)
{
this._eventbus.off(`${oldPrepend}:add`, this._addEventbus, this);
this._eventbus.off(`${oldPrepend}:add:all`, this._addAllEventbus, this);
this._eventbus.off(`${oldPrepend}:async:add`, this._addEventbusAsync, this);
this._eventbus.off(`${oldPrepend}:async:add:all`, this._addAllEventbusAsync, this);
this._eventbus.off(`${oldPrepend}:async:destroy:manager`, this._destroyEventbusAsync, this);
this._eventbus.off(`${oldPrepend}:async:invoke`, this.invokeAsync, this);
this._eventbus.off(`${oldPrepend}:async:invoke:event`, this.invokeAsyncEvent, this);
this._eventbus.off(`${oldPrepend}:async:remove`, this._removeEventbusAsync, this);
this._eventbus.off(`${oldPrepend}:async:remove:all`, this._removeAllEventbusAsync, this);
this._eventbus.off(`${oldPrepend}:create:event:proxy`, this.createEventProxy, this);
this._eventbus.off(`${oldPrepend}:destroy:manager`, this._destroyEventbus, this);
this._eventbus.off(`${oldPrepend}:get:all:plugin:data`, this.getAllPluginData, this);
this._eventbus.off(`${oldPrepend}:get:extra:event:data`, this.getExtraEventData, this);
this._eventbus.off(`${oldPrepend}:get:method:names`, this.getMethodNames, this);
this._eventbus.off(`${oldPrepend}:get:options`, this.getOptions, this);
this._eventbus.off(`${oldPrepend}:get:plugin:enabled`, this.getPluginEnabled, this);
this._eventbus.off(`${oldPrepend}:get:plugin:data`, this.getPluginData, this);
this._eventbus.off(`${oldPrepend}:get:plugin:event:names`, this.getPluginEventNames, this);
this._eventbus.off(`${oldPrepend}:get:plugin:method:names`, this.getPluginMethodNames, this);
this._eventbus.off(`${oldPrepend}:get:plugin:names`, this.getPluginNames, this);
this._eventbus.off(`${oldPrepend}:get:plugin:options`, this.getPluginOptions, this);
this._eventbus.off(`${oldPrepend}:get:plugins:enabled`, this.getPluginsEnabled, this);
this._eventbus.off(`${oldPrepend}:get:plugins:by:event:name`, this.getPluginsByEventName, this);
this._eventbus.off(`${oldPrepend}:get:plugins:event:names`, this.getPluginsEventNames, this);
this._eventbus.off(`${oldPrepend}:has:method`, this.hasMethod, this);
this._eventbus.off(`${oldPrepend}:has:plugin`, this.hasPlugin, this);
this._eventbus.off(`${oldPrepend}:has:plugin:method`, this.hasPluginMethod, this);
this._eventbus.off(`${oldPrepend}:invoke`, this.invoke, this);
this._eventbus.off(`${oldPrepend}:is:valid:config`, this.isValidConfig, this);
this._eventbus.off(`${oldPrepend}:remove`, this._removeEventbus, this);
this._eventbus.off(`${oldPrepend}:remove:all`, this._removeAllEventbus, this);
this._eventbus.off(`${oldPrepend}:set:extra:event:data`, this.setExtraEventData, this);
this._eventbus.off(`${oldPrepend}:set:options`, this._setOptionsEventbus, this);
this._eventbus.off(`${oldPrepend}:set:plugin:enabled`, this.setPluginEnabled, this);
this._eventbus.off(`${oldPrepend}:set:plugins:enabled`, this.setPluginsEnabled, this);
this._eventbus.off(`${oldPrepend}:sync:invoke`, this.invokeSync, this);
this._eventbus.off(`${oldPrepend}:sync:invoke:event`, this.invokeSyncEvent, this);
// Invoke `typhonjs:plugin:manager:eventbus:removed` allowing external code to react to eventbus removal.
this._eventbus.trigger(`typhonjs:plugin:manager:eventbus:removed`,
{
oldEventbus: this._eventbus,
oldEventPrepend: oldPrepend,
newEventbus: targetEventbus,
newEventPrepend: eventPrepend
});
}
targetEventbus.on(`${eventPrepend}:add`, this._addEventbus, this);
targetEventbus.on(`${eventPrepend}:add:all`, this._addAllEventbus, this);
targetEventbus.on(`${eventPrepend}:async:add`, this._addEventbusAsync, this);
targetEventbus.on(`${eventPrepend}:async:add:all`, this._addAllEventbusAsync, this);
targetEventbus.on(`${eventPrepend}:async:destroy:manager`, this._destroyEventbusAsync, this);
targetEventbus.on(`${eventPrepend}:async:invoke`, this.invokeAsync, this);
targetEventbus.on(`${eventPrepend}:async:invoke:event`, this.invokeAsyncEvent, this);
targetEventbus.on(`${eventPrepend}:async:remove`, this._removeEventbusAsync, this);
targetEventbus.on(`${eventPrepend}:async:remove:all`, this._removeAllEventbusAsync, this);
targetEventbus.on(`${eventPrepend}:create:event:proxy`, this.createEventProxy, this);
targetEventbus.on(`${eventPrepend}:destroy:manager`, this._destroyEventbus, this);
targetEventbus.on(`${eventPrepend}:get:all:plugin:data`, this.getAllPluginData, this);
targetEventbus.on(`${eventPrepend}:get:extra:event:data`, this.getExtraEventData, this);
targetEventbus.on(`${eventPrepend}:get:method:names`, this.getMethodNames, this);
targetEventbus.on(`${eventPrepend}:get:options`, this.getOptions, this);
targetEventbus.on(`${eventPrepend}:get:plugin:data`, this.getPluginData, this);
targetEventbus.on(`${eventPrepend}:get:plugin:enabled`, this.getPluginEnabled, this);
targetEventbus.on(`${eventPrepend}:get:plugin:event:names`, this.getPluginEventNames, this);
targetEventbus.on(`${eventPrepend}:get:plugin:method:names`, this.getPluginMethodNames, this);
targetEventbus.on(`${eventPrepend}:get:plugin:names`, this.getPluginNames, this);
targetEventbus.on(`${eventPrepend}:get:plugin:options`, this.getPluginOptions, this);
targetEventbus.on(`${eventPrepend}:get:plugins:enabled`, this.getPluginsEnabled, this);
targetEventbus.on(`${eventPrepend}:get:plugins:by:event:name`, this.getPluginsByEventName, this);
targetEventbus.on(`${eventPrepend}:get:plugins:event:names`, this.getPluginsEventNames, this);
targetEventbus.on(`${eventPrepend}:has:method`, this.hasMethod, this);
targetEventbus.on(`${eventPrepend}:has:plugin`, this.hasPlugin, this);
targetEventbus.on(`${eventPrepend}:has:plugin:method`, this.hasPluginMethod, this);
targetEventbus.on(`${eventPrepend}:invoke`, this.invoke, this);
targetEventbus.on(`${eventPrepend}:is:valid:config`, this.isValidConfig, this);
targetEventbus.on(`${eventPrepend}:remove`, this._removeEventbus, this);
targetEventbus.on(`${eventPrepend}:remove:all`, this._removeAllEventbus, this);
targetEventbus.on(`${eventPrepend}:set:extra:event:data`, this.setExtraEventData, this);
targetEventbus.on(`${eventPrepend}:set:options`, this._setOptionsEventbus, this);
targetEventbus.on(`${eventPrepend}:set:plugin:enabled`, this.setPluginEnabled, this);
targetEventbus.on(`${eventPrepend}:set:plugins:enabled`, this.setPluginsEnabled, this);
targetEventbus.on(`${eventPrepend}:sync:invoke`, this.invokeSync, this);
targetEventbus.on(`${eventPrepend}:sync:invoke:event`, this.invokeSyncEvent, this);
// Invoke `typhonjs:plugin:manager:eventbus:set` allowing external code to react to eventbus set.
targetEventbus.trigger('typhonjs:plugin:manager:eventbus:set',
{
oldEventbus: this._eventbus,
oldEventPrepend: oldPrepend,
newEventbus: targetEventbus,
newEventPrepend: eventPrepend
});
this._eventbus = targetEventbus;
return this;
}
/**
* Sets the eventbus associated with this plugin manager. If any previous eventbus was associated all plugin manager
* events will be removed then added to the new eventbus. If there are any existing plugins being managed their
* events will be removed from the old eventbus and then `onPluginLoad` will be called with the new eventbus.
*
* @param {TyphonEvents} targetEventbus - The target eventbus to associate.
*
* @param {string} [eventPrepend='plugins'] - An optional string to prepend to all of the event binding
* targets.
*
* @returns {Promise<PluginManager>}
*/
async setEventbusAsync(targetEventbus, eventPrepend = 'plugins')
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof targetEventbus !== 'object') { throw new TypeError(`'targetEventbus' is not an 'object'.`); }
if (typeof eventPrepend !== 'string') { throw new TypeError(`'eventPrepend' is not a 'string'.`); }
// Early escape if the targetEventbus is the same as the current eventbus.
if (targetEventbus === this._eventbus) { return this; }
const oldPrepend = this._eventPrepend;
/**
* Stores the prepend string for eventbus registration.
* @type {string}
* @private
*/
this._eventPrepend = eventPrepend;
// Unload and reload any existing plugins from the old eventbus to the target eventbus.
if (this._pluginMap.size > 0)
{
// Invoke private module method which allows skipping optional error checking.
await s_INVOKE_ASYNC_EVENTS('onPluginUnload', {}, {}, this._extraEventData, this._pluginMap.keys(),
this._pluginMap, this._options, false);
for (const entry of this._pluginMap.values())
{
// Automatically remove any potential reference to a stored event proxy instance.
try
{
entry.instance._eventbus = void 0;
}
catch (err) { /* nop */ }
entry.data.manager.eventPrepend = eventPrepend;
entry.data.plugin.scopedName = `${eventPrepend}:${entry.name}`;
if (entry.eventProxy instanceof EventProxy) { entry.eventProxy.destroy(); }
entry.eventProxy = new EventProxy(targetEventbus);
}
// Invoke private module method which allows skipping optional error checking.
await s_INVOKE_ASYNC_EVENTS('onPluginLoad', {}, {}, this._extraEventData, this._pluginMap.keys(),
this._pluginMap, this._options, false);
for (const entry of this._pluginMap.values())
{
// Invoke `typhonjs:plugin:manager:eventbus:changed` allowing external code to react to plugin
// changing eventbus.
if (this._eventbus)
{
this._eventbus.trigger(`typhonjs:plugin:manager:eventbus:changed`, Object.assign({
oldEventbus: this._eventbus,
oldManagerEventPrepend: oldPrepend,
oldScopedName: `${oldPrepend}:${entry.name}`,
newEventbus: targetEventbus,
newManagerEventPrepend: eventPrepend,
newScopedName: `${eventPrepend}:${entry.name}`
}, JSON.parse(JSON.stringify(entry.data))));
}
}
}
if (this._eventbus !== null)
{
this._eventbus.off(`${oldPrepend}:add`, this._addEventbus, this);
this._eventbus.off(`${oldPrepend}:add:all`, this._addAllEventbus, this);
this._eventbus.off(`${oldPrepend}:async:add`, this._addEventbusAsync, this);
this._eventbus.off(`${oldPrepend}:async:add:all`, this._addAllEventbusAsync, this);
this._eventbus.off(`${oldPrepend}:async:destroy:manager`, this._destroyEventbusAsync, this);
this._eventbus.off(`${oldPrepend}:async:invoke`, this.invokeAsync, this);
this._eventbus.off(`${oldPrepend}:async:invoke:event`, this.invokeAsyncEvent, this);
this._eventbus.off(`${oldPrepend}:async:remove`, this._removeEventbusAsync, this);
this._eventbus.off(`${oldPrepend}:async:remove:all`, this._removeAllEventbusAsync, this);
this._eventbus.off(`${oldPrepend}:create:event:proxy`, this.createEventProxy, this);
this._eventbus.off(`${oldPrepend}:destroy:manager`, this._destroyEventbus, this);
this._eventbus.off(`${oldPrepend}:get:all:plugin:data`, this.getAllPluginData, this);
this._eventbus.off(`${oldPrepend}:get:extra:event:data`, this.getExtraEventData, this);
this._eventbus.off(`${oldPrepend}:get:method:names`, this.getMethodNames, this);
this._eventbus.off(`${oldPrepend}:get:options`, this.getOptions, this);
this._eventbus.off(`${oldPrepend}:get:plugin:enabled`, this.getPluginEnabled, this);
this._eventbus.off(`${oldPrepend}:get:plugin:data`, this.getPluginData, this);
this._eventbus.off(`${oldPrepend}:get:plugin:event:names`, this.getPluginEventNames, this);
this._eventbus.off(`${oldPrepend}:get:plugin:method:names`, this.getPluginMethodNames, this);
this._eventbus.off(`${oldPrepend}:get:plugin:names`, this.getPluginNames, this);
this._eventbus.off(`${oldPrepend}:get:plugin:options`, this.getPluginOptions, this);
this._eventbus.off(`${oldPrepend}:get:plugins:enabled`, this.getPluginsEnabled, this);
this._eventbus.off(`${oldPrepend}:get:plugins:by:event:name`, this.getPluginsByEventName, this);
this._eventbus.off(`${oldPrepend}:get:plugins:event:names`, this.getPluginsEventNames, this);
this._eventbus.off(`${oldPrepend}:has:method`, this.hasMethod, this);
this._eventbus.off(`${oldPrepend}:has:plugin`, this.hasPlugin, this);
this._eventbus.off(`${oldPrepend}:has:plugin:method`, this.hasPluginMethod, this);
this._eventbus.off(`${oldPrepend}:invoke`, this.invoke, this);
this._eventbus.off(`${oldPrepend}:is:valid:config`, this.isValidConfig, this);
this._eventbus.off(`${oldPrepend}:remove`, this._removeEventbus, this);
this._eventbus.off(`${oldPrepend}:remove:all`, this._removeAllEventbus, this);
this._eventbus.off(`${oldPrepend}:set:extra:event:data`, this.setExtraEventData, this);
this._eventbus.off(`${oldPrepend}:set:options`, this._setOptionsEventbus, this);
this._eventbus.off(`${oldPrepend}:set:plugin:enabled`, this.setPluginEnabled, this);
this._eventbus.off(`${oldPrepend}:set:plugins:enabled`, this.setPluginsEnabled, this);
this._eventbus.off(`${oldPrepend}:sync:invoke`, this.invokeSync, this);
this._eventbus.off(`${oldPrepend}:sync:invoke:event`, this.invokeSyncEvent, this);
// Invoke `typhonjs:plugin:manager:eventbus:removed` allowing external code to react to eventbus removal.
this._eventbus.trigger(`typhonjs:plugin:manager:eventbus:removed`,
{
oldEventbus: this._eventbus,
oldEventPrepend: oldPrepend,
newEventbus: targetEventbus,
newEventPrepend: eventPrepend
});
}
targetEventbus.on(`${eventPrepend}:add`, this._addEventbus, this);
targetEventbus.on(`${eventPrepend}:add:all`, this._addAllEventbus, this);
targetEventbus.on(`${eventPrepend}:async:add`, this._addEventbusAsync, this);
targetEventbus.on(`${eventPrepend}:async:add:all`, this._addAllEventbusAsync, this);
targetEventbus.on(`${eventPrepend}:async:destroy:manager`, this._destroyEventbusAsync, this);
targetEventbus.on(`${eventPrepend}:async:invoke`, this.invokeAsync, this);
targetEventbus.on(`${eventPrepend}:async:invoke:event`, this.invokeAsyncEvent, this);
targetEventbus.on(`${eventPrepend}:async:remove`, this._removeEventbusAsync, this);
targetEventbus.on(`${eventPrepend}:async:remove:all`, this._removeAllEventbusAsync, this);
targetEventbus.on(`${eventPrepend}:create:event:proxy`, this.createEventProxy, this);
targetEventbus.on(`${eventPrepend}:destroy:manager`, this._destroyEventbus, this);
targetEventbus.on(`${eventPrepend}:get:all:plugin:data`, this.getAllPluginData, this);
targetEventbus.on(`${eventPrepend}:get:extra:event:data`, this.getExtraEventData, this);
targetEventbus.on(`${eventPrepend}:get:method:names`, this.getMethodNames, this);
targetEventbus.on(`${eventPrepend}:get:options`, this.getOptions, this);
targetEventbus.on(`${eventPrepend}:get:plugin:data`, this.getPluginData, this);
targetEventbus.on(`${eventPrepend}:get:plugin:enabled`, this.getPluginEnabled, this);
targetEventbus.on(`${eventPrepend}:get:plugin:event:names`, this.getPluginEventNames, this);
targetEventbus.on(`${eventPrepend}:get:plugin:method:names`, this.getPluginMethodNames, this);
targetEventbus.on(`${eventPrepend}:get:plugin:names`, this.getPluginNames, this);
targetEventbus.on(`${eventPrepend}:get:plugin:options`, this.getPluginOptions, this);
targetEventbus.on(`${eventPrepend}:get:plugins:enabled`, this.getPluginsEnabled, this);
targetEventbus.on(`${eventPrepend}:get:plugins:by:event:name`, this.getPluginsByEventName, this);
targetEventbus.on(`${eventPrepend}:get:plugins:event:names`, this.getPluginsEventNames, this);
targetEventbus.on(`${eventPrepend}:has:method`, this.hasMethod, this);
targetEventbus.on(`${eventPrepend}:has:plugin`, this.hasPlugin, this);
targetEventbus.on(`${eventPrepend}:has:plugin:method`, this.hasPluginMethod, this);
targetEventbus.on(`${eventPrepend}:invoke`, this.invoke, this);
targetEventbus.on(`${eventPrepend}:is:valid:config`, this.isValidConfig, this);
targetEventbus.on(`${eventPrepend}:remove`, this._removeEventbus, this);
targetEventbus.on(`${eventPrepend}:remove:all`, this._removeAllEventbus, this);
targetEventbus.on(`${eventPrepend}:set:extra:event:data`, this.setExtraEventData, this);
targetEventbus.on(`${eventPrepend}:set:options`, this._setOptionsEventbus, this);
targetEventbus.on(`${eventPrepend}:set:plugin:enabled`, this.setPluginEnabled, this);
targetEventbus.on(`${eventPrepend}:set:plugins:enabled`, this.setPluginsEnabled, this);
targetEventbus.on(`${eventPrepend}:sync:invoke`, this.invokeSync, this);
targetEventbus.on(`${eventPrepend}:sync:invoke:event`, this.invokeSyncEvent, this);
// Invoke `typhonjs:plugin:manager:eventbus:set` allowing external code to react to eventbus set.
targetEventbus.trigger('typhonjs:plugin:manager:eventbus:set',
{
oldEventbus: this._eventbus,
oldEventPrepend: oldPrepend,
newEventbus: targetEventbus,
newEventPrepend: eventPrepend
});
this._eventbus = targetEventbus;
return this;
}
/**
* Sets any extra event data attached to PluginEvent `extra` field.
*
* @param {*} extraEventData - Adds extra data to PluginEvent `extra` field.
*/
setExtraEventData(extraEventData = void 0)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
this._extraEventData = extraEventData;
}
/**
* Set optional parameters. All parameters are off by default.
*
* @param {PluginManagerOptions} options - Defines optional parameters to set.
*/
setOptions(options = {})
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof options !== 'object') { throw new TypeError(`'options' is not an object.`); }
if (typeof options.pluginsEnabled === 'boolean') { this._options.pluginsEnabled = options.pluginsEnabled; }
if (typeof options.noEventAdd === 'boolean') { this._options.noEventAdd = options.noEventAdd; }
if (typeof options.noEventDestroy === 'boolean') { this._options.noEventDestroy = options.noEventDestroy; }
if (typeof options.noEventOptions === 'boolean') { this._options.noEventOptions = options.noEventOptions; }
if (typeof options.noEventRemoval === 'boolean') { this._options.noEventRemoval = options.noEventRemoval; }
if (typeof options.throwNoMethod === 'boolean') { this._options.throwNoMethod = options.throwNoMethod; }
if (typeof options.throwNoPlugin === 'boolean') { this._options.throwNoPlugin = options.throwNoPlugin; }
}
/**
* Provides the eventbus callback which may prevent plugin manager options being set if optional `noEventOptions` is
* enabled. This disables the ability for the plugin manager options to be set via events preventing any external
* code modifying options.
*
* @param {PluginManagerOptions} options - Defines optional parameters to set.
*
* @private
*/
_setOptionsEventbus(options = {})
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (!this._options.noEventOptions) { this.setOptions(options); }
}
/**
* Enables or disables a single plugin.
*
* @param {string} pluginName - Plugin name to set state.
* @param {boolean} enabled - The new enabled state.
*
* @returns {boolean} - Operation success.
*/
setPluginEnabled(pluginName, enabled)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof pluginName !== 'string') { throw new TypeError(`'pluginName' is not a string.`); }
if (typeof enabled !== 'boolean') { throw new TypeError(`'enabled' is not a boolean.`); }
const entry = this._pluginMap.get(pluginName);
if (entry instanceof PluginEntry)
{
entry.enabled = enabled;
// Invoke `typhonjs:plugin:manager:plugin:enabled` allowing external code to react to plugin enabled state.
if (this._eventbus)
{
this._eventbus.trigger(`typhonjs:plugin:manager:plugin:enabled`, Object.assign({
enabled
}, JSON.parse(JSON.stringify(entry.data))));
}
return true;
}
return false;
}
/**
* Enables or disables a set of plugins given an array or iterabe of plugin names.
*
* @param {Array<string>} pluginNames - An array / iterable of plugin names.
* @param {boolean} enabled - The new enabled state.
*
* @returns {boolean} - Operation success.
*/
setPluginsEnabled(pluginNames, enabled)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (typeof enabled !== 'boolean') { throw new TypeError(`'enabled' is not a boolean.`); }
let success = true;
for (const pluginName of pluginNames)
{
if (!this.setPluginEnabled(pluginName, enabled)) { success = false; }
}
return success;
}
/**
* Removes a plugin by name after unloading it and clearing any event bindings automatically.
*
* @param {string} pluginName - The plugin name to remove.
*
* @returns {boolean} - Operation success.
*/
remove(pluginName)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
const entry = this._pluginMap.get(pluginName);
if (entry instanceof PluginEntry)
{
// Invoke private module method which allows skipping optional error checking.
s_INVOKE_SYNC_EVENTS('onPluginUnload', {}, {}, this._extraEventData, pluginName, this._pluginMap,
this._options, false);
// Automatically remove any potential reference to a stored event proxy instance.
try
{
entry.instance._eventbus = void 0;
}
catch (err) { /* nop */ }
if (entry.eventProxy instanceof EventProxy) { entry.eventProxy.destroy(); }
const pluginData = this.getPluginData(pluginName);
this._pluginMap.delete(pluginName);
// Invoke `typhonjs:plugin:manager:plugin:removed` allowing external code to react to plugin removed.
if (this._eventbus)
{
this._eventbus.trigger(`typhonjs:plugin:manager:plugin:removed`, pluginData);
}
return true;
}
return false;
}
/**
* Removes a plugin by name after unloading it and clearing any event bindings automatically.
*
* @param {string} pluginName - The plugin name to remove.
*
* @returns {Promise<boolean>} - Operation success.
*/
async removeAsync(pluginName)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
const entry = this._pluginMap.get(pluginName);
if (entry instanceof PluginEntry)
{
// Invoke private module method which allows skipping optional error checking.
await s_INVOKE_ASYNC_EVENTS('onPluginUnload', {}, {}, this._extraEventData, pluginName, this._pluginMap,
this._options, false);
// Automatically remove any potential reference to a stored event proxy instance.
try
{
entry.instance._eventbus = void 0;
}
catch (err) { /* nop */ }
if (entry.eventProxy instanceof EventProxy) { entry.eventProxy.destroy(); }
const pluginData = this.getPluginData(pluginName);
this._pluginMap.delete(pluginName);
// Invoke `typhonjs:plugin:manager:plugin:removed` allowing external code to react to plugin removed.
if (this._eventbus)
{
await this._eventbus.triggerAsync(`typhonjs:plugin:manager:plugin:removed`, pluginData);
}
return true;
}
return false;
}
/**
* Removes all plugins after unloading them and clearing any event bindings automatically.
*/
removeAll()
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
for (const pluginName of this._pluginMap.keys())
{
this.remove(pluginName);
}
this._pluginMap.clear();
}
/**
* Removes all plugins after unloading them and clearing any event bindings automatically.
*
* @returns {Promise.<*>}
*/
removeAllAsync()
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
const values = [];
for (const pluginName of this._pluginMap.keys())
{
values.push(this.remove(pluginName));
}
this._pluginMap.clear();
return Promise.all(values);
}
/**
* Provides the eventbus callback which may prevent removal if optional `noEventRemoval` is enabled. This disables
* the ability for plugins to be removed via events preventing any external code removing plugins in this manner.
*
* @param {string} pluginName - The plugin name to remove.
*
* @returns {boolean} - Operation success.
* @private
*/
_removeEventbus(pluginName)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
return !this._options.noEventRemoval ? this.remove(pluginName) : false;
}
/**
* Provides the eventbus callback which may prevent removal if optional `noEventRemoval` is enabled. This disables
* the ability for plugins to be removed via events preventing any external code removing plugins in this manner.
*
* @param {string} pluginName - The plugin name to remove.
*
* @returns {Promise<boolean>} - Operation success.
* @private
*/
async _removeEventbusAsync(pluginName)
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
return !this._options.noEventRemoval ? await this.removeAsync(pluginName) : Promise.resolve(false);
}
/**
* Provides the eventbus callback which may prevent removal if optional `noEventRemoval` is enabled. This disables
* the ability for plugins to be removed via events preventing any external code removing plugins in this manner.
*
* @private
*/
_removeAllEventbus()
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (!this._options.noEventRemoval) { this.removeAll(); }
}
/**
* Provides the eventbus callback which may prevent removal if optional `noEventRemoval` is enabled. This disables
* the ability for plugins to be removed via events preventing any external code removing plugins in this manner.
*
* @private
*/
async _removeAllEventbusAsync()
{
if (this._pluginMap === null) { throw new ReferenceError('This PluginManager instance has been destroyed.'); }
if (!this._options.noEventRemoval) { await this.removeAll(); }
}
} |
JavaScript | class NameEngine extends pattern_engine_1.PatternEngine {
register(checker) {
for (const value of this.config.values) {
const matcher = new absolute_matcher_1.AbsoluteMatcher(value);
// `String.prototype.split` only returns emtpy array when both the string
// and the splitter are empty. Here we should be able to safely assert pop
// returns a non-null result.
const bannedIdName = matcher.bannedName.split('.').pop();
checker.onNamedIdentifier(bannedIdName, this.wrapCheckWithAllowlistingAndFixer((tc, n) => checkId(tc, n, matcher)), this.config.errorCode);
}
}
} |
JavaScript | class DockerImageCode {
/**
* (experimental) Use an existing ECR image as the Lambda code.
*
* @param repository the ECR repository that the image is in.
* @param props properties to further configure the selected image.
* @experimental
*/
static fromEcr(repository, props) {
return {
_bind() {
return new code_1.EcrImageCode(repository, props);
},
};
}
/**
* (experimental) Create an ECR image from the specified asset and bind it as the Lambda code.
*
* @param directory the directory from which the asset must be created.
* @param props properties to further configure the selected image.
* @experimental
*/
static fromImageAsset(directory, props = {}) {
return {
_bind() {
return new code_1.AssetImageCode(directory, props);
},
};
}
} |
JavaScript | class DockerImageFunction extends function_1.Function {
/**
*
*/
constructor(scope, id, props) {
super(scope, id, {
...props,
handler: handler_1.Handler.FROM_IMAGE,
runtime: runtime_1.Runtime.FROM_IMAGE,
code: props.code._bind(),
});
}
} |
JavaScript | class PWAInstallButton extends HTMLButtonElement {
/**
* Base constructor.
*/
constructor() {
super();
this._deferredEvent = null;
this.setAttribute('disabled', '');
window.addEventListener('beforeinstallprompt', (evt) => {
this._deferredEvent = evt;
this._showButton(true);
this._fireEvent('available', null, null, true);
});
window.addEventListener('appinstalled', () => {
this._deferredEvent = null;
this._showButton(false);
this._fireEvent('installed');
});
this.addEventListener('click', (evt) => {
this._showButton(false);
this._showPrompt(evt);
});
}
/**
* Can the PWA be installed?
* @readonly
* @member {boolean}
*/
get canInstall() {
return !!this._deferredEvent;
}
/**
* Helper class to fire events.
* @param {string} action - The type of interaction.
* @param {string} [label] - Useful for categorizing events.
* @param {number} [value] - A numeric value associated with the event.
* @param {boolean} [nonInteraction=false] - Indicates a non-interaction evt.
*/
_fireEvent(action, label, value, nonInteraction) {
const opts = {
bubbles: true,
composed: true,
detail: {action, label, value, nonInteraction},
};
this.dispatchEvent(new CustomEvent('pwa-install', opts));
}
/**
* Shows the add to home screen prompt (if possible).
* @return {boolean} If the prompt was shown or not.
*/
_showPrompt() {
if (!this.canInstall) {
return false;
}
this._fireEvent('promptShown');
this._deferredEvent.prompt();
this._deferredEvent.userChoice.then((result) => {
const value = result.outcome === 'dismissed' ? 0 : 1;
this._fireEvent('promptResponse', null, value);
});
return true;
}
/**
* Shows or hide the button.
* @param {boolean} visible - True to show the button.
* @return {boolean} If the button was shown or not.
*/
_showButton(visible) {
if (!!visible && this._deferredEvent) {
this.removeAttribute('disabled');
return true;
}
this.setAttribute('disabled', '');
return false;
}
} |
JavaScript | class ObjectCullStates {
/**
* @private
* @param scene
*/
constructor(scene) {
this._scene = scene;
this._objects = []; // Array of all Entity instances that represent objects
this._objectsViewCulled = []; // A flag for each object to indicate its view-cull status
this._objectsDetailCulled = []; // A flag for each object to indicate its detail-cull status
this._objectsChanged = []; // A flag for each object, set whenever its cull status has changed since last _applyChanges()
this._objectsChangedList = []; // A list of objects whose cull status has changed, applied and cleared by _applyChanges()
this._modelInfos = {};
this._numObjects = 0;
this._lenObjectsChangedList = 0;
this._dirty = true;
this._onModelLoaded = scene.on("modelLoaded", (modelId) => {
const model = scene.models[modelId];
if (model) {
this._addModel(model);
}
});
this._onTick = scene.on("tick", () => {
if (this._dirty) {
this._build();
}
this._applyChanges();
});
}
_addModel(model) {
const modelInfo = {
model: model,
onDestroyed: model.on("destroyed", () => {
this._removeModel(model);
})
};
this._modelInfos[model.id] = modelInfo;
this._dirty = true;
}
_removeModel(model) {
const modelInfo = this._modelInfos[model.id];
if (modelInfo) {
modelInfo.model.off(modelInfo.onDestroyed);
delete this._modelInfos[model.id];
this._dirty = true;
}
}
_build() {
if (!this._dirty) {
return;
}
this._applyChanges();
const objects = this._scene.objects;
for (let i = 0; i < this._numObjects; i++) {
this._objects[i] = null;
}
this._numObjects = 0;
for (let objectId in objects) {
const entity = objects[objectId];
this._objects[this._numObjects++] = entity;
}
this._lenObjectsChangedList = 0;
this._dirty = false;
}
_applyChanges() {
if (this._lenObjectsChangedList > 0) {
for (let i = 0; i < this._lenObjectsChangedList; i++) {
const objectIdx = this._objectsChangedList[i];
const object = this._objects[objectIdx];
const viewCulled = this._objectsViewCulled[objectIdx];
const detailCulled = this._objectsDetailCulled[objectIdx];
const culled = (viewCulled || detailCulled);
object.culled = culled;
this._objectsChanged[objectIdx] = false;
}
this._lenObjectsChangedList = 0;
}
}
/**
* Array of {@link Entity} instances that represent objects in the {@link Scene}.
*
* ObjectCullStates rebuilds this from {@link Scene#objects} whenever ````Scene```` fires a ````modelLoaded```` event.
*
* @returns {Entity[]}
*/
get objects() {
if (this._dirty) {
this._build();
}
return this._objects;
}
/**
* Number of objects in {@link ObjectCullStates#objects},
*
* Updated whenever ````Scene```` fires a ````modelLoaded```` event.
*
* @returns {Number}
*/
get numObjects() {
if (this._dirty) {
this._build();
}
return this._numObjects;
}
/**
* Updates an object's view-cull status.
*
* @param {Number} objectIdx Index of the object in {@link ObjectCullStates#objects}
* @param {boolean} culled Whether to view-cull or not.
*/
setObjectViewCulled(objectIdx, culled) {
if (this._dirty) {
this._build();
}
if (this._objectsViewCulled[objectIdx] === culled) {
return;
}
this._objectsViewCulled[objectIdx] = culled;
if (!this._objectsChanged[objectIdx]) {
this._objectsChanged[objectIdx] = true;
this._objectsChangedList[this._lenObjectsChangedList++] = objectIdx;
}
}
/**
* Updates an object's detail-cull status.
*
* @param {Number} objectIdx Index of the object in {@link ObjectCullStates#objects}
* @param {boolean} culled Whether to detail-cull or not.
*/
setObjectDetailCulled(objectIdx, culled) {
if (this._dirty) {
this._build();
}
if (this._objectsDetailCulled[objectIdx] === culled) {
return;
}
this._objectsDetailCulled[objectIdx] = culled;
if (!this._objectsChanged[objectIdx]) {
this._objectsChanged[objectIdx] = true;
this._objectsChangedList[this._lenObjectsChangedList++] = objectIdx;
}
}
/**
* Destroys this ObjectCullStAtes.
*/
_destroy() {
this._clear();
this._scene.off(this._onModelLoaded);
this._scene.off(this._onTick);
}
_clear() {
for (let modelId in this._modelInfos) {
const modelInfo = this._modelInfos[modelId];
modelInfo.model.off(modelInfo.onDestroyed);
}
this._modelInfos = {};
this._dirty = true;
}
} |
JavaScript | class Letter{
constructor (char){
this.char = char;
const validChars = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z","0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"];
if (validChars.includes(char) || validChars.includes(char.toLowercase())){
this.visible = false;
} else {
this.visible = true;
}
}
} |
JavaScript | class AudioContextFactory {
/**
* @param {AudioContextFactoryOptions} [options]
*/
constructor(options) {
options = Object.assign({
AudioContext: NativeAudioContext
}, options);
Object.defineProperties(this, {
_AudioContext: {
value: options.AudioContext
},
_audioContext: {
value: null,
writable: true
},
_holders: {
value: new Set()
},
AudioContextFactory: {
enumerable: true,
value: AudioContextFactory
}
});
}
/**
* Each call to {@link AudioContextFactory#getOrCreate} should be paired with a
* call to {@link AudioContextFactory#release}. Calling this increments an
* internal reference count.
* @param {*} holder - The object to hold a reference to the AudioContext
* @returns {?AudioContext}
*/
getOrCreate(holder) {
holder = window;
if (!this._holders.has(holder)) {
this._holders.add(holder);
if (this._AudioContext && !this._audioContext) {
try {
this._audioContext = new this._AudioContext();
} catch (error) {
// Do nothing;
}
}
}
return this._audioContext;
}
/**
* Decrement the internal reference count. If it reaches zero, close and destroy
* the AudioContext.
* @param {*} holder - The object that held a reference to the AudioContext
* @returns {void}
*/
release(holder) {
if (this._holders.has(holder)) {
this._holders.delete(holder);
if (!this._holders.size && this._audioContext) {
this._audioContext.close();
this._audioContext = null;
}
}
}
} |
JavaScript | class HomePage extends Component {
/**
* Creates an instance of HomePage.
* @param {any} props
*
* @memberOf HomePage
*/
constructor(props) {
super(props);
this.state = {
defaultSiteVersion: {
versionValue: '',
modeValue: '',
isActive: false,
},
open: false,
UploaderData: {}
};
this.addSiteVersion = this.addSiteVersion.bind(this);
this.updateSiteVersion = this.updateSiteVersion.bind(this);
this.deleteSiteVersion = this.deleteSiteVersion.bind(this);
this.handleOpen = this.handleOpen.bind(this);
this.handleClose = this.handleClose.bind(this);
this.getUploaderData = this.getUploaderData.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
/**
*
*
*
* @memberOf HomePage
*/
componentWillMount() {
this.props.siteVersionActions.loadModes();
this.props.siteVersionActions.loadVersions();
this.props.siteVersionActions.loadSiteVersions();
this.props.uploadActions.loadFiles();
}
/**
*
*
* @param {any} siteVersion
*
* @memberOf HomePage
*/
addSiteVersion(siteVersion) {
this.props.siteVersionActions.addSiteVersion(siteVersion);
}
/**
*
*
* @param {any} siteVersion
*
* @memberOf HomePage
*/
updateSiteVersion(siteVersion) {
this.props.siteVersionActions.updateSiteVersion(siteVersion);
}
/**
*
*
* @param {any} siteVersion
*
* @memberOf HomePage
*/
deleteSiteVersion(siteVersion) {
this.props.siteVersionActions.deleteSiteVersion(siteVersion);
}
/**
*
*
*
* @memberOf HomePage
*/
handleOpen() {
this.setState({ open: true });
}
/**
*
*
*
* @memberOf HomePage
*/
handleClose() {
this.setState({ open: false });
}
/**
*
*
* @param {any} UploaderData
*
* @memberOf HomePage
*/
getUploaderData(UploaderData) {
this.setState({ UploaderData });
}
/**
*
*
*
* @memberOf HomePage
*/
onSubmit() {
this.setState({ open: false });
this.props.uploadActions.uploadFiles(this.state.UploaderData);
}
/**
*
*
* @returns
*
* @memberOf HomePage
*/
render() {
// const uploadedFiles = this.props.files.map((fls, i) =>
// <TableRow key={i}>
// <TableRowColumn>
// <ul>
// {
// fls.files.map((file, i) => <li key={i}>{file.name}</li>)
// }
// </ul>
// </TableRowColumn>
// <TableRowColumn>
// {fls.ZipCheck ? 'True' : 'False'}
// </TableRowColumn>
// <TableRowColumn style={{ width: 24 }}>
// {fls.PDFCheck ? 'True' : 'False'}
// </TableRowColumn>
// </TableRow>
// );
const gridRows = this.props.siteVersion.map((sv, i) =>
<GridRow
key={i}
versions={this.props.versions}
modes={this.props.modes}
siteVersion={sv}
deleteRow={this.deleteSiteVersion}
updateSiteVersion={this.updateSiteVersion}
/>
);
const actions = [
<FlatButton
key="0"
label="Cancel"
primary={true}
onTouchTap={this.handleClose}
/>,
<FlatButton
key="1"
label="Upload and Create"
primary={true}
onTouchTap={this.onSubmit}
/>,
];
return (
<div>
<RaisedButton primary={true} label="Add Site Version" onClick={() => this.addSiteVersion(this.state.defaultSiteVersion)} labelStyle={{ textTransform: 'none' }} style={{ margin: '20px 0' }} />
<Table selectable={false} height="220px" style={{ border: '1px solid rgb(224, 224, 224)' }}>
<TableHeader displaySelectAll={false} adjustForCheckbox={false}>
<TableRow>
<TableHeaderColumn style={{ textAlign: 'center' }} children="Version" className="header" />
<TableHeaderColumn style={{ textAlign: 'center' }} children="Mode" />
<TableHeaderColumn style={{ width: 24, textAlign: 'center' }} children="Activate" />
<TableHeaderColumn style={{ width: 24, textAlign: 'center' }} />
</TableRow>
</TableHeader>
<TableBody displayRowCheckbox={false}>
{gridRows}
</TableBody>
</Table>
<RaisedButton primary={true} label="Bulk Upload" onTouchTap={this.handleOpen} labelStyle={{ textTransform: 'none' }}/>
<Dialog
actions={actions}
modal={true}
open={this.state.open}
>
<Uploader multiple={true} onDataChange={this.getUploaderData} />
</Dialog>
</div>
);
}
} |
JavaScript | class Sidebar extends React.Component {
constructor() {
super()
this.state = {
selectedLimitOrder: false,
limitOrderPrice: 0,
orderQuantity: 0,
}
}
// To use bytes32 functions
bytes32(name) {
return myWeb3.utils.fromAscii(name)
}
resetInputs() {
this.refs.limitOrderPrice.value = ''
this.refs.orderQuantity.value = ''
this.setState({
limitOrderPrice: 0,
orderQuantity: 0,
})
}
render() {
return (
<div className="sidebar">
<div className="selected-assets-title heading">Selected assets</div>
<div className="selected-asset-one">{this.props.firstSymbol}</div>
<div className="selected-asset-two">{this.props.secondSymbol}</div>
<div className="your-portfolio heading">Your portfolio</div>
<div className="grid-center">{this.props.firstSymbol}:</div><div className="grid-center">{this.props.balanceOne ? this.props.balanceOne : 'Loading...'}</div>
<div className="grid-center">{this.props.secondSymbol}:</div><div className="grid-center">{this.props.balanceTwo ? this.props.balanceTwo : 'Loading...'}</div>
<div className="money-management heading">Money management</div>
<button className="button-outline" onClick={() => {
const amount = prompt(`How many ${this.props.firstSymbol} tokens do you want to deposit?`)
this.props.deposit(this.props.firstSymbol, amount)
}}>Deposit {this.props.firstSymbol} </button>
<button className="button-outline" onClick={() => {
const amount = prompt(`How many ${this.props.firstSymbol} tokens do you want to withdraw?`)
this.props.withdraw(this.props.firstSymbol, amount)
}}>Withdraw {this.props.firstSymbol}</button>
<button className="button-outline" onClick={() => {
const amount = prompt(`How many ${this.props.secondSymbol} tokens do you want to deposit?`)
this.props.deposit(this.props.secondSymbol, amount)
}}>Deposit {this.props.secondSymbol} </button>
<button className="button-outline" onClick={() => {
const amount = prompt(`How many ${this.props.secondSymbol} tokens do you want to withdraw?`)
this.props.withdraw(this.props.secondSymbol, amount)
}}>Withdraw {this.props.secondSymbol}</button>
<div className="actions heading">Actions</div>
<button onClick={() => {
if(this.state.orderQuantity == 0) return alert('You must specify how many tokens you want to buy')
if(this.state.selectedLimitOrder) {
if(this.state.limitOrderPrice == 0) return alert('You must specify the token price at which you want to buy')
if(this.props.balanceTwo < (this.state.orderQuantity * this.state.limitOrderPrice)) {
return alert(`You must approve ${this.state.orderQuantity * this.state.limitOrderPrice} of ${this.props.secondSymbol} tokens to create this buy limit order, your ${this.props.secondSymbol} token balance must be larger than ${this.state.orderQuantity * this.state.limitOrderPrice}`)
}
// Buy the this.state.orderQuantity of this.props.firstSymbol
this.props.limitOrder(this.bytes32('buy'), this.bytes32(this.props.firstSymbol), this.bytes32(this.props.secondSymbol), this.state.orderQuantity, this.state.limitOrderPrice)
} else {
this.props.marketOrder(this.bytes32('buy'), this.bytes32(this.props.firstSymbol), this.bytes32(this.props.secondSymbol), this.state.orderQuantity)
}
this.resetInputs()
}}>Buy {this.props.firstSymbol}</button>
<button onClick={() => {
if(this.state.orderQuantity == 0) return alert('You must specify how many tokens you want to sell')
if(this.state.selectedLimitOrder) {
if(this.state.limitOrderPrice == 0) return alert('You must specify the token price at which you want to sell')
if(this.props.balanceOne < this.state.orderQuantity) {
return alert(`You must approve ${this.state.orderQuantity} of ${this.props.firstSymbol} tokens to create this sell limit order, your ${this.props.firstSymbol} token balance must be larger than ${this.state.orderQuantity}`)
}
// Buy the this.state.orderQuantity of this.props.firstSymbol
this.props.limitOrder(this.bytes32('sell'), this.bytes32(this.props.firstSymbol), this.bytes32(this.props.secondSymbol), this.state.orderQuantity, this.state.limitOrderPrice)
} else {
this.props.marketOrder(this.bytes32('sell'), this.bytes32(this.props.firstSymbol), this.bytes32(this.props.secondSymbol), this.state.orderQuantity)
}
this.resetInputs()
}} className="sell">Sell {this.props.firstSymbol}</button>
<select defaultValue="market-order" onChange={selected => {
if(selected.target.value == 'limit-order') {
this.setState({selectedLimitOrder: true})
} else {
this.setState({selectedLimitOrder: false})
}
}}>
<option value="market-order">Market Order</option>
<option value="limit-order">Limit Order</option>
</select>
<input ref="limitOrderPrice" onChange={event => {
this.setState({limitOrderPrice: event.target.value})
}} className={this.state.selectedLimitOrder ? '' : 'hidden'} type="number" placeholder="Price to buy or sell at..." />
<input ref="orderQuantity" onChange={event => {
this.setState({orderQuantity: event.target.value})
}} type="number" placeholder={`Quantity of ${this.props.firstSymbol} to buy or sell...`} />
</div>
)
}
} |
JavaScript | class Orders extends React.Component {
constructor() {
super()
}
render() {
let buyOrders = this.props.buyOrders
let sellOrders = this.props.sellOrders
if(buyOrders.length > 0) {
buyOrders = buyOrders.map((trade, index) => (
<div key={trade.id + index} className="trade-container buy-trade">
<div className="trade-symbol">{trade.firstSymbol}</div>
<div className="trade-symbol">{trade.secondSymbol}</div>
<div className="trade-pricing">{trade.type} {trade.quantity} {trade.secondSymbol} at {trade.price} {trade.secondSymbol} each</div>
</div>
))
}
if(sellOrders.length > 0) {
sellOrders = sellOrders.map((trade, index) => (
<div key={trade.id + index} className="trade-container sell-trade">
<div className="trade-symbol">{trade.firstSymbol}</div>
<div className="trade-symbol">{trade.secondSymbol}</div>
<div className="trade-pricing">{trade.type} {trade.quantity} {trade.secondSymbol} at {trade.price} {trade.secondSymbol} each</div>
</div>
))
}
return (
<div className="trades">
<div className="buy-trades-title heading">Buy</div>
<div className="buy-trades-container">{buyOrders}</div>
<div className="sell-trades-title heading">Sell</div>
<div className="sell-trades-container">{sellOrders}</div>
</div>
)
}
} |
JavaScript | class History extends React.Component {
constructor() {
super()
}
render() {
let closedOrders = this.props.closedOrders
if(closedOrders.length > 0) {
closedOrders = closedOrders.map((trade, index) => (
<div key={trade.id + index} className="historical-trade">
<div className={trade.type == 'sell' ? 'sell-trade' : 'buy-trade'}>{trade.type} {trade.quantity} {trade.firstSymbol} for {trade.quantity * trade.price} {trade.secondSymbol} at {trade.price} each</div>
</div>
))
}
return (
<div className="history">
<div className="heading">Recent history</div>
<div className="historical-trades-container">{closedOrders}</div>
</div>
)
}
} |
JavaScript | class AudioListenerOld extends AudioListenerBase {
/**
* Creates a new positioner that uses WebAudio's playback dependent time progression.
* @param {AudioListener} listener
*/
constructor(listener) {
super(listener);
Object.seal(this);
}
/**
* Performs the spatialization operation for the audio source's latest location.
* @param {Pose} loc
*/
update(loc) {
super.update(loc);
const { p, f, u } = loc;
this.node.setPosition(p.x, p.y, p.z);
this.node.setOrientation(f.x, f.y, f.z, u.x, u.y, u.z);
}
/**
* Creates a spatialzer for an audio source.
* @private
* @param {string} id
* @param {MediaStream|HTMLAudioElement} stream - the audio element that is being spatialized.
* @param {number} bufferSize - the size of the analysis buffer to use for audio activity detection
* @param {AudioContext} audioContext
* @param {Pose} dest
* @return {BaseSource}
*/
createSource(id, stream, bufferSize, audioContext, dest) {
return new PannerOld(id, stream, bufferSize, audioContext);
}
} |
JavaScript | class RoleController extends Controller {
/**
* isRequestWellParameterized - verify if request contains valid params
*
* @param {Request} request
* @returns {boolean}
*/
isRequestWellParameterized( request ) {
return this.verifyParams([
{ property: 'name', typeExpected: 'string' },
{ property: 'slug', typeExpected: 'string' }
], request.getBody() )
}
/**
* roleExists
*
* @param {Request} request
* @param {Response} response
* @returns {boolean}
*/
async roleExists( request, response ) {
const em = this.getEntityManager()
const Role = em.getModel( 'role/entity/role' )
const roleRepository = em.getRepository( 'role/entity/role.repository', { model: Role })
try {
const role = await roleRepository.find( request.getRouteParameter( 'role_id' ), Role )
if ( !role ) {
response.notFound()
return false
}
request.store( 'role', role )
return true
} catch ( error ) {
response.internalServerError( error )
return false
}
}
/**
* getRoles - get all roles
*
* @param {Request} request
* @param {Response} response
*/
async getRoles( request, response ) {
const roleRepository = this.getEntityManager().getRepository( 'role/entity/role.repository', { model: 'role/entity/role' })
try {
const roles = await roleRepository.findAll()
response.ok( roles )
} catch ( error ) {
response.internalServerError( error )
}
}
/**
* createRole - create new role
*
* @param {Request} request
* @param {Response} response
*/
async createRole( request, response ) {
if ( this.isRequestWellParameterized( request ) ) {
const em = this.getEntityManager()
const Role = em.getModel( 'role/entity/role' )
const roleRepository = em.getRepository( 'role/entity/role.repository', { model: Role })
try {
const role = await roleRepository.save( new Role(), request.getBody() )
response.created( role )
} catch ( error ) {
response.internalServerError( error )
}
} else {
response.badRequest()
}
}
/**
* getRole - get role by id
*
* @param {Request} request
* @param {Response} response
*/
getRole( request, response ) {
response.ok( request.retrieve( 'role' ) )
}
/**
* updateRole - update role
*
* @param {Request} request
* @param {Response} response
*/
async updateRole( request, response ) {
if ( this.isRequestWellParameterized( request ) ) {
const roleRepository = this.getEntityManager().getRepository( 'role/entity/role.repository', { model: 'role/entity/role' })
try {
const role = await roleRepository.save( request.retrieve( 'role' ), request.getBody() )
response.ok( role )
} catch ( error ) {
response.internalServerError( error )
}
} else {
response.badRequest()
}
}
/**
* deleteRole - delete role
*
* @param {Request} request
* @param {Response} response
*/
async deleteRole( request, response ) {
const roleRepository = this.getEntityManager().getRepository( 'role/entity/role.repository', { model: 'role/entity/role' })
try {
await roleRepository.delete( request.retrieve( 'role' ) )
response.noContent()
} catch ( error ) {
response.internalServerError( error )
}
}
} |
JavaScript | class Serial {
constructor(config) {
console.log(config);
}
open(cb) { }
close(cb) { }
write(data, cb) { }
flush(cb) { }
on(x, cd) { }
} |
JavaScript | class PathMovingComponent extends ComponentBase
{
init(props)
{
props.path = []
props.current_point = 0
super.init(props)
this.join("TransformComponent")
this.addIntefaces(new ISpeed(), new ITimer())
}
getCounter()
{
return this.getProperty("current_point")
}
getPath()
{
return this.getProperty("path")
}
getPathSize()
{
return this.getPath().length
}
getCurentPoint()
{
let path = this.getPath()
let index = this.getCounter();
return path[index]
}
setCounter(value)
{
this.setProperty("current_point", value)
}
switchPoint()
{
let counter = this.getCounter() + 1
let size = this.getPathSize()
this.setCounter(counter)
if(counter >= size) this.setCounter(0);
}
update()
{
let transform_component = this.joined["TransformComponent"]
if(this.getPathSize())
{
let pos = transform_component.getPosition();
let point = this.getCurentPoint();
transform_component.move_to(point, this.getSpeed() * TimeSystem.getDeltaTime())
if(point.equals(pos))
{
if(!this.updateTimer())
{
this.switchPoint()
}
}
}
}
} |
JavaScript | class BrownianMovingComponent extends ComponentBase
{
init(props)
{
super.init(props)
this.join("TransformComponent")
this.addIntefaces(new ISpeed())
}
update()
{
let transform_component = this.joined["TransformComponent"]
let vec = Vector2.random();
transform_component.move(vec.mul(TimeSystem.getDeltaTime() * this.getSpeed()))
}
} |
JavaScript | class RoundMovingComponent extends ComponentBase
{
init(props)
{
props.axis = new Vector2(0, 0);
super.init(props)
this.join("TransformComponent")
this.addIntefaces(new ISpeed(), new ITarget())
}
getAxis()
{
let target = this.getTarget();
if(target)
{
if(target.hasComponent("TransformComponent"))
{
return target.getComponent("TransformComponent").getCenter()
}
}
return this.getProperty("axis")
}
update()
{
let transform_component = this.joined["TransformComponent"]
transform_component.move_around(this.getAxis(), this.getSpeed() * TimeSystem.getDeltaTime())
}
} |
JavaScript | class LrnButton extends PolymerElement {
/* REQUIRED FOR TOOLING DO NOT TOUCH */
/**
* Store the tag name to make it easier to obtain directly.
* @notice function name must be here for tooling to operate correctly
*/
static get tag() {
return "lrn-button";
}
constructor() {
super();
import("@polymer/paper-button/paper-button.js");
import("@polymer/paper-tooltip/paper-tooltip.js");
}
/**
* life cycle, element is afixed to the DOM
*/
connectedCallback() {
super.connectedCallback();
afterNextRender(this, function() {
this.addEventListener("mousedown", this.tapEventOn);
this.addEventListener("mouseover", this.tapEventOn);
this.addEventListener("mouseout", this.tapEventOff);
this.$.button.addEventListener("focused-changed", this.focusToggle);
});
}
/**
* life cycle, element is removed from the DOM
*/
disconnectedCallback() {
this.removeEventListener("mousedown", this.tapEventOn);
this.removeEventListener("mouseover", this.tapEventOn);
this.removeEventListener("mouseout", this.tapEventOff);
this.$.button.removeEventListener("focused-changed", this.focusToggle);
super.disconnectedCallback();
}
/**
* Go to the href if the button isn't disabled
*/
ready() {
super.ready();
if (!this.disabled) {
this.showHref = this.href;
}
}
/**
* Class processing on un-tap / hover
*/
tapEventOn(e) {
let root = this;
if (typeof root.hoverClass !== typeof undefined && !root.disabled) {
// break class into array
var classes = root.hoverClass.split(" ");
// run through each and add or remove classes
classes.forEach(function(item, index) {
if (item != "") {
root.$.button.classList.add(item);
if (item.indexOf("-") != -1) {
root.$.icon.classList.add(item);
}
}
});
}
}
/**
* Undo class processing on un-tap / hover
*/
tapEventOff(e) {
let root = this;
if (typeof root.hoverClass !== typeof undefined && !root.disabled) {
// break class into array
var classes = root.hoverClass.split(" ");
// run through each and add or remove classes
classes.forEach(function(item, index) {
if (item != "") {
root.$.button.classList.remove(item);
if (item.indexOf("-") != -1) {
root.$.icon.classList.remove(item);
}
}
});
}
}
/**
* Handle toggle for mouse class and manage classList array for paper-button.
*/
focusToggle(e) {
let root = this;
this.dispatchEvent(
new CustomEvent("focus-changed", {
bubbles: true,
composed: true,
detail: { focus: root.focusState }
})
);
// see if it has hover classes
if (typeof root.hoverClass !== typeof undefined && !root.disabled) {
// break class into array
var classes = root.hoverClass.split(" ");
// run through each and add or remove classes
classes.forEach(function(item, index) {
if (item != "") {
if (root.focusState) {
root.$.button.classList.add(item);
if (item.indexOf("-") != -1) {
root.$.icon.classList.add(item);
}
} else {
root.$.button.classList.remove(item);
if (item.indexOf("-") != -1) {
root.$.icon.classList.remove(item);
}
}
}
});
}
root.focusState = !root.focusState;
}
} |
JavaScript | class Scene_IntroVideo extends _Scene_Base {
constructor() {
super();
};
start(){
super.start();
$camera.pivot.y = -$camera._sceneH/2
this.create_IntroVideo();
//this.setupCamera(); //TODO: ADD TO SCENE BASE ?
};
update(delta){
};
end(){
this.visible = false;
this.renderable = false;
};
create_IntroVideo () {
const dataVideo = $Loader.Data2['vidA1'].data;
const texture = PIXI.Texture.fromVideo( dataVideo, 1, void 0, false );
const videoSprite = new PIXI.Sprite(texture);
const videoControler = texture.baseTexture.source;
videoSprite.anchor.set(0.5,1)
videoSprite.width = 1920;
videoSprite.height = 1080;
videoControler.currentTime = 12.2;
videoControler.onended = () => {
//this.nextVideo();
$stage.goto('Scene_Title');
}
this.addChild(videoSprite);
this.videoControler = videoControler;
videoControler.play();
};
setupCamera(){
//$camera.initialize();
//$camera.setTarget($player.spine.position);
}
} |
JavaScript | class BaseEnum {
static getStaticKeysList() {
return Object.keys(this);
}
static getStaticValueList() {
return Object.values(this);
}
} |
JavaScript | class ShiftController
{
/**
* Retrieve a Shift [GET /packhouse/sites/{siteId}/shifts/{id}]
*
* @static
* @public
* @param {number} siteId The Site ID
* @param {string} id The Shift ID
* @return {Promise<ShiftModel>}
*/
static getOne(siteId, id)
{
return new Promise((resolve, reject) => {
RequestHelper.getRequest(`/packhouse/sites/${siteId}/shifts/${id}`)
.then((result) => {
let resolveValue = (function(){
return ShiftModel.fromJSON(result);
}());
resolve(resolveValue);
})
.catch(error => reject(error));
});
}
/**
* Update a Shift [PATCH /packhouse/sites/{siteId}/shifts/{id}]
*
* @static
* @public
* @param {number} siteId The Site ID
* @param {string} id The Shift ID
* @param {ShiftController.UpdateData} updateData The Shift Update Data
* @return {Promise<ShiftModel>}
*/
static update(siteId, id, updateData)
{
return new Promise((resolve, reject) => {
RequestHelper.patchRequest(`/packhouse/sites/${siteId}/shifts/${id}`, updateData)
.then((result) => {
let resolveValue = (function(){
return ShiftModel.fromJSON(result);
}());
resolve(resolveValue);
})
.catch(error => reject(error));
});
}
/**
* Delete a Shift [DELETE /packhouse/sites/{siteId}/shifts/{id}]
*
* @static
* @public
* @param {number} siteId The Site ID
* @param {string} id The Shift ID
* @return {Promise<boolean>}
*/
static delete(siteId, id)
{
return new Promise((resolve, reject) => {
RequestHelper.deleteRequest(`/packhouse/sites/${siteId}/shifts/${id}`)
.then((result) => {
resolve(result ?? true);
})
.catch(error => reject(error));
});
}
/**
* Retrieve Comments [GET /packhouse/sites/{siteId}/shifts/{id}/comments]
*
* Retrieves Comments for a Shift
*
* @static
* @public
* @param {number} siteId The Site ID
* @param {string} id The Shift ID
* @return {Promise<Array<ShiftController.CommentItem>>}
*/
static getComments(siteId, id)
{
return new Promise((resolve, reject) => {
RequestHelper.getRequest(`/packhouse/sites/${siteId}/shifts/${id}/comments`)
.then((result) => {
let resolveValue = (function(){
if(Array.isArray(result) !== true)
{
return [];
}
return result.map((resultItem) => {
return (function(){
let resultItemObject = {};
if(typeof resultItem === 'object' && 'id' in resultItem)
{
resultItemObject.id = (function(){
if(typeof resultItem.id !== 'string')
{
return String(resultItem.id);
}
return resultItem.id;
}());
}
else
{
resultItemObject.id = "";
}
if(typeof resultItem === 'object' && 'content' in resultItem)
{
resultItemObject.content = (function(){
if(resultItem.content === null)
{
return null;
}
if(typeof resultItem.content !== 'string')
{
return String(resultItem.content);
}
return resultItem.content;
}());
}
else
{
resultItemObject.content = null;
}
if(typeof resultItem === 'object' && 'createdTimestamp' in resultItem)
{
resultItemObject.createdTimestamp = (function(){
if(resultItem.createdTimestamp === null)
{
return null;
}
if(typeof resultItem.createdTimestamp !== 'string')
{
return new Date(String(resultItem.createdTimestamp));
}
return new Date(resultItem.createdTimestamp);
}());
}
else
{
resultItemObject.createdTimestamp = null;
}
if(typeof resultItem === 'object' && 'updatedTimestamp' in resultItem)
{
resultItemObject.updatedTimestamp = (function(){
if(resultItem.updatedTimestamp === null)
{
return null;
}
if(typeof resultItem.updatedTimestamp !== 'string')
{
return new Date(String(resultItem.updatedTimestamp));
}
return new Date(resultItem.updatedTimestamp);
}());
}
else
{
resultItemObject.updatedTimestamp = null;
}
return resultItemObject;
}());
});
}());
resolve(resolveValue);
})
.catch(error => reject(error));
});
}
/**
* Create a Comment [POST /packhouse/sites/{siteId}/shifts/{id}/comments]
*
* Create a Comment for a Shift
*
* @static
* @public
* @param {number} siteId The Site ID
* @param {string} id The Shift ID
* @param {string} content The Content of the New Comment
* @return {Promise<ShiftController.CommentItem>}
*/
static createComment(siteId, id, content)
{
return new Promise((resolve, reject) => {
RequestHelper.postRequest(`/packhouse/sites/${siteId}/shifts/${id}/comments`, {content})
.then((result) => {
let resolveValue = (function(){
let resultObject = {};
if(typeof result === 'object' && 'id' in result)
{
resultObject.id = (function(){
if(typeof result.id !== 'string')
{
return String(result.id);
}
return result.id;
}());
}
else
{
resultObject.id = "";
}
if(typeof result === 'object' && 'content' in result)
{
resultObject.content = (function(){
if(result.content === null)
{
return null;
}
if(typeof result.content !== 'string')
{
return String(result.content);
}
return result.content;
}());
}
else
{
resultObject.content = null;
}
if(typeof result === 'object' && 'createdTimestamp' in result)
{
resultObject.createdTimestamp = (function(){
if(result.createdTimestamp === null)
{
return null;
}
if(typeof result.createdTimestamp !== 'string')
{
return new Date(String(result.createdTimestamp));
}
return new Date(result.createdTimestamp);
}());
}
else
{
resultObject.createdTimestamp = null;
}
if(typeof result === 'object' && 'updatedTimestamp' in result)
{
resultObject.updatedTimestamp = (function(){
if(result.updatedTimestamp === null)
{
return null;
}
if(typeof result.updatedTimestamp !== 'string')
{
return new Date(String(result.updatedTimestamp));
}
return new Date(result.updatedTimestamp);
}());
}
else
{
resultObject.updatedTimestamp = null;
}
return resultObject;
}());
resolve(resolveValue);
})
.catch(error => reject(error));
});
}
/**
* Retrieve a Comment [GET /packhouse/sites/{siteId}/shifts/{id}/comments/{commentId}]
*
* Retrieves Comments for a Shift
*
* @static
* @public
* @param {number} siteId The Site ID
* @param {string} id The Shift ID
* @param {string} commentId The Comment ID
* @return {Promise<ShiftController.CommentItem>}
*/
static getOneComment(siteId, id, commentId)
{
return new Promise((resolve, reject) => {
RequestHelper.getRequest(`/packhouse/sites/${siteId}/shifts/${id}/comments/${commentId}`)
.then((result) => {
let resolveValue = (function(){
let resultObject = {};
if(typeof result === 'object' && 'id' in result)
{
resultObject.id = (function(){
if(typeof result.id !== 'string')
{
return String(result.id);
}
return result.id;
}());
}
else
{
resultObject.id = "";
}
if(typeof result === 'object' && 'content' in result)
{
resultObject.content = (function(){
if(result.content === null)
{
return null;
}
if(typeof result.content !== 'string')
{
return String(result.content);
}
return result.content;
}());
}
else
{
resultObject.content = null;
}
if(typeof result === 'object' && 'createdTimestamp' in result)
{
resultObject.createdTimestamp = (function(){
if(result.createdTimestamp === null)
{
return null;
}
if(typeof result.createdTimestamp !== 'string')
{
return new Date(String(result.createdTimestamp));
}
return new Date(result.createdTimestamp);
}());
}
else
{
resultObject.createdTimestamp = null;
}
if(typeof result === 'object' && 'updatedTimestamp' in result)
{
resultObject.updatedTimestamp = (function(){
if(result.updatedTimestamp === null)
{
return null;
}
if(typeof result.updatedTimestamp !== 'string')
{
return new Date(String(result.updatedTimestamp));
}
return new Date(result.updatedTimestamp);
}());
}
else
{
resultObject.updatedTimestamp = null;
}
return resultObject;
}());
resolve(resolveValue);
})
.catch(error => reject(error));
});
}
/**
* Update a Comment [PATCH /packhouse/sites/{siteId}/shifts/{id}/comments/{commentId}]
*
* Update a Comment for a Shift
*
* @static
* @public
* @param {number} siteId The Site ID
* @param {string} id The Shift ID
* @param {string} commentId The Comment ID
* @param {string} content The Updated Content for the Comment
* @return {Promise<ShiftController.CommentItem>}
*/
static updateOneComment(siteId, id, commentId, content)
{
return new Promise((resolve, reject) => {
RequestHelper.patchRequest(`/packhouse/sites/${siteId}/shifts/${id}/comments/${commentId}`, {content})
.then((result) => {
let resolveValue = (function(){
let resultObject = {};
if(typeof result === 'object' && 'id' in result)
{
resultObject.id = (function(){
if(typeof result.id !== 'string')
{
return String(result.id);
}
return result.id;
}());
}
else
{
resultObject.id = "";
}
if(typeof result === 'object' && 'content' in result)
{
resultObject.content = (function(){
if(result.content === null)
{
return null;
}
if(typeof result.content !== 'string')
{
return String(result.content);
}
return result.content;
}());
}
else
{
resultObject.content = null;
}
if(typeof result === 'object' && 'createdTimestamp' in result)
{
resultObject.createdTimestamp = (function(){
if(result.createdTimestamp === null)
{
return null;
}
if(typeof result.createdTimestamp !== 'string')
{
return new Date(String(result.createdTimestamp));
}
return new Date(result.createdTimestamp);
}());
}
else
{
resultObject.createdTimestamp = null;
}
if(typeof result === 'object' && 'updatedTimestamp' in result)
{
resultObject.updatedTimestamp = (function(){
if(result.updatedTimestamp === null)
{
return null;
}
if(typeof result.updatedTimestamp !== 'string')
{
return new Date(String(result.updatedTimestamp));
}
return new Date(result.updatedTimestamp);
}());
}
else
{
resultObject.updatedTimestamp = null;
}
return resultObject;
}());
resolve(resolveValue);
})
.catch(error => reject(error));
});
}
/**
* Delete a Comment [DELETE /packhouse/sites/{siteId}/shifts/{id}/comments/{commentId}]
*
* Delete a Comment for a Shift
*
* @static
* @public
* @param {number} siteId The Site ID
* @param {string} id The Shift ID
* @param {string} commentId The Comment ID
* @return {Promise<boolean>}
*/
static deleteOneComment(siteId, id, commentId)
{
return new Promise((resolve, reject) => {
RequestHelper.deleteRequest(`/packhouse/sites/${siteId}/shifts/${id}/comments/${commentId}`)
.then((result) => {
resolve(result ?? true);
})
.catch(error => reject(error));
});
}
/**
* List all Shifts [GET /packhouse/sites/{siteId}/shifts]
*
* @static
* @public
* @param {number} siteId The Site ID
* @param {ShiftController.GetAllQueryParameters} [queryParameters] The Optional Query Parameters
* @return {Promise<ShiftModel[]>}
*/
static getAll(siteId, queryParameters = {})
{
return new Promise((resolve, reject) => {
RequestHelper.getRequest(`/packhouse/sites/${siteId}/shifts`, queryParameters)
.then((result) => {
let resolveValue = (function(){
if(Array.isArray(result) !== true)
{
return [];
}
return result.map((resultItem) => {
return (function(){
return ShiftModel.fromJSON(resultItem);
}());
});
}());
resolve(resolveValue);
})
.catch(error => reject(error));
});
}
/**
* Create a Shift [POST /packhouse/sites/{siteId}/shifts]
*
* @static
* @public
* @param {number} siteId The Site ID
* @param {ShiftController.CreateData} createData The Shift Create Data
* @return {Promise<ShiftModel>}
*/
static create(siteId, createData)
{
return new Promise((resolve, reject) => {
RequestHelper.postRequest(`/packhouse/sites/${siteId}/shifts`, createData)
.then((result) => {
let resolveValue = (function(){
return ShiftModel.fromJSON(result);
}());
resolve(resolveValue);
})
.catch(error => reject(error));
});
}
} |
JavaScript | class Lexer {
constructor() {
/**
* Flag indicating whether the end of the current buffer marks the end of
* all input
*/
this.atEnd = false;
/**
* Explicit indent set in block scalar header, as an offset from the current
* minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not
* explicitly set.
*/
this.blockScalarIndent = -1;
/**
* Block scalars that include a + (keep) chomping indicator in their header
* include trailing empty lines, which are otherwise excluded from the
* scalar's contents.
*/
this.blockScalarKeep = false;
/** Current input */
this.buffer = '';
/**
* Flag noting whether the map value indicator : can immediately follow this
* node within a flow context.
*/
this.flowKey = false;
/** Count of surrounding flow collection levels. */
this.flowLevel = 0;
/**
* Minimum level of indentation required for next lines to be parsed as a
* part of the current scalar value.
*/
this.indentNext = 0;
/** Indentation level of the current line. */
this.indentValue = 0;
/** Position of the next \n character. */
this.lineEndPos = null;
/** Stores the state of the lexer if reaching the end of incpomplete input */
this.next = null;
/** A pointer to `buffer`; the current position of the lexer. */
this.pos = 0;
}
/**
* Generate YAML tokens from the `source` string. If `incomplete`,
* a part of the last line may be left as a buffer for the next call.
*
* @returns A generator of lexical tokens
*/
*lex(source, incomplete = false) {
var _a;
if (source) {
this.buffer = this.buffer ? this.buffer + source : source;
this.lineEndPos = null;
}
this.atEnd = !incomplete;
let next = (_a = this.next) !== null && _a !== void 0 ? _a : 'stream';
while (next && (incomplete || this.hasChars(1)))
next = yield* this.parseNext(next);
}
atLineEnd() {
let i = this.pos;
let ch = this.buffer[i];
while (ch === ' ' || ch === '\t')
ch = this.buffer[++i];
if (!ch || ch === '#' || ch === '\n')
return true;
if (ch === '\r')
return this.buffer[i + 1] === '\n';
return false;
}
charAt(n) {
return this.buffer[this.pos + n];
}
continueScalar(offset) {
let ch = this.buffer[offset];
if (this.indentNext > 0) {
let indent = 0;
while (ch === ' ')
ch = this.buffer[++indent + offset];
if (ch === '\r') {
const next = this.buffer[indent + offset + 1];
if (next === '\n' || (!next && !this.atEnd))
return offset + indent + 1;
}
return ch === '\n' || indent >= this.indentNext || (!ch && !this.atEnd)
? offset + indent
: -1;
}
if (ch === '-' || ch === '.') {
const dt = this.buffer.substr(offset, 3);
if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3]))
return -1;
}
return offset;
}
getLine() {
let end = this.lineEndPos;
if (typeof end !== 'number' || (end !== -1 && end < this.pos)) {
end = this.buffer.indexOf('\n', this.pos);
this.lineEndPos = end;
}
if (end === -1)
return this.atEnd ? this.buffer.substring(this.pos) : null;
if (this.buffer[end - 1] === '\r')
end -= 1;
return this.buffer.substring(this.pos, end);
}
hasChars(n) {
return this.pos + n <= this.buffer.length;
}
setNext(state) {
this.buffer = this.buffer.substring(this.pos);
this.pos = 0;
this.lineEndPos = null;
this.next = state;
return null;
}
peek(n) {
return this.buffer.substr(this.pos, n);
}
*parseNext(next) {
switch (next) {
case 'stream':
return yield* this.parseStream();
case 'line-start':
return yield* this.parseLineStart();
case 'block-start':
return yield* this.parseBlockStart();
case 'doc':
return yield* this.parseDocument();
case 'flow':
return yield* this.parseFlowCollection();
case 'quoted-scalar':
return yield* this.parseQuotedScalar();
case 'block-scalar':
return yield* this.parseBlockScalar();
case 'plain-scalar':
return yield* this.parsePlainScalar();
}
}
*parseStream() {
let line = this.getLine();
if (line === null)
return this.setNext('stream');
if (line[0] === cst.BOM) {
yield* this.pushCount(1);
line = line.substring(1);
}
if (line[0] === '%') {
let dirEnd = line.length;
const cs = line.indexOf('#');
if (cs !== -1) {
const ch = line[cs - 1];
if (ch === ' ' || ch === '\t')
dirEnd = cs - 1;
}
while (true) {
const ch = line[dirEnd - 1];
if (ch === ' ' || ch === '\t')
dirEnd -= 1;
else
break;
}
const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
yield* this.pushCount(line.length - n); // possible comment
this.pushNewline();
return 'stream';
}
if (this.atLineEnd()) {
const sp = yield* this.pushSpaces(true);
yield* this.pushCount(line.length - sp);
yield* this.pushNewline();
return 'stream';
}
yield cst.DOCUMENT;
return yield* this.parseLineStart();
}
*parseLineStart() {
const ch = this.charAt(0);
if (!ch && !this.atEnd)
return this.setNext('line-start');
if (ch === '-' || ch === '.') {
if (!this.atEnd && !this.hasChars(4))
return this.setNext('line-start');
const s = this.peek(3);
if (s === '---' && isEmpty(this.charAt(3))) {
yield* this.pushCount(3);
this.indentValue = 0;
this.indentNext = 0;
return 'doc';
}
else if (s === '...' && isEmpty(this.charAt(3))) {
yield* this.pushCount(3);
return 'stream';
}
}
this.indentValue = yield* this.pushSpaces(false);
if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
this.indentNext = this.indentValue;
return yield* this.parseBlockStart();
}
*parseBlockStart() {
const [ch0, ch1] = this.peek(2);
if (!ch1 && !this.atEnd)
return this.setNext('block-start');
if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) {
const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
this.indentNext = this.indentValue + 1;
this.indentValue += n;
return yield* this.parseBlockStart();
}
return 'doc';
}
*parseDocument() {
yield* this.pushSpaces(true);
const line = this.getLine();
if (line === null)
return this.setNext('doc');
let n = yield* this.pushIndicators();
switch (line[n]) {
case '#':
yield* this.pushCount(line.length - n);
// fallthrough
case undefined:
yield* this.pushNewline();
return yield* this.parseLineStart();
case '{':
case '[':
yield* this.pushCount(1);
this.flowKey = false;
this.flowLevel = 1;
return 'flow';
case '}':
case ']':
// this is an error
yield* this.pushCount(1);
return 'doc';
case '*':
yield* this.pushUntil(isNotAnchorChar);
return 'doc';
case '"':
case "'":
return yield* this.parseQuotedScalar();
case '|':
case '>':
n += yield* this.parseBlockScalarHeader();
n += yield* this.pushSpaces(true);
yield* this.pushCount(line.length - n);
yield* this.pushNewline();
return yield* this.parseBlockScalar();
default:
return yield* this.parsePlainScalar();
}
}
*parseFlowCollection() {
let nl, sp;
let indent = -1;
do {
nl = yield* this.pushNewline();
if (nl > 0) {
sp = yield* this.pushSpaces(false);
this.indentValue = indent = sp;
}
else {
sp = 0;
}
sp += yield* this.pushSpaces(true);
} while (nl + sp > 0);
const line = this.getLine();
if (line === null)
return this.setNext('flow');
if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') ||
(indent === 0 &&
(line.startsWith('---') || line.startsWith('...')) &&
isEmpty(line[3]))) {
// Allowing for the terminal ] or } at the same (rather than greater)
// indent level as the initial [ or { is technically invalid, but
// failing here would be surprising to users.
const atFlowEndMarker = indent === this.indentNext - 1 &&
this.flowLevel === 1 &&
(line[0] === ']' || line[0] === '}');
if (!atFlowEndMarker) {
// this is an error
this.flowLevel = 0;
yield cst.FLOW_END;
return yield* this.parseLineStart();
}
}
let n = 0;
while (line[n] === ',') {
n += yield* this.pushCount(1);
n += yield* this.pushSpaces(true);
this.flowKey = false;
}
n += yield* this.pushIndicators();
switch (line[n]) {
case undefined:
return 'flow';
case '#':
yield* this.pushCount(line.length - n);
return 'flow';
case '{':
case '[':
yield* this.pushCount(1);
this.flowKey = false;
this.flowLevel += 1;
return 'flow';
case '}':
case ']':
yield* this.pushCount(1);
this.flowKey = true;
this.flowLevel -= 1;
return this.flowLevel ? 'flow' : 'doc';
case '*':
yield* this.pushUntil(isNotAnchorChar);
return 'flow';
case '"':
case "'":
this.flowKey = true;
return yield* this.parseQuotedScalar();
case ':': {
const next = this.charAt(1);
if (this.flowKey || isEmpty(next) || next === ',') {
this.flowKey = false;
yield* this.pushCount(1);
yield* this.pushSpaces(true);
return 'flow';
}
}
// fallthrough
default:
this.flowKey = false;
return yield* this.parsePlainScalar();
}
}
*parseQuotedScalar() {
const quote = this.charAt(0);
let end = this.buffer.indexOf(quote, this.pos + 1);
if (quote === "'") {
while (end !== -1 && this.buffer[end + 1] === "'")
end = this.buffer.indexOf("'", end + 2);
}
else {
// double-quote
while (end !== -1) {
let n = 0;
while (this.buffer[end - 1 - n] === '\\')
n += 1;
if (n % 2 === 0)
break;
end = this.buffer.indexOf('"', end + 1);
}
}
// Only looking for newlines within the quotes
const qb = this.buffer.substring(0, end);
let nl = qb.indexOf('\n', this.pos);
if (nl !== -1) {
while (nl !== -1) {
const cs = this.continueScalar(nl + 1);
if (cs === -1)
break;
nl = qb.indexOf('\n', cs);
}
if (nl !== -1) {
// this is an error caused by an unexpected unindent
end = nl - (qb[nl - 1] === '\r' ? 2 : 1);
}
}
if (end === -1) {
if (!this.atEnd)
return this.setNext('quoted-scalar');
end = this.buffer.length;
}
yield* this.pushToIndex(end + 1, false);
return this.flowLevel ? 'flow' : 'doc';
}
*parseBlockScalarHeader() {
this.blockScalarIndent = -1;
this.blockScalarKeep = false;
let i = this.pos;
while (true) {
const ch = this.buffer[++i];
if (ch === '+')
this.blockScalarKeep = true;
else if (ch > '0' && ch <= '9')
this.blockScalarIndent = Number(ch) - 1;
else if (ch !== '-')
break;
}
return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#');
}
*parseBlockScalar() {
let nl = this.pos - 1; // may be -1 if this.pos === 0
let indent = 0;
let ch;
loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) {
switch (ch) {
case ' ':
indent += 1;
break;
case '\n':
nl = i;
indent = 0;
break;
case '\r': {
const next = this.buffer[i + 1];
if (!next && !this.atEnd)
return this.setNext('block-scalar');
if (next === '\n')
break;
} // fallthrough
default:
break loop;
}
}
if (!ch && !this.atEnd)
return this.setNext('block-scalar');
if (indent >= this.indentNext) {
if (this.blockScalarIndent === -1)
this.indentNext = indent;
else
this.indentNext += this.blockScalarIndent;
do {
const cs = this.continueScalar(nl + 1);
if (cs === -1)
break;
nl = this.buffer.indexOf('\n', cs);
} while (nl !== -1);
if (nl === -1) {
if (!this.atEnd)
return this.setNext('block-scalar');
nl = this.buffer.length;
}
}
if (!this.blockScalarKeep) {
do {
let i = nl - 1;
let ch = this.buffer[i];
if (ch === '\r')
ch = this.buffer[--i];
const lastChar = i; // Drop the line if last char not more indented
while (ch === ' ' || ch === '\t')
ch = this.buffer[--i];
if (ch === '\n' && i >= this.pos && i + 1 + indent > lastChar)
nl = i;
else
break;
} while (true);
}
yield cst.SCALAR;
yield* this.pushToIndex(nl + 1, true);
return yield* this.parseLineStart();
}
*parsePlainScalar() {
const inFlow = this.flowLevel > 0;
let end = this.pos - 1;
let i = this.pos - 1;
let ch;
while ((ch = this.buffer[++i])) {
if (ch === ':') {
const next = this.buffer[i + 1];
if (isEmpty(next) || (inFlow && next === ','))
break;
end = i;
}
else if (isEmpty(ch)) {
let next = this.buffer[i + 1];
if (ch === '\r') {
if (next === '\n') {
i += 1;
ch = '\n';
next = this.buffer[i + 1];
}
else
end = i;
}
if (next === '#' || (inFlow && invalidFlowScalarChars.includes(next)))
break;
if (ch === '\n') {
const cs = this.continueScalar(i + 1);
if (cs === -1)
break;
i = Math.max(i, cs - 2); // to advance, but still account for ' #'
}
}
else {
if (inFlow && invalidFlowScalarChars.includes(ch))
break;
end = i;
}
}
if (!ch && !this.atEnd)
return this.setNext('plain-scalar');
yield cst.SCALAR;
yield* this.pushToIndex(end + 1, true);
return inFlow ? 'flow' : 'doc';
}
*pushCount(n) {
if (n > 0) {
yield this.buffer.substr(this.pos, n);
this.pos += n;
return n;
}
return 0;
}
*pushToIndex(i, allowEmpty) {
const s = this.buffer.slice(this.pos, i);
if (s) {
yield s;
this.pos += s.length;
return s.length;
}
else if (allowEmpty)
yield '';
return 0;
}
*pushIndicators() {
switch (this.charAt(0)) {
case '!':
return ((yield* this.pushTag()) +
(yield* this.pushSpaces(true)) +
(yield* this.pushIndicators()));
case '&':
return ((yield* this.pushUntil(isNotAnchorChar)) +
(yield* this.pushSpaces(true)) +
(yield* this.pushIndicators()));
case '-': // this is an error
case '?': // this is an error outside flow collections
case ':': {
const inFlow = this.flowLevel > 0;
const ch1 = this.charAt(1);
if (isEmpty(ch1) || (inFlow && invalidFlowScalarChars.includes(ch1))) {
if (!inFlow)
this.indentNext = this.indentValue + 1;
else if (this.flowKey)
this.flowKey = false;
return ((yield* this.pushCount(1)) +
(yield* this.pushSpaces(true)) +
(yield* this.pushIndicators()));
}
}
}
return 0;
}
*pushTag() {
if (this.charAt(1) === '<') {
let i = this.pos + 2;
let ch = this.buffer[i];
while (!isEmpty(ch) && ch !== '>')
ch = this.buffer[++i];
return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false);
}
else {
let i = this.pos + 1;
let ch = this.buffer[i];
while (ch) {
if (tagChars.includes(ch))
ch = this.buffer[++i];
else if (ch === '%' &&
hexDigits.includes(this.buffer[i + 1]) &&
hexDigits.includes(this.buffer[i + 2])) {
ch = this.buffer[(i += 3)];
}
else
break;
}
return yield* this.pushToIndex(i, false);
}
}
*pushNewline() {
const ch = this.buffer[this.pos];
if (ch === '\n')
return yield* this.pushCount(1);
else if (ch === '\r' && this.charAt(1) === '\n')
return yield* this.pushCount(2);
else
return 0;
}
*pushSpaces(allowTabs) {
let i = this.pos - 1;
let ch;
do {
ch = this.buffer[++i];
} while (ch === ' ' || (allowTabs && ch === '\t'));
const n = i - this.pos;
if (n > 0) {
yield this.buffer.substr(this.pos, n);
this.pos = i;
}
return n;
}
*pushUntil(test) {
let i = this.pos;
let ch = this.buffer[i];
while (!test(ch))
ch = this.buffer[++i];
return yield* this.pushToIndex(i, false);
}
} |
JavaScript | class PopReceipt {
constructor() {}
validate({ request = undefined }) {
const msg = QueueManager.getQueueAndMessage({
queueName: request.queueName,
messageId: request.messageId,
}).message;
if (msg.expirationTime < request.now) {
throw new AError(ErrorCodes.MessageNotFound);
}
}
} |
JavaScript | class PropertyInspectorProvider extends Widget {
/**
* Construct a new Property Inspector.
*/
constructor() {
super();
this._tracker = new FocusTracker();
this._inspectors = new Map();
this.addClass('jp-PropertyInspector');
this._tracker = new FocusTracker();
this._tracker.currentChanged.connect(this._onCurrentChanged, this);
}
/**
* Register a widget in the property inspector provider.
*
* @param widget The owner widget to register.
*/
register(widget) {
if (this._inspectors.has(widget)) {
throw new Error('Widget is already registered');
}
const inspector = new Private.PropertyInspector(widget);
widget.disposed.connect(this._onWidgetDisposed, this);
this._inspectors.set(widget, inspector);
inspector.onAction.connect(this._onInspectorAction, this);
this._tracker.add(widget);
return inspector;
}
/**
* The current widget being tracked by the inspector.
*/
get currentWidget() {
return this._tracker.currentWidget;
}
/**
* Refresh the content for the current widget.
*/
refresh() {
const current = this._tracker.currentWidget;
if (!current) {
this.setContent(null);
return;
}
const inspector = this._inspectors.get(current);
if (inspector) {
this.setContent(inspector.content);
}
}
/**
* Handle the disposal of a widget.
*/
_onWidgetDisposed(sender) {
const inspector = this._inspectors.get(sender);
if (inspector) {
inspector.dispose();
this._inspectors.delete(sender);
}
}
/**
* Handle inspector actions.
*/
_onInspectorAction(sender, action) {
const owner = sender.owner;
const current = this._tracker.currentWidget;
switch (action) {
case 'content':
if (current === owner) {
this.setContent(sender.content);
}
break;
case 'dispose':
if (owner) {
this._tracker.remove(owner);
this._inspectors.delete(owner);
}
break;
case 'show-panel':
if (current === owner) {
this.showPanel();
}
break;
default:
throw new Error('Unsupported inspector action');
}
}
/**
* Handle a change to the current widget in the tracker.
*/
_onCurrentChanged() {
const current = this._tracker.currentWidget;
if (current) {
const inspector = this._inspectors.get(current);
const content = inspector.content;
this.setContent(content);
}
else {
this.setContent(null);
}
}
} |
JavaScript | class SideBarPropertyInspectorProvider extends PropertyInspectorProvider {
/**
* Construct a new Side Bar Property Inspector.
*/
constructor(labshell, placeholder) {
super();
this._labshell = labshell;
const layout = (this.layout = new SingletonLayout());
if (placeholder) {
this._placeholder = placeholder;
}
else {
const node = document.createElement('div');
const content = document.createElement('div');
content.textContent = 'No properties to inspect.';
content.className = 'jp-PropertyInspector-placeholderContent';
node.appendChild(content);
this._placeholder = new Widget({ node });
this._placeholder.addClass('jp-PropertyInspector-placeholder');
}
layout.widget = this._placeholder;
labshell.currentChanged.connect(this._onShellCurrentChanged, this);
this._onShellCurrentChanged();
}
/**
* Set the content of the sidebar panel.
*/
setContent(content) {
const layout = this.layout;
if (layout.widget) {
layout.widget.removeClass('jp-PropertyInspector-content');
layout.removeWidget(layout.widget);
}
if (!content) {
content = this._placeholder;
}
content.addClass('jp-PropertyInspector-content');
layout.widget = content;
}
/**
* Show the sidebar panel.
*/
showPanel() {
this._labshell.activateById(this.id);
}
/**
* Handle the case when the current widget is not in our tracker.
*/
_onShellCurrentChanged() {
var _a;
const current = this.currentWidget;
if (!current) {
this.setContent(null);
return;
}
const currentShell = this._labshell.currentWidget;
if ((_a = currentShell) === null || _a === void 0 ? void 0 : _a.node.contains(current.node)) {
this.refresh();
}
else {
this.setContent(null);
}
}
} |
JavaScript | class PropertyInspector {
/**
* Construct a new property inspector.
*/
constructor(owner) {
this._isDisposed = false;
this._content = null;
this._owner = null;
this._onAction = new Signal(this);
this._owner = owner;
}
/**
* The owner widget for the property inspector.
*/
get owner() {
return this._owner;
}
/**
* The current content for the property inspector.
*/
get content() {
return this._content;
}
/**
* Whether the property inspector is disposed.
*/
get isDisposed() {
return this._isDisposed;
}
/**
* A signal used for actions related to the property inspector.
*/
get onAction() {
return this._onAction;
}
/**
* Show the property inspector panel.
*/
showPanel() {
if (this._isDisposed) {
return;
}
this._onAction.emit('show-panel');
}
/**
* Render the property inspector content.
*/
render(widget) {
if (this._isDisposed) {
return;
}
if (widget instanceof Widget) {
this._content = widget;
}
else {
this._content = ReactWidget.create(widget);
}
this._onAction.emit('content');
}
/**
* Dispose of the property inspector.
*/
dispose() {
if (this._isDisposed) {
return;
}
this._isDisposed = true;
this._content = null;
this._owner = null;
Signal.clearData(this);
}
} |
JavaScript | class TableBody extends Control {
/**
* @constructs
* @param {UI} parent
* @param {string} theme = ""
*/
constructor(parent, theme = "") {
super(parent, theme);
this.config(BGroup);
this.setAttribute("element-type", "TableBody");
this.setAttribute("element-name", "container");
}
} |
JavaScript | class DragSelect extends React.Component {
// When allowClick is false we discard zero-length drags. If true
// we will invoke onSelect with a zero-length selection.
static defaultProps = {enabled: () => true, allowClick: false};
componentWillMount() {
var mousedown = new Rx.Subject();
var mousedrag = mousedown.flatMap((down) => {
var target = down.currentTarget,
start = targetPos(target, down),
selection = this.props.allowClick ? getSelection(target, down, start) :
undefined;
return Rx.Observable.fromEvent(window, 'mousemove').map(function (mm) {
selection = getSelection(target, mm, start);
return {dragging: true, ...selection};
}).takeUntil(Rx.Observable.fromEvent(window, 'mouseup'))
.concat(Rx.Observable.defer(() => Rx.Observable.of({selection})));
});
this.subscription = mousedrag.subscribe(ev => {
var {dragging, ...selection} = ev;
if (dragging) {
this.props.onDrag && this.props.onDrag(selection);
}
if (ev.selection) {
this.props.onSelect && this.props.onSelect(ev.selection);
}
});
this.dragStart = ev => this.props.enabled(ev) && mousedown.next(ev);
}
componentWillUnmount() {
this.subscription.unsubscribe();
}
render() {
var containerProps = _.omit(this.props, 'onSelect', 'enabled', 'allowClick');
return (
<div {...containerProps} style={styles.wrapper} onMouseDown={this.dragStart}>
{this.props.children}
</div>);
}
} |
JavaScript | class Display extends Buffer {
#aspectRatio = null;
#maxWidth = null;
constructor(
{ canvas = null, width = 832, height = 640, color = 'transparent' } = {
canvas: null,
width: 832,
height: 640,
color: 'transparent',
}
) {
if (Display.instance) {
return Display.instance;
} else {
super({ canvas, width, height, color });
this.#maxWidth = width;
this.#aspectRatio = height / width;
this.#init();
Display.instance = this;
return this;
}
}
/**
* to initialize this display
* by just adding the required listeners
*/
#init() {
this.#resize();
window.addEventListener('keypress', (event) => {
if (event.code === 'KeyF') {
this.#toggleFullscreen();
}
});
window.addEventListener('resize', (e) => {
e.preventDefault();
if (!document.fullscreenElement) {
this.#resize();
}
});
}
/**
* to add the fullscreen functionality to this display
* using the fullscreen api
*/
#toggleFullscreen() {
if (!document.fullscreenElement) {
this.canvas.requestFullscreen();
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
}
}
}
/**
* to add resize functionality to this display
*/
#resize() {
const { innerWidth: width, innerHeight: height } = window;
let newWidth,
newHeight = 0;
if (height / width >= this.#aspectRatio) {
newWidth = width;
newHeight = width * this.#aspectRatio;
} else {
newWidth = height / this.#aspectRatio;
newHeight = height;
}
if (newWidth >= this.#maxWidth) {
this.canvas.width = this.#maxWidth;
this.canvas.height = this.#maxWidth * this.#aspectRatio;
} else {
this.canvas.width = newWidth;
this.canvas.height = newHeight;
}
}
} |
JavaScript | class Home extends React.Component {
static defaultProps = {
remoteJoinCode: ''
};
static propTypes = {
calendarError: PropTypes.any,
calendarService: PropTypes.object,
enableAutoUpdate: PropTypes.bool,
events: PropTypes.array,
hasFetchedEvents: PropTypes.bool,
history: PropTypes.object,
isSetupComplete: PropTypes.bool,
onGoToMeetingCommand: PropTypes.func,
onStartScreenshareMeeting: PropTypes.func,
onTimeWithinRangeUpdate: PropTypes.func,
productName: PropTypes.string,
remoteControlServer: PropTypes.object,
remoteJoinCode: PropTypes.string,
spotRoomName: PropTypes.string,
t: PropTypes.func
};
/**
* Initializes a new {@code Home} instance.
*
* @param {Object} props - The read-only properties with which the new
* instance is to be initialized.
*/
constructor(props) {
super(props);
this.state = {
calendarError: null
};
this._onCommand = this._onCommand.bind(this);
}
/**
* Registers listeners for updating the view's data and display.
*
* @inheritdoc
*/
componentDidMount() {
this.props.remoteControlServer.addListener(
SERVICE_UPDATES.CLIENT_MESSAGE_RECEIVED,
this._onCommand
);
}
/**
* Cleans up listeners for daemons and long-running updaters.
*
* @inheritdoc
*/
componentWillUnmount() {
this.props.remoteControlServer.removeListener(
SERVICE_UPDATES.CLIENT_MESSAGE_RECEIVED,
this._onCommand
);
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
*/
render() {
const {
isSetupComplete: _isSetupComplete,
spotRoomName
} = this.props;
return (
<WiredScreenshareChangeListener
onDeviceConnected = { this.props.onStartScreenshareMeeting }>
<div className = 'spot-home'>
<Clock />
<div className = 'room-name'>
{ spotRoomName && <div>{ spotRoomName }</div> }
</div>
<div className = 'calendar-content'>
{ this._getCalendarEventsView() }
</div>
{
_isSetupComplete
&& <div className = 'spot-home-footer'>
<JoinInfo showDomain = { _isSetupComplete } />
</div>
}
</div>
<div className = 'admin-toolbar'>
<SettingsButton />
</div>
<div className = 'home-feedback'>
<FeedbackOpener />
</div>
</WiredScreenshareChangeListener>
);
}
/**
* Returns the React Component which should be displayed for the list of
* calendars.
*
* @returns {ReactComponent|null}
*/
_getCalendarEventsView() {
if (!this.props.isSetupComplete) {
return this._renderSetupMessage();
}
if (this.props.calendarError) {
return this._renderError();
}
if (this.props.hasFetchedEvents) {
return this.props.events.length
? <ScheduledMeetings events = { this.props.events } />
: this._renderNoEventsMessage();
}
return <LoadingIcon />;
}
/**
* Listens for Spot-Remotes commanding this Spot-TV to enter a meeting.
*
* @param {string} type - The type of the command being sent.
* @param {Object} data - Additional data necessary to execute the command.
* @private
* @returns {void}
*/
_onCommand(type, data) {
switch (type) {
case COMMANDS.GO_TO_MEETING: {
this.props.onGoToMeetingCommand(data);
break;
}
}
}
/**
* Instantiates a React Element with a message stating calendar events could
* not be fetched.
*
* @private
* @returns {ReactElement}
*/
_renderError() {
const { t } = this.props;
return (
<div className = 'no-events-message'>
<div>{ t('calendar.errorGettingEvents') }</div>
<div> { t('calendar.retrySync') }</div>
</div>
);
}
/**
* Instantiates a React Element with a message stating there are no
* scheduled meetings on the calendar associated with the Spot-TV.
*
* @private
* @returns {ReactElement}
*/
_renderNoEventsMessage() {
const { t } = this.props;
return (
<div className = 'no-events-message'>
<div>{ t('calendar.noEvents') }</div>
<div>{ t('calendar.inviteThisRoom') }</div>
</div>
);
}
/**
* Instantiates a React Element with a message stating Spot-TV should have a
* calendar connected.
*
* @private
* @returns {ReactElement}
*/
_renderSetupMessage() {
const { productName, remoteJoinCode, t } = this.props;
return (
<div className = 'no-events-message'>
<h1>{ t('welcome', { productName }) }</h1>
<div className = 'setup-instructions'>
<div>{ t('calendar.setupHeader') }</div>
<div>{ t('calendar.setupHow') }</div>
</div>
{
remoteJoinCode
&& (
<div className = 'setup-join-code'>
<JoinInfo />
</div>
)
}
</div>
);
}
} |
JavaScript | class editFlight extends Component {
render() {
return (
<div>
"editFlights here - Gego brdo"
</div>
)
}
} |
JavaScript | class CtlPeer {
/**
* Constructs a new <code>CtlPeer</code>.
* @alias module:model/CtlPeer
* @class
*/
constructor() {
}
/**
* Constructs a <code>CtlPeer</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/CtlPeer} obj Optional instance to populate.
* @return {module:model/CtlPeer} The populated <code>CtlPeer</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new CtlPeer();
if (data.hasOwnProperty('Id')) {
obj['Id'] = ApiClient.convertToType(data['Id'], 'String');
}
if (data.hasOwnProperty('Address')) {
obj['Address'] = ApiClient.convertToType(data['Address'], 'String');
}
if (data.hasOwnProperty('Port')) {
obj['Port'] = ApiClient.convertToType(data['Port'], 'Number');
}
if (data.hasOwnProperty('Metadata')) {
obj['Metadata'] = ApiClient.convertToType(data['Metadata'], {'String': 'String'});
}
}
return obj;
}
/**
* @member {String} Id
*/
Id = undefined;
/**
* @member {String} Address
*/
Address = undefined;
/**
* @member {Number} Port
*/
Port = undefined;
/**
* @member {Object.<String, String>} Metadata
*/
Metadata = undefined;
} |
JavaScript | class ChopsTimestamp extends LitElement {
render() {
return html`
${this._displayedTime}
`;
}
static get properties() {
return {
/** The data for the time which can be in any format readable by
* Date.parse.
*/
timestamp: {type: String},
/** When true, a shorter version of the date will be displayed. */
short: {type: Boolean},
/** The Date object, which is stored in UTC, to be converted to a string. */
_date: {type: Object},
};
}
get _displayedTime() {
const date = this._date;
const short = this.short;
// TODO(zhangtiff): Add logic to dynamically re-compute relative time
// based on set intervals.
if (!date) return;
if (short) {
return standardTimeShort(date);
}
return standardTime(date);
}
update(changedProperties) {
if (changedProperties.has('timestamp')) {
this._date = this._parseTimestamp(this.timestamp);
this.setAttribute('title', standardTime(this._date));
}
super.update(changedProperties);
}
_parseTimestamp(timestamp) {
if (!timestamp) return;
let unixTimeMs = 0;
// Make sure to do Date.parse before Number.parseInt because parseInt
// will parse numbers within a string.
if (/^\d+$/.test(timestamp)) {
// Check if a string contains only digits before guessing it's
// unix time. This is necessary because Number.parseInt will parse
// number strings that contain non-numbers.
unixTimeMs = Number.parseInt(timestamp) * 1000;
} else {
// Date.parse will parse strings with only numbers as though those
// strings were truncated ISO formatted strings.
unixTimeMs = Date.parse(timestamp);
if (Number.isNaN(unixTimeMs)) {
throw new Error('Timestamp is in an invalid format.');
}
}
return new Date(unixTimeMs);
}
} |
JavaScript | class OverlayRenderer extends Renderer {
/**
* Instantiates a new OverlayRenderer object.
*/
constructor() {
super();
this.overlay = null;
}
/**
* Executed when the overlay is attached to a plot.
*
* @param {Overlay} overlay - The overlay to attach the renderer to.
*
* @returns {OverlayRenderer} The renderer object, for chaining.
*/
onAdd(overlay) {
if (!overlay) {
throw 'No overlay provided as argument';
}
this.overlay = overlay;
return this;
}
/**
* Executed when the overlay is removed from a plot.
*
* @param {Overlay} overlay - The overlay to remove the renderer from.
*
* @returns {OverlayRenderer} The renderer object, for chaining.
*/
onRemove(overlay) {
if (!overlay) {
throw 'No overlay provided as argument';
}
this.overlay = null;
return this;
}
} |
JavaScript | class ModuleSettings
{
/**
* Registers all module settings.
*
* @see {@link settings}
*/
static register()
{
game.settings.register(constants.moduleName, settings.allowPlayersDrag, {
name: 'ForienQuestLog.Settings.allowPlayersDrag.Enable',
hint: 'ForienQuestLog.Settings.allowPlayersDrag.EnableHint',
scope: scope.world,
config: true,
default: false,
type: Boolean,
onChange: () =>
{
// Must enrich all quests again in QuestDB.
QuestDB.enrichAll();
// Render all views; immediately stops / enables player drag if Quest view is open.
ViewManager.renderAll({ force: true, questPreview: true });
}
});
game.settings.register(constants.moduleName, settings.allowPlayersCreate, {
name: 'ForienQuestLog.Settings.allowPlayersCreate.Enable',
hint: 'ForienQuestLog.Settings.allowPlayersCreate.EnableHint',
scope: scope.world,
config: true,
default: false,
type: Boolean,
onChange: () =>
{
// Render quest log to show / hide add quest button.
if (ViewManager.questLog.rendered) { ViewManager.questLog.render(); }
}
});
game.settings.register(constants.moduleName, settings.allowPlayersAccept, {
name: 'ForienQuestLog.Settings.allowPlayersAccept.Enable',
hint: 'ForienQuestLog.Settings.allowPlayersAccept.EnableHint',
scope: scope.world,
config: true,
default: false,
type: Boolean,
onChange: () =>
{
// Must enrich all quests again in QuestDB.
QuestDB.enrichAll();
// Render all views as quest status actions need to be shown or hidden for some players.
ViewManager.renderAll({ questPreview: true });
}
});
game.settings.register(constants.moduleName, settings.trustedPlayerEdit, {
name: 'ForienQuestLog.Settings.trustedPlayerEdit.Enable',
hint: 'ForienQuestLog.Settings.trustedPlayerEdit.EnableHint',
scope: scope.world,
config: true,
default: false,
type: Boolean,
onChange: () =>
{
// Must perform a consistency check as there are possible quests that need to be added / removed
// from the in-memory DB based on trusted player edit status.
QuestDB.consistencyCheck();
// Render all views as trusted player edit adds / removes capabilities.
ViewManager.renderAll({ questPreview: true });
}
});
game.settings.register(constants.moduleName, settings.countHidden, {
name: 'ForienQuestLog.Settings.countHidden.Enable',
hint: 'ForienQuestLog.Settings.countHidden.EnableHint',
scope: scope.world,
config: true,
default: false,
type: Boolean,
onChange: () =>
{
// Must enrich all quests again in QuestDB.
QuestDB.enrichAll();
// Must render the quest log / floating quest log / quest tracker.
ViewManager.renderAll();
}
});
game.settings.register(constants.moduleName, settings.dynamicBookmarkBackground, {
name: 'ForienQuestLog.Settings.dynamicBookmarkBackground.Enable',
hint: 'ForienQuestLog.Settings.dynamicBookmarkBackground.EnableHint',
scope: scope.world,
config: true,
default: true,
type: Boolean,
onChange: () =>
{
// Must render the quest log.
if (ViewManager.questLog.rendered) { ViewManager.questLog.render(); }
}
});
// Currently provides a hidden setting to set the default abstract reward image.
// It may never be displayed in the module settings menu, but if it is in the future this is where it would go.
game.settings.register(constants.moduleName, settings.defaultAbstractRewardImage, {
scope: 'world',
config: false,
default: 'icons/svg/item-bag.svg',
type: String
});
game.settings.register(constants.moduleName, settings.navStyle, {
name: 'ForienQuestLog.Settings.navStyle.Enable',
hint: 'ForienQuestLog.Settings.navStyle.EnableHint',
scope: scope.client,
config: true,
default: 'bookmarks',
type: String,
choices: {
bookmarks: 'ForienQuestLog.Settings.navStyle.bookmarks',
classic: 'ForienQuestLog.Settings.navStyle.classic'
},
onChange: () =>
{
// Must enrich all quests again in QuestDB.
QuestDB.enrichAll();
// Must render the quest log.
if (ViewManager.questLog.rendered) { ViewManager.questLog.render(); }
}
});
game.settings.register(constants.moduleName, settings.showTasks, {
name: 'ForienQuestLog.Settings.showTasks.Enable',
hint: 'ForienQuestLog.Settings.showTasks.EnableHint',
scope: scope.world,
config: true,
default: 'default',
type: String,
choices: {
default: 'ForienQuestLog.Settings.showTasks.default',
onlyCurrent: 'ForienQuestLog.Settings.showTasks.onlyCurrent',
no: 'ForienQuestLog.Settings.showTasks.no'
},
onChange: () =>
{
// Must enrich all quests again in QuestDB.
QuestDB.enrichAll();
// Must render the quest log.
ViewManager.renderAll();
}
});
game.settings.register(constants.moduleName, settings.defaultPermission, {
name: 'ForienQuestLog.Settings.defaultPermissionLevel.Enable',
hint: 'ForienQuestLog.Settings.defaultPermissionLevel.EnableHint',
scope: scope.world,
config: true,
default: 'Observer',
type: String,
choices: {
OBSERVER: 'ForienQuestLog.Settings.defaultPermissionLevel.OBSERVER',
NONE: 'ForienQuestLog.Settings.defaultPermissionLevel.NONE',
OWNER: 'ForienQuestLog.Settings.defaultPermissionLevel.OWNER'
}
});
game.settings.register(constants.moduleName, settings.hideFQLFromPlayers, {
name: 'ForienQuestLog.Settings.hideFQLFromPlayers.Enable',
hint: 'ForienQuestLog.Settings.hideFQLFromPlayers.EnableHint',
scope: scope.world,
config: true,
default: false,
type: Boolean,
onChange: async(value) =>
{
if (!game.user.isGM)
{
// Hide all FQL apps from non GM user and remove the ui.controls for FQL.
if (value)
{
ViewManager.closeAll({ questPreview: true });
const notes = ui?.controls?.controls.find((c) => c.name === 'notes');
if (notes) { notes.tools = notes?.tools.filter((c) => !c.name.startsWith(constants.moduleName)); }
// Remove all quests from in-memory DB. This is required so that users can not retrieve quests
// from the QuestAPI or content links in Foundry resolve when FQL is hidden.
QuestDB.removeAll();
}
else
{
// Initialize QuestDB loading all quests that are currently observable for the user.
await QuestDB.init();
// Add back ui.controls
const notes = ui?.controls?.controls.find((c) => c.name === 'notes');
if (notes) { notes.tools.push(...noteControls); }
}
ui?.controls?.render(true);
}
// Render the journal to show / hide open quest log button & folder.
game?.journal?.render();
// Close or open the quest tracker based on active quests (users w/ FQL hidden will have no quests in
// QuestDB)
if (ViewManager.isQuestTrackerVisible())
{
ViewManager.questTracker.render(true, { focus: true });
}
else
{
ViewManager.questTracker.close();
}
}
});
game.settings.register(constants.moduleName, settings.notifyRewardDrop, {
name: 'ForienQuestLog.Settings.notifyRewardDrop.Enable',
hint: 'ForienQuestLog.Settings.notifyRewardDrop.EnableHint',
scope: scope.world,
config: true,
default: false,
type: Boolean,
});
game.settings.register(constants.moduleName, settings.showFolder, {
name: 'ForienQuestLog.Settings.showFolder.Enable',
hint: 'ForienQuestLog.Settings.showFolder.EnableHint',
scope: scope.world,
config: true,
default: false,
type: Boolean,
onChange: () => game.journal.render() // Render the journal to show / hide the quest folder.
});
game.settings.register(constants.moduleName, settings.questTrackerPosition, {
scope: scope.client,
config: false,
default: s_QUEST_TRACKER_DEFAULT,
});
game.settings.register(constants.moduleName, settings.enableQuestTracker, {
name: 'ForienQuestLog.WorkshopPUF.Settings.enableQuestTracker.name',
hint: 'ForienQuestLog.WorkshopPUF.Settings.enableQuestTracker.hint',
scope: scope.client,
config: true,
default: false,
type: Boolean,
onChange: () =>
{
// Show hide the quest tracker based on visible quests and this setting.
if (ViewManager.isQuestTrackerVisible())
{
ViewManager.questTracker.render(true, { focus: true });
}
else
{
ViewManager.questTracker.close();
}
}
});
game.settings.register(constants.moduleName, settings.questTrackerBackground, {
name: 'ForienQuestLog.WorkshopPUF.Settings.questTrackerBackground.name',
hint: 'ForienQuestLog.WorkshopPUF.Settings.questTrackerBackground.hint',
scope: scope.client,
config: true,
default: true,
type: Boolean,
onChange: (value) =>
{
// Toggle the background CSS class for the quest tracker.
if (ViewManager.questTracker.rendered)
{
ViewManager.questTracker.element.toggleClass('background', value);
}
}
});
game.settings.register(constants.moduleName, settings.resetQuestTracker, {
name: 'ForienQuestLog.WorkshopPUF.Settings.resetQuestTracker.name',
hint: 'ForienQuestLog.WorkshopPUF.Settings.resetQuestTracker.hint',
scope: scope.client,
config: true,
default: false,
type: Boolean,
onChange: (value) =>
{
if (value)
{
// Reset the quest tracker position.
game.settings.set(constants.moduleName, settings.questTrackerPosition, s_QUEST_TRACKER_DEFAULT);
game.settings.set(constants.moduleName, settings.resetQuestTracker, false);
if (ViewManager.questTracker.rendered)
{
ViewManager.questTracker.render();
}
}
}
});
}
} |
JavaScript | class Parser {
white () {
var ch = this.ch;
while (ch && ch <= ' ') {
ch = this.next();
}
return this.comment(ch)
}
/**
* Slurp any C or C++ style comments
*/
comment (ch) {
if (ch !== '/') { return ch }
var p = this.at;
var second = this.lookahead();
if (second === '/') {
while (ch) {
ch = this.next();
if (ch === '\n' || ch === '\r') { break }
}
ch = this.next();
} else if (second === '*') {
while (ch) {
ch = this.next();
if (ch === '*' && this.lookahead() === '/') {
this.next();
break
}
}
if (!ch) {
this.error('Unclosed comment, starting at character ' + p);
}
this.next();
return this.white()
}
return ch
};
next (c) {
if (c && c !== this.ch) {
this.error("Expected '" + c + "' but got '" + this.ch + "'");
}
this.ch = this.text.charAt(this.at);
this.at += 1;
return this.ch
}
lookahead () {
return this.text[this.at]
}
error (m) {
if (m instanceof Error) { throw m }
let [name, msg] = m.name ? [m.name, m.message] : [m, ''];
const message = `\n${name} ${msg} of
${this.text}\n` + Array(this.at).join(' ') + '_/ 🔥 \\_\n';
throw new Error(message)
}
name () {
// A name of a binding
var name = '';
var enclosedBy;
this.white();
var ch = this.ch;
if (ch === "'" || ch === '"') {
enclosedBy = ch;
ch = this.next();
}
while (ch) {
if (enclosedBy && ch === enclosedBy) {
this.white();
ch = this.next();
if (ch !== ':' && ch !== ',') {
this.error(
'Object name: ' + name + ' missing closing ' + enclosedBy
);
}
return name
} else if (ch === ':' || ch <= ' ' || ch === ',' || ch === '|') {
return name
}
name += ch;
ch = this.next();
}
return name
}
number () {
let number;
let string = '';
let ch = this.ch;
if (ch === '-') {
string = '-';
ch = this.next('-');
}
while (ch >= '0' && ch <= '9') {
string += ch;
ch = this.next();
}
if (ch === '.') {
string += '.';
ch = this.next();
while (ch && ch >= '0' && ch <= '9') {
string += ch;
ch = this.next();
}
}
if (ch === 'e' || ch === 'E') {
string += ch;
ch = this.next();
if (ch === '-' || ch === '+') {
string += ch;
ch = this.next();
}
while (ch >= '0' && ch <= '9') {
string += ch;
ch = this.next();
}
}
number = +string;
if (!isFinite(number)) {
options.onError(new Error('Bad number: ' + number + ' in ' + string));
} else {
return number
}
}
/**
* Add a property to 'object' that equals the given value.
* @param {Object} object The object to add the value to.
* @param {String} key object[key] is set to the given value.
* @param {mixed} value The value, may be a primitive or a function. If a
* function it is unwrapped as a property.
*/
objectAddValue (object, key, value) {
if (value && value[Node.isExpressionOrIdentifierSymbol]) {
Object.defineProperty(object, key, {
get: () => Node.value_of(value, ...this.currentContextGlobals),
enumerable: true
});
} else if (Array.isArray(value)) {
Object.defineProperty(object, key, {
get: () => value.map(v => Node.value_of(v, ...this.currentContextGlobals)),
enumerable: true
});
} else {
// primitives
object[key] = value;
}
}
object () {
let key;
let object = {};
let ch = this.ch;
if (ch === '{') {
this.next('{');
ch = this.white();
if (ch === '}') {
ch = this.next('}');
return object
}
while (ch) {
if (ch === '"' || ch === "'" || ch === '`') {
key = this.string();
} else {
key = this.name();
}
this.white();
ch = this.next(':');
if (Object.hasOwnProperty.call(object, key)) {
this.error('Duplicate key "' + key + '"');
}
this.objectAddValue(object, key, this.expression());
ch = this.white();
if (ch === '}') {
ch = this.next('}');
return object
}
this.next(',');
ch = this.white();
}
}
this.error('Bad object');
}
/**
* Read up to delim and return the string
* @param {string} delim The delimiter, either ' or "
* @return {string} The string read.
*/
readString (delim) {
let string = '';
let nodes = [''];
let plusOp = operators['+'];
let hex;
let i;
let uffff;
let interpolate = delim === '`';
let ch = this.next();
while (ch) {
if (ch === delim) {
ch = this.next();
if (interpolate) { nodes.push(plusOp); }
nodes.push(string);
return nodes
}
if (ch === '\\') {
ch = this.next();
if (ch === 'u') {
uffff = 0;
for (i = 0; i < 4; i += 1) {
hex = parseInt(ch = this.next(), 16);
if (!isFinite(hex)) {
break
}
uffff = uffff * 16 + hex;
}
string += String.fromCharCode(uffff);
} else if (typeof escapee[ch] === 'string') {
string += escapee[ch];
} else {
break
}
} else if (interpolate && ch === '$') {
ch = this.next();
if (ch === '{') {
this.next('{');
nodes.push(plusOp);
nodes.push(string);
nodes.push(plusOp);
nodes.push(this.expression());
string = '';
// this.next('}');
} else {
string += '$' + ch;
}
} else {
string += ch;
}
ch = this.next();
}
this.error('Bad string');
}
string () {
var ch = this.ch;
if (ch === '"') {
return this.readString('"').join('')
} else if (ch === "'") {
return this.readString("'").join('')
} else if (ch === '`') {
return Node.create_root(this.readString('`'))
}
this.error('Bad string');
}
array () {
let array = [];
let ch = this.ch;
if (ch === '[') {
ch = this.next('[');
this.white();
if (ch === ']') {
ch = this.next(']');
return array
}
while (ch) {
array.push(this.expression());
ch = this.white();
if (ch === ']') {
ch = this.next(']');
return array
}
this.next(',');
ch = this.white();
}
}
this.error('Bad array');
}
value () {
var ch;
this.white();
ch = this.ch;
switch (ch) {
case '{': return this.object()
case '[': return this.array()
case '"': case "'": case '`': return this.string()
case '-': return this.number()
default:
return ch >= '0' && ch <= '9' ? this.number() : this.identifier()
}
}
/**
* Get the function for the given operator.
* A `.precedence` value is added to the function, with increasing
* precedence having a higher number.
* @return {function} The function that performs the infix operation
*/
operator (opts) {
let op = '';
let opFn;
let ch = this.white();
let isIdentifierChar = Identifier.is_valid_start_char;
while (ch) {
if (isIdentifierChar(ch) || ch <= ' ' || ch === '' ||
ch === '"' || ch === "'" || ch === '{' || ch === '(' ||
ch === '`' || ch === ')' || (ch <= '9' && ch >= '0')) {
break
}
if (!opts.not_an_array && ch === '[') {
break
}
op += ch;
ch = this.next();
// An infix followed by the prefix e.g. a + @b
// TODO: other prefix unary operators
if (ch === '@') {
break
}
isIdentifierChar = Identifier.is_valid_continue_char;
}
if (op !== '') {
if (opts.prefix && op === '-') { op = '&-'; }
opFn = operators[op];
if (!opFn) {
this.error("Bad operator: '" + op + "'.");
}
}
return opFn
}
/**
* Filters
* Returns what the Node interprets as an "operator".
* e.g.
* <span data-bind="text: name | fit:20 | uppercase"></span>
*/
filter () {
let ch = this.next();
let args = [];
let nextFilter = function (v) { return v };
let name = this.name();
if (!options.filters[name]) {
options.onError('Cannot find filter by the name of: ' + name);
}
ch = this.white();
while (ch) {
if (ch === ':') {
ch = this.next();
args.push(this.expression('|'));
}
if (ch === '|') {
nextFilter = this.filter();
break
}
if (ch === ',') { break }
ch = this.white();
}
var filter = function filter (value, ignored, context, globals, node) {
var argValues = [value];
for (var i = 0, j = args.length; i < j; ++i) {
argValues.push(Node.value_of(args[i], context, globals, node));
}
return nextFilter(options.filters[name].apply(null, argValues))
};
// Lowest precedence.
filter.precedence = 1;
return filter
}
/**
* Parse an expression – builds an operator tree, in something like
* Shunting-Yard.
* See: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
*
* @return {function} A function that computes the value of the expression
* when called or a primitive.
*/
expression (filterable) {
let op;
let nodes = [];
let ch = this.white();
while (ch) {
// unary prefix operators
op = this.operator({ prefix: true });
if (op) {
nodes.push(undefined); // LHS Tree node.
nodes.push(op);
ch = this.white();
}
if (ch === '(') {
this.next();
nodes.push(this.expression());
this.next(')');
} else {
nodes.push(this.value());
}
ch = this.white();
if (ch === ':' || ch === '}' || ch === ',' || ch === ']' ||
ch === ')' || ch === '' || ch === '`' || (ch === '|' && filterable === '|')) {
break
}
// filters
if (ch === '|' && this.lookahead() !== '|' && filterable) {
nodes.push(this.filter());
nodes.push(undefined);
break
}
// infix or postfix operators
op = this.operator({ not_an_array: true });
if (op === operators['?']) {
this.ternary(nodes);
break
} else if (op === operators['.']) {
nodes.push(op);
nodes.push(this.member());
op = null;
} else if (op === operators['[']) {
nodes.push(op);
nodes.push(this.expression());
ch = this.next(']');
op = null;
} else if (op) {
nodes.push(op);
}
ch = this.white();
if (ch === ']' || (!op && ch === '(')) { break }
}
if (nodes.length === 0) {
return undefined
}
var dereferences = this.dereferences();
if (nodes.length === 1 && !dereferences.length) {
return nodes[0]
}
for (var i = 0, j = dereferences.length; i < j; ++i) {
var deref = dereferences[i];
if (deref.constructor === Arguments) {
nodes.push(operators.call);
} else {
nodes.push(operators['.']);
}
nodes.push(deref);
}
return new Expression(nodes)
}
ternary (nodes) {
var ternary = new Ternary();
ternary.yes = this.expression();
this.next(':');
ternary.no = this.expression();
nodes.push(operators['?']);
nodes.push(ternary);
}
/**
* Parse the arguments to a function, returning an Array.
*
*/
funcArguments () {
let args = [];
let ch = this.next('(');
while (ch) {
ch = this.white();
if (ch === ')') {
this.next(')');
return new Arguments(this, args)
} else {
args.push(this.expression());
ch = this.white();
}
if (ch !== ')') { this.next(','); }
}
this.error('Bad arguments to function');
}
/**
* The literal string reference `abc` in an `x.abc` expression.
*/
member () {
let member = '';
let ch = this.white();
let isIdentifierChar = Identifier.is_valid_start_char;
while (ch) {
if (!isIdentifierChar(ch)) {
break
}
member += ch;
ch = this.next();
isIdentifierChar = Identifier.is_valid_continue_char;
}
return member
}
/**
* A dereference applies to an identifer, being either a function
* call "()" or a membership lookup with square brackets "[member]".
* @return {fn or undefined} Dereference function to be applied to the
* Identifier
*/
dereference () {
let member;
let ch = this.white();
while (ch) {
if (ch === '(') {
// a(...) function call
return this.funcArguments()
} else if (ch === '[') {
// a[x] membership
this.next('[');
member = this.expression();
this.white();
this.next(']');
return member
} else if (ch === '.') {
// a.x membership
this.next('.');
return this.member()
} else {
break
}
}
}
dereferences () {
let ch = this.white();
let dereferences = [];
let deref;
while (ch) {
deref = this.dereference();
if (deref !== undefined) {
dereferences.push(deref);
} else {
break
}
}
return dereferences
}
identifier () {
let token = '';
let isIdentifierChar = Identifier.is_valid_start_char;
let ch = this.white();
while (ch) {
if (!isIdentifierChar(ch)) {
break
}
token += ch;
ch = this.next();
isIdentifierChar = Identifier.is_valid_continue_char;
}
switch (token) {
case 'true': return true
case 'false': return false
case 'null': return null
case 'undefined': return void 0
case 'function':
throw new Error('Knockout: Anonymous functions are no longer supported, but `=>` lambas are.')
// return this.anonymous_fn();
}
return new Identifier(this, token, this.dereferences())
}
readBindings () {
let key;
let bindings = {};
let sep;
let expr;
let ch = this.ch;
while (ch) {
key = this.name();
sep = this.white();
if (!sep || sep === ',') {
if (sep) {
ch = this.next(',');
} else {
ch = '';
}
// A "bare" binding e.g. "text"; substitute value of 'null'
// so it becomes "text: null".
bindings[key] = null;
} else {
if (key.indexOf('.') !== -1) {
// Namespaced – i.e.
// `attr.css: x` becomes `attr: { css: x }`
// ^^^ - key
key = key.split('.');
bindings[key[0]] = bindings[key[0]] || {};
if (key.length !== 2) {
options.onError('Binding ' + key + ' should have two parts (a.b).');
} else if (bindings[key[0]].constructor !== Object) {
options.onError('Binding ' + key[0] + '.' + key[1] + ' paired with a non-object.');
}
ch = this.next(':');
this.objectAddValue(bindings[key[0]], key[1], this.expression(true));
} else {
ch = this.next(':');
if (bindings[key] && typeof bindings[key] === 'object' && bindings[key].constructor === Object) {
// Extend a namespaced bindings e.g. we've previously seen
// on.x, now we're seeing on: { 'abc' }.
expr = this.expression(true);
if (typeof expr !== 'object' || expr.constructor !== Object) {
options.onError('Expected plain object for ' + key + ' value.');
} else {
extend(bindings[key], expr);
}
} else {
bindings[key] = this.expression(true);
}
}
this.white();
if (this.ch) {
ch = this.next(',');
} else {
ch = '';
}
}
}
return bindings
}
valueAsAccessor (value, context, globals, node) {
if (!value) { return () => value }
if (typeof value === 'function') { return value }
if (value[Node.isExpressionOrIdentifierSymbol]) {
return () => Node.value_of(value, context, globals, node)
}
if (Array.isArray(value)) {
return () => value.map(v => Node.value_of(v, context, globals, node))
}
if (typeof (value) !== 'function') {
return () => clonePlainObjectDeep(value)
}
throw new Error('Value has cannot be converted to accessor: ' + value)
}
/**
* Convert result[name] from a value to a function (i.e. `valueAccessor()`)
* @param {object} result [Map of top-level names to values]
* @return {object} [Map of top-level names to functions]
*
* Accessors may be one of (below) constAccessor, identifierAccessor,
* expressionAccessor, or nodeAccessor.
*/
convertToAccessors (result, context, globals, node) {
objectForEach(result, (name, value) => {
if (value instanceof Identifier) {
// Return a function that, with no arguments returns
// the value of the identifier, otherwise sets the
// value of the identifier to the first given argument.
Object.defineProperty(result, name, {
value: function (optionalValue, options$$1) {
const currentValue = value.get_value(undefined, context, globals, node);
if (arguments.length === 0) { return currentValue }
const unchanged = optionalValue === currentValue;
if (options$$1 && options$$1.onlyIfChanged && unchanged) { return }
return value.set_value(optionalValue, context, globals)
}
});
} else {
result[name] = this.valueAsAccessor(value, context, globals, node);
}
});
return result
}
runParse (source, fn) {
this.text = (source || '').trim();
this.at = 0;
this.ch = ' ';
try {
var result = fn();
this.white();
if (this.ch) {
this.error('Syntax Error');
}
return result
} catch (e) {
options.onError(e);
}
}
/**
* Get the bindings as name: accessor()
* @param {string} source The binding string to parse.
* @return {object} Map of name to accessor function.
*/
parse (source, context = {}, globals = {}, node) {
if (!source) { return () => null }
this.currentContextGlobals = [context, globals, node];
const parseFn = () => this.readBindings();
const bindingAccessors = this.runParse(source, parseFn);
return this.convertToAccessors(bindingAccessors, context, globals, node)
}
/**
* Return a function that evaluates and returns the result of the expression.
*/
parseExpression (source, context = {}, globals = {}, node) {
if (!source) { return () => '' }
this.currentContextGlobals = [context, globals, node];
const parseFn = () => this.expression(true);
const bindingAccessors = this.runParse(source, parseFn);
return this.valueAsAccessor(bindingAccessors, context, globals, node)
}
} |
JavaScript | class BindingHandlerObject {
constructor() {}
set(nameOrObject, value) {
if (typeof nameOrObject === 'string') {
this[nameOrObject] = value;
} else if (typeof nameOrObject === 'object') {
if (value !== undefined) {
options.onError(
new Error("Given extraneous `value` parameter (first param should be a string, but it was an object)." + nameOrObject));
}
Object.assign(this, nameOrObject);
} else {
options.onError(
new Error("Given a bad binding handler type: " + nameOrObject));
}
}
/**
* The handler may have a `.` in it, e.g. `attr.title`, in which case the
* handler is `attr`. Otherwise it's the name given
*/
get(nameOrDotted) {
const [name] = nameOrDotted.split('.');
return this[name]
}
} |
JavaScript | class BindingStringProvider extends Provider {
/** Call bindingHandler.preprocess on each respective binding string.
*
* The `preprocess` property of bindingHandler must be a static
* function (i.e. on the object or constructor).
*/
* processBinding (key, value) {
// Get the "on" binding from "on.click"
const [handlerName, property] = key.split('.');
const handler = this.bindingHandlers.get(handlerName);
if (handler && handler.preprocess) {
const bindingsAddedByHandler = [];
const chainFn = (...args) => bindingsAddedByHandler.push(args);
value = handler.preprocess(value, key, chainFn);
for (const [key, value] of bindingsAddedByHandler) {
yield * this.processBinding(key, value);
}
} else if (property) {
value = `{${property}:${value}}`;
}
yield `${handlerName}:${value}`;
}
* generateBindingString (bindingString) {
for (const {key, unknown, value} of parseObjectLiteral(bindingString)) {
yield * this.processBinding(key || unknown, value);
}
}
preProcessBindings (bindingString) {
return Array.from(this.generateBindingString(bindingString)).join(',')
}
getBindingAccessors (node, context) {
const bindingString = node && this.getBindingString(node);
if (!bindingString) { return }
const processed = this.preProcessBindings(bindingString);
return new Parser().parse(processed, context, this.globals, node)
}
getBindingString () { throw new Error('Overload getBindingString.') }
} |
JavaScript | class AttrProvider extends Provider {
get FOR_NODE_TYPES () { return [document.ELEMENT_NODE] }
get PREFIX () { return 'ko-' }
getBindingAttributesList (node) {
if (!node.hasAttributes()) { return [] }
return Array.from(node.attributes)
.filter(attr => attr.name.startsWith(this.PREFIX))
}
nodeHasBindings (node) {
return this.getBindingAttributesList(node).length > 0
}
getBindingAccessors (node, context) {
return Object.assign({}, ...this.handlersFromAttributes(node, context))
}
* handlersFromAttributes (node, context) {
for (const attr of this.getBindingAttributesList(node)) {
const name = attr.name.substr(this.PREFIX.length);
yield {[name]: () => this.getValue(attr.value, context, node)};
}
}
getValue (token, $context, node) {
/* FIXME: This duplicates Identifier.prototype.lookup_value; it should
be refactored into e.g. a BindingContext method */
if (!token) { return }
const $data = $context.$data;
switch (token) {
case '$element': return node
case '$context': return $context
case 'this': case '$data': return $context.$data
}
if ($data instanceof Object && token in $data) { return $data[token] }
if (token in $context) { return $context[token] }
if (token in this.globals) { return this.globals[token] }
throw new Error(`The variable '${token} not found.`)
}
} |
JavaScript | class AttributeMustacheProvider extends Provider {
get FOR_NODE_TYPES () { return [document.ELEMENT_NODE] }
constructor (params = {}) {
super(params);
this.ATTRIBUTES_TO_SKIP = new Set(params.attributesToSkip || ['data-bind']);
}
* attributesToInterpolate (attributes) {
for (const attr of Array.from(attributes)) {
if (this.ATTRIBUTES_TO_SKIP.has(attr.name)) { continue }
if (attr.specified && attr.value.includes('{{')) { yield attr; }
}
}
nodeHasBindings (node) {
return !this.attributesToInterpolate(node.attributes).next().done
}
partsTogether (parts, context, node, ...valueToWrite) {
if (parts.length > 1) {
return parts
.map(p => unwrap(p.asAttr(context, this.globals, node))).join('')
}
// It may be a writeable observable e.g. value="{{ value }}".
const part = parts[0].asAttr(context, this.globals);
if (valueToWrite.length) { part(valueToWrite[0]); }
return part
}
attributeBinding (name, parts) {
return [name, parts]
}
* bindingParts (node, context) {
for (const attr of this.attributesToInterpolate(node.attributes)) {
const parts = Array.from(parseInterpolation(attr.value));
if (parts.length) { yield this.attributeBinding(attr.name, parts); }
}
}
* bindingObjects (node, context) {
for (const [attrName, parts] of this.bindingParts(node, context)) {
const hasBinding = this.bindingHandlers.get(attrName);
const handler = hasBinding ? attrName : `attr.${attrName}`;
const accessorFn = hasBinding
? (...v) => this.partsTogether(parts, context, node, ...v)
: (...v) => ({[attrName]: this.partsTogether(parts, context, node, ...v)});
node.removeAttribute(attrName);
yield { [handler]: accessorFn };
}
}
getBindingAccessors (node, context) {
return Object.assign({}, ...this.bindingObjects(node, context))
}
} |
JavaScript | class AsyncBindingHandler extends BindingHandler {
constructor (params) {
super(params);
this.bindingCompletion = new options.Promise((resolve) => { this.completeBinding = resolve; });
}
get bindingCompleted () { return this.bindingCompletion }
} |
JavaScript | class ConditionalBindingHandler extends AsyncBindingHandler {
constructor (params) {
super(params);
this.hasElse = detectElse(this.$element);
const elseChainSatisfied = this.completesElseChain = observable();
set(this.$element, 'conditional', { elseChainSatisfied });
this.computed(this.render.bind(this));
}
get elseChainIsAlreadySatisfied () { return false }
get needsRefresh () {
return this.isFirstRender || this.shouldDisplayIf !== this.didDisplayOnLastUpdate
}
get shouldDisplayIf () { return !!unwrap(this.value) }
render () {
const isFirstRender = !this.ifElseNodes;
let shouldDisplayIf = this.shouldDisplayIf;
let needsRefresh = this.needsRefresh;
if (this.elseChainIsAlreadySatisfied) {
shouldDisplayIf = false;
needsRefresh = isFirstRender || this.didDisplayOnLastUpdate;
this.completesElseChain(true);
} else {
this.completesElseChain(this.shouldDisplayIf);
}
if (!needsRefresh) { return }
if (isFirstRender && (getDependenciesCount() || this.hasElse)) {
this.ifElseNodes = cloneIfElseNodes(this.$element, this.hasElse);
}
if (shouldDisplayIf) {
if (!isFirstRender || this.hasElse) {
setDomNodeChildren$1(this.$element, cloneNodes(this.ifElseNodes.ifNodes));
}
} else if (this.ifElseNodes) {
setDomNodeChildren$1(this.$element, cloneNodes(this.ifElseNodes.elseNodes));
} else {
emptyNode(this.$element);
}
applyBindingsToDescendants(this.bindingContext, this.$element)
.then(this.completeBinding);
this.didDisplayOnLastUpdate = shouldDisplayIf;
}
get bindingContext () { return this.$context }
get controlsDescendants () { return true }
static get allowVirtualElements () { return true }
} |
JavaScript | class WebGL2RenderTarget extends THREE.WebGLRenderTarget {
/** returns true if this is instance of WebGL2RenderTarget */
get isWebGL2RenderTarget() {
return true;
}
/** same as THREE.WebGLRenderTarget, supports option.multipleRenderTargets
* @param {number} same as THREE.WebGLRenderTarget
* @param {number} same as THREE.WebGLRenderTarget
* @param {object} same as THREE.WebGLRenderTarget. set { multipleRenderTargets:true, renderTargetCount:4 } to use MRT with specifyed texture number.
*/
constructor( width, height, options ) {
super( width, height, options );
// check support
if ( this.isWebGLRenderTargetCube )
throw new Error("WebGL2RenderTarget: Cube render target not supported");
// listen dispose event
this.addEventListener( 'dispose', this._onDispose.bind(this) );
// MRT settings
options = options || {};
/**
* flag to use multiple render targets
* @type {boolean}
*/
this.multipleRenderTargets = options.multipleRenderTargets || false;
/**
* render target count to use
* @type {int}
*/
this.renderTargetCount = options.renderTargetCount || 1;
/**
* array of THREE.Texture used for MRT, the length is WebGL2RenderTarget.renderTargetCount. the first element is WebGL2RenderTarget.texture
* @type {Array.<THREE.Texture>}
*/
this.textures = [this.texture];
// create textures
if (this.multipleRenderTargets)
for ( let i = 1; i < this.renderTargetCount; i++ )
this.textures.push(new THREE.Texture().copy(this.texture));
}
isPowerOfTwo() {
return ( THREE.Math.isPowerOfTwo( this.width ) && THREE.Math.isPowerOfTwo( this.height ) );
}
_onDispose( event ) {
console.warn("WebGL2RenderTarget: dispose not impelented.");
}
_setupIfNeeded( renderer ) {
const gl = renderer._context;
const renderTargetProperties = renderer.properties.get( this );
//
if (renderTargetProperties.__webglFramebuffer)
return;
// check render target capacity
if ( this.renderTargetCount > gl.getParameter(gl.MAX_DRAW_BUFFERS) )
throw new Error("WebGL2RenderTarget: renderTargetCount is over system capacity. " + gl.getParameter(gl.MAX_DRAW_BUFFERS) + " buffers @ max.");
// create new framebuffer
renderTargetProperties.__webglFramebuffer = gl.createFramebuffer();
// setup color buffer
if ( this.multipleRenderTargets ) {
// create webgl textures
for ( let i = 0; i < this.renderTargetCount; i++ )
this._setupColorBuffer( renderer, this.textures[i], i, renderTargetProperties.__webglFramebuffer );
// draw buffers
gl.bindFramebuffer(gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
gl.drawBuffers(this.textures.map(( texture, i )=>( gl.COLOR_ATTACHMENT0 + i)));
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
} else {
this._setupColorBuffer( renderer, this.texture, 0, renderTargetProperties.__webglFramebuffer );
}
renderer.state.bindTexture( gl.TEXTURE_2D, null );
// Setup depth and stencil buffers
if ( this.depthBuffer )
this._setupDepthRenderbuffer(renderer);
}
_setupColorBuffer( renderer, texture, attachIndex, framebuffer ) {
const gl = renderer._context,
webGLTexture = gl.createTexture(),
textureProperties = renderer.properties.get( texture );
// create webgl texture
textureProperties.__webglTexture = webGLTexture;
renderer.info.memory.textures ++;
// setup color buffer
renderer.state.bindTexture( gl.TEXTURE_2D, webGLTexture );
this._setTextureParameters( gl, gl.TEXTURE_2D, texture );
this._setupFrameBufferTexture( renderer, framebuffer, gl.COLOR_ATTACHMENT0 + attachIndex, gl.TEXTURE_2D, webGLTexture );
// create mipmap if required
if ( texture.generateMipmaps && this.isPowerOfTwo() &&
texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter )
this._generateMipmap( renderer, gl.TEXTURE_2D, texture, this.width, this.height );
}
_setTextureParameters( gl, textureType, texture ) {
// from WebGLTextures.js
const wrappingToGL = {
[ THREE.RepeatWrapping ]: gl.REPEAT,
[ THREE.ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
[ THREE.MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
};
const filterToGL = {
[ THREE.NearestFilter ]: gl.NEAREST,
[ THREE.NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
[ THREE.NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
[ THREE.LinearFilter ]: gl.LINEAR,
[ THREE.LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
[ THREE.LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
};
if (this.isPowerOfTwo()) {
gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping )
console.warn( 'THREE.WebGL2Renderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
if (texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter )
console.warn( 'THREE.WebGL2Renderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
} else {
gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
}
gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
}
_setupFrameBufferTexture( renderer, framebuffer, attachment, textureTarget, texture ) {
const utils = WebGL2Renderer._utils,
gl = renderer._context,
glFormat = utils.convert( this.texture.format ),
glType = utils.convert( this.texture.type ),
glInternalFormat = this._getInternalFormat( renderer, glFormat, glType );
renderer.state.texImage2D( textureTarget, 0, glInternalFormat, this.width, this.height, 0, glFormat, glType, null );
gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, textureTarget, texture, 0 );
gl.bindFramebuffer( gl.FRAMEBUFFER, null );
}
_generateMipmap( renderer, target, texture, width, height ) {
renderer._context.generateMipmap( target );
const textureProperties = renderer.properties.get( texture );
textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
}
_setupDepthRenderbuffer( renderer ) {
const gl = renderer._context,
renderTargetProperties = renderer.properties.get( this );
gl.bindFramebuffer( gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
if ( this.depthTexture ) {
this._setupDepthTexture( renderer, renderTargetProperties.__webglFramebuffer );
} else {
renderTargetProperties.__webglDepthbuffer = gl.createRenderbuffer();
this._setupRenderBufferStorage( renderer, renderTargetProperties.__webglDepthbuffer );
}
gl.bindFramebuffer( gl.FRAMEBUFFER, null );
}
_getInternalFormat( renderer, glFormat, glType ) {
const gl = renderer._context;
let prop = "";
if ( glFormat === gl.RED ) prop = "R";
else if ( glFormat === gl.RGB ) prop = "RGB";
else if ( glFormat === gl.RGBA ) prop = "RGBA";
else return glFormat;
if ( glType === gl.FLOAT ) prop += "32F";
else if ( glType === gl.HALF_FLOAT ) prop += "16F";
else if ( glType === gl.UNSIGNED_BYTE ) prop += "8";
else return glFormat;
return renderer._context[prop];
}
_setupDepthTexture( renderer, framebuffer ) {
const gl = renderer._context;
if ( ! ( this.depthTexture && this.depthTexture.isDepthTexture ) )
throw new Error( 'this.depthTexture must be an instance of THREE.DepthTexture' );
// upload an empty depth texture with framebuffer size
if ( ! renderer.properties.get( this.depthTexture ).__webglTexture ||
this.depthTexture.image.width !== this.width ||
this.depthTexture.image.height !== this.height ) {
this.depthTexture.image.width = this.width;
this.depthTexture.image.height = this.height;
this.depthTexture.needsUpdate = true;
}
renderer.setTexture2D( this.depthTexture, 0 );
const webglDepthTexture = properties.get( this.depthTexture ).__webglTexture;
if ( this.depthTexture.format === THREE.DepthFormat )
gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, webglDepthTexture, 0 );
else if ( this.depthTexture.format === THREE.DepthStencilFormat )
gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, webglDepthTexture, 0 );
else
throw new Error( 'Unknown depthTexture format' );
}
_setupRenderBufferStorage( renderer, renderbuffer ) {
const gl = renderer._context;
gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
if ( this.depthBuffer && ! this.stencilBuffer ) {
gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, this.width, this.height );
gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
} else if ( this.depthBuffer && this.stencilBuffer ) {
gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, this.width, this.height );
gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
} else {
// FIXME: We don't support !depth !stencil
gl.renderbufferStorage( gl.RENDERBUFFER, gl.RGBA4, this.width, this.height );
}
gl.bindRenderbuffer( gl.RENDERBUFFER, null );
}
} |
JavaScript | class ClickElement extends BaseElementCommand {
get extraArgsCount() {
return 0;
}
get elementProtocolAction() {
return 'clickElement';
}
} |
JavaScript | class StatusServicoProcessor {
constructor(empresa, ambiente, modelo, webProxy) {
this.empresa = empresa;
this.ambiente = ambiente;
this.modelo = modelo;
this.webProxy = webProxy;
}
async processarDocumento() {
let xml = this.gerarXmlStatusServico('4.00', this.ambiente, this.empresa.endereco.cUf);
return await this.consultarStatusServico(xml, this.empresa.certificado);
}
async consultarStatusServico(xml, cert) {
let Sefaz = this.modelo == '65' ? sefazNfce_1.SefazNFCe : sefazNfe_1.SefazNFe;
let soap = Sefaz.getSoapInfo(this.empresa.endereco.uf, this.ambiente, nfe_1.ServicosSefaz.consultarStatusServico);
return await webserviceHelper_1.WebServiceHelper.makeSoapRequest(xml, cert, soap, this.webProxy);
}
gerarXmlStatusServico(versao, ambiente, cUf) {
let status = {
$: {
versao: versao,
xmlns: 'http://www.portalfiscal.inf.br/nfe'
},
tpAmb: Utils.getEnumByValue(schema.TAmb, ambiente),
cUF: Utils.getEnumByValue(schema.TCodUfIBGE, cUf),
xServ: schema.TConsStatServXServ.STATUS
};
return xmlHelper_1.XmlHelper.serializeXml(status, 'consStatServ');
}
} |
JavaScript | class MapGroundOverlay {
constructor(_map, _ngZone) {
this._map = _map;
this._ngZone = _ngZone;
this._eventManager = new MapEventManager(this._ngZone);
this._opacity = new BehaviorSubject(1);
this._url = new BehaviorSubject('');
this._destroyed = new Subject();
/** Whether the overlay is clickable */
this.clickable = false;
/**
* See
* developers.google.com/maps/documentation/javascript/reference/image-overlay#GroundOverlay.click
*/
this.mapClick = this._eventManager.getLazyEmitter('click');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/image-overlay
* #GroundOverlay.dblclick
*/
this.mapDblclick = this._eventManager.getLazyEmitter('dblclick');
}
/** URL of the image that will be shown in the overlay. */
set url(url) {
this._url.next(url);
}
/** Opacity of the overlay. */
set opacity(opacity) {
this._opacity.next(opacity);
}
ngOnInit() {
if (!this.bounds) {
throw Error('Image bounds are required');
}
if (this._map._isBrowser) {
this._combineOptions().pipe(take(1)).subscribe(options => {
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this._ngZone.runOutsideAngular(() => {
this.groundOverlay =
new google.maps.GroundOverlay(this._url.getValue(), this.bounds, options);
});
this._assertInitialized();
this.groundOverlay.setMap(this._map.googleMap);
this._eventManager.setTarget(this.groundOverlay);
});
this._watchForOpacityChanges();
this._watchForUrlChanges();
}
}
ngOnDestroy() {
this._eventManager.destroy();
this._destroyed.next();
this._destroyed.complete();
if (this.groundOverlay) {
this.groundOverlay.setMap(null);
}
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/image-overlay
* #GroundOverlay.getBounds
*/
getBounds() {
this._assertInitialized();
return this.groundOverlay.getBounds();
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/image-overlay
* #GroundOverlay.getOpacity
*/
getOpacity() {
this._assertInitialized();
return this.groundOverlay.getOpacity();
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/image-overlay
* #GroundOverlay.getUrl
*/
getUrl() {
this._assertInitialized();
return this.groundOverlay.getUrl();
}
_combineOptions() {
return this._opacity.pipe(map(opacity => {
const combinedOptions = {
clickable: this.clickable,
opacity,
};
return combinedOptions;
}));
}
_watchForOpacityChanges() {
this._opacity.pipe(takeUntil(this._destroyed)).subscribe(opacity => {
if (opacity) {
this._assertInitialized();
this.groundOverlay.setOpacity(opacity);
}
});
}
_watchForUrlChanges() {
this._url.pipe(takeUntil(this._destroyed)).subscribe(url => {
this._assertInitialized();
const overlay = this.groundOverlay;
overlay.set('url', url);
// Google Maps only redraws the overlay if we re-set the map.
overlay.setMap(null);
overlay.setMap(this._map.googleMap);
});
}
_assertInitialized() {
if (!this._map.googleMap) {
throw Error('Cannot access Google Map information before the API has been initialized. ' +
'Please wait for the API to load before trying to interact with it.');
}
if (!this.groundOverlay) {
throw Error('Cannot interact with a Google Map GroundOverlay before it has been initialized. ' +
'Please wait for the GroundOverlay to load before trying to interact with it.');
}
}
} |
JavaScript | class DatasourceRouter {
constructor(options) {
let urlData = options && options.urlData || new UrlData();
this._baseLength = urlData.baseURLPath.length - 1;
}
// Extracts the data source parameter from the request and adds it to the query
extractQueryParams(request, query) {
(query.features || (query.features = {})).datasource = true;
let path = request.url && request.url.pathname || '/';
query.datasource = path.substr(this._baseLength);
}
} |
JavaScript | class TotalStatisticsCapability extends Capability {
/**
* The amount and type of stuff returned here depends on the robots implementation
*
* @return {Promise<Array<ValetudoDataPoint>>}
*/
async getStatistics() {
throw new NotImplementedError();
}
getType() {
return TotalStatisticsCapability.TYPE;
}
} |
JavaScript | class DSChannelAsService {
/**
* @param {DSChannel} channel
*/
constructor (channel) {
this._emitter = new DSEventEmitter()
this._channel = channel
this._key = undefined
this._users = new Map() // user id to user
this._keys = new Map() // user id to key
this._onMessageReceived = (...args) => this._handleMessage(...args).then()
}
get events () {
return this._emitter
}
/**
* Join the service by broadcasting a joining message.
*/
async join (key) {
this._key = key
this._channel.events.on('message-received', this._onMessageReceived)
await this._channel.join()
const data = JSON.stringify({ type: 'join', data: key.data })
await this._channel.send(new DSMessage(data))
}
/**
* Leave the service by broadcasting a leaving message.
*/
async leave () {
this._channel.events.off('message-received', this._onMessageReceived)
const data = JSON.stringify({ type: 'left' })
await this._channel.send(new DSMessage(data))
await this._channel.leave()
}
/**
* Submit our key by broadcasting it through the channel.
*/
async submit (key) {
this._key = key
const data = JSON.stringify({ type: 'reset', data: key.data })
await this._channel.send(new DSMessage(data))
}
/**
* Obtain key for an already seen user.
*/
async obtain (of) {
return this._keys.get(of.id)
}
async send (message, to) {
message.data = JSON.stringify({ type: 'message', data: message.data })
await this._channel.send(message, to)
}
/**
* Welcome a user by sending them our key.
* @param {DSUser} user
*/
async _welcome (user) {
const data = JSON.stringify({ type: 'welcome', data: this._key.data })
await this._channel.send(new DSMessage(data), user)
}
/**
* Take decision based on the type of the message.
* @param {DSUser} from
* @param {DSMessage} message
*/
async _handleMessage (from, message) {
const { type, data } = JSON.parse(message.data)
if (type === 'message') {
message.data = data
this._emitter.emit('message-received', from, message)
} else if (type === 'join') {
// send our key again so that the new user can know about us
await this._welcome(from)
const key = new DSKey(data)
this._keys.set(from.id, key)
this._users.set(from.id, from)
this._emitter.emit('user-join', from, key)
} else if (type === 'welcome') {
const key = new DSKey(data)
this._keys.set(from.id, key)
this._users.set(from.id, from)
this._emitter.emit('user-seen', from, key)
} else if (type === 'reset') {
if (this._users.has(from.id)) {
const key = new DSKey(data)
this._keys.set(from.id, key)
this._emitter.emit('user-reset', from, key)
}
} else if (type === 'left') {
if (this._users.has(from.id)) {
this._keys.delete(from.id)
this._users.delete(from.id)
this._emitter.emit('user-left', from)
}
} else {
console.log(`User ${from.id} might be in the wrong channel.`)
}
}
} |
JavaScript | class DecoratedComponent extends React.Component {
static displayName = `Form(${Component.displayName})`
constructor(props) {
// This needs to be in the constructor because we may want to fetch
// default text values based on props
super(props);
const initialValues = Map(setup.values).map((value, k) => {
if (typeof value === 'function') {
return new ValidatingValue(value(props));
} else if (typeof value === 'object' && value !== null) {
return new ValidatingValue(value);
}
throw new Error(`the value "${k}" must be either an object or a function that returns an object`);
});
this.state = {
values: initialValues,
};
}
render() {
const getValueForKey = (key) => this.state.values.get(key);
const changeValueForKey = (key) => (event) => {
this.setState({
values: this.state.values.setIn([key, 'text'], event.target.value).setIn([key, 'shouldValidate'], false),
});
};
const checkForValidValues = (keys = Set()) => {
return Q.Promise((resolve, reject) => {
const values = this.state.values.map(value => value.set('shouldValidate', true));
const valuesToCheck = keys.count() ?
values.filter((_, k) => keys.has(k)) :
values;
const error = getFirstErrorInMap(valuesToCheck);
// This sets the state of the `ValidatingValue`s to shouldValidate
this.setState({
values,
}, () => {
if (error) {
reject(error);
} else {
resolve(valuesToCheck.map(value => transformValidatingValue(value)));
}
});
});
};
return <Component
{...this.props}
checkForValidValues={checkForValidValues}
getValueForKey={getValueForKey}
changeValueForKey={changeValueForKey}
/>;
}
} |
JavaScript | class LinksTransformer {
constructor(links) {
this.links = links
}
async element(element) {
const newContent = this.links.map(link => `<a href=${link.url}>${link.name}</a>`).join("")
element.setInnerContent(newContent, {html:true})
}
} |
JavaScript | class ProfileTransformer {
async element(element) {
element.setAttribute("style", "")
}
} |
JavaScript | class AvatarTransformer {
async element(element) {
element.setAttribute("src", "https://zumaad.me/images/profile.png")
}
} |
JavaScript | class SocialLinksTransformer {
constructor(links) {
this.links = links
}
async element(element) {
element.setAttribute("style", "")
const newContent = this.links.map(link => `<a href=${link.url}>${link.name}<img src=${link.svg}></a>`).join("")
element.setInnerContent(newContent, {html:true})
}
} |
JavaScript | class BodyTransformer {
async element(element) {
element.setAttribute("style","background-color:green")
}
} |
JavaScript | class Engineer extends Employee {
constructor (name, id, email, github) {
//Inherited properties from the parent employee class
super (name, id, email);
this.github = github;
//Define the role as engineer
this.role = "Engineer";
}
//getGithub method on engineer returns the user-inputeted github user name
getGithub () {
return this.github;
}
//getRole return the engineer role from the instance of the engineer class
getRole () {
return this.role;
}
} |
JavaScript | class IonFormWizardStepComponent {
constructor(parent) {
this.parent = parent;
// console.log('Hello IonFormWizardStepComponent Component');
}
} |
JavaScript | class DefaultMatcher {
static compare(lastResult, newResult) {
// array
if(Array.isArray(lastResult) && Array.isArray(newResult)) {
return shallowEqualsArray(lastResult, newResult);
}
// set
if(lastResult instanceof Set && newResult instanceof Set) {
return shallowEqualsSet(lastResult, newResult);
}
// map
if(lastResult instanceof Map && newResult instanceof Map) {
return shallowEqualsMap(lastResult, newResult);
}
return lastResult === newResult;
}
static store(result) {
// array
if(Array.isArray(result)) {
return Array.prototype.slice.call(result);
}
// set
if(result instanceof Set) {
return new Set(result);
}
// map
if(result instanceof Map) {
return new Map(result);
}
return result;
}
} |
JavaScript | class BaseActiveExpression {
/**
*
* @param func (Function) the expression to be observed
* #TODO: incorrect parameter list, how to specify spread arguments in jsdoc?
* @param ...params (Objects) the instances bound as parameters to the expression
*/
constructor(func, { params = [], match, errorMode = 'silent', location } = {}) {
this._eventTarget = new EventTarget(),
this.func = func;
this.params = params;
this.errorMode = errorMode;
this.setupMatcher(match);
this._initLastValue();
this.callbacks = [];
// this.allCallbacks = new Map();
this._isDisposed = false;
this._shouldDisposeOnLastCallbackDetached = false;
this._annotations = new Annotations();
if(location){this.meta({location})};
this.initializeEvents();
this.logEvent('created');
if(new.target === BaseActiveExpression) {
this.addToRegistry();
}
}
_initLastValue() {
const { value, isError } = this.evaluateToCurrentValue();
if (!isError) {
this.storeResult(value);
} else {
this.lastValue = NO_VALUE_YET;
}
}
addToRegistry() {
AExprRegistry.addAExpr(this);
}
hasCallbacks() {
return this.callbacks.length !== 0;
}
/**
* Executes the encapsulated expression with the given parameters.
* aliases with 'now' (#TODO: caution, consider ambigous terminology: 'now' as in 'give me the value' or as in 'dataflow'?)
* @private
* @returns {*} the current value of the expression
*/
getCurrentValue() {
return this.func(...this.params);
}
/**
* Safely executes the encapsulated expression with the given parameters.
* @public
* @returns {{ value: *, isError: Boolean}} the current value of the expression, or the thrown error if any
*/
evaluateToCurrentValue() {
try {
const result = this.getCurrentValue();
return { value: result, isError: false };
} catch (e) {
return { value: e, isError: true };
}
}
/*MD ## EventTarget Interface MD*/
on(type, callback) {
this._eventTarget.addEventListener(type, callback);
return this;
}
off(type, callback) {
this._eventTarget.removeEventListener(type, callback);
return this;
}
emit(type, ...params) {
this._eventTarget.dispatchEvent(type, ...params);
}
getEventListeners(type) {
return this._eventTarget.getEventListeners(type);
}
/*MD ## --- MD*/
/**
* @public
* @param callback
* @returns {BaseActiveExpression} this very active expression (for chaining)
*/
onChange(callback) {
this.callbacks.push(callback);
this.logEvent('dependencies changed', 'Added: '+callback);
AExprRegistry.updateAExpr(this);
return this;
}
/**
* @public
* @param callback
* @returns {BaseActiveExpression} this very active expression (for chaining)
*/
// #TODO: should this remove all occurences of the callback?
offChange(callback) {
const index = this.callbacks.indexOf(callback);
if (index > -1) {
this.callbacks.splice(index, 1);
this.logEvent('dependencies changed', 'Removed: '+callback);
AExprRegistry.updateAExpr(this);
}
if (this._shouldDisposeOnLastCallbackDetached && this.callbacks.length === 0) {
this.dispose();
}
return this;
}
/**
* Signals the active expression that a state change might have happened.
* Mainly for implementation strategies.
* @public
*/
checkAndNotify() {
const { value, isError } = this.evaluateToCurrentValue();
if(isError || this.compareResults(this.lastValue, value)) { return; }
const lastValue = this.lastValue;
this.storeResult(value);
this.logEvent('changed value', value);
this.notify(value, {
lastValue,
expr: this.func ,
aexpr: this
});
}
setupMatcher(matchConfig) {
// configure using existing matcher
if(matchConfig && isString.call(matchConfig)) {
if(!MATCHER_MAP.has(matchConfig)) {
throw new Error(`No matcher of type '${matchConfig}' registered.`)
}
this.matcher = MATCHER_MAP.get(matchConfig);
return;
}
// configure using a custom matcher
if(typeof matchConfig === 'object') {
if(matchConfig.hasOwnProperty('compare') && matchConfig.hasOwnProperty('store')) {
this.matcher = matchConfig;
return;
}
throw new Error(`Given matcher object does not provide 'compare' and 'store' methods.`)
}
// use smart default matcher
this.matcher = DefaultMatcher;
}
// #TODO: extract into CompareAndStore classes
compareResults(lastResult, newResult) {
try {
window.__compareAExprResults__ = true;
return this.matcher.compare(lastResult, newResult);
} finally {
window.__compareAExprResults__ = false;
}
}
storeResult(result) {
try {
window.__compareAExprResults__ = true;
this.lastValue = this.matcher.store(result);
} finally {
window.__compareAExprResults__ = false;
}
}
notify(...args) {
this.callbacks.forEach(callback => callback(...args));
AExprRegistry.updateAExpr(this);
}
onBecomeTrue(callback) {
// setup dependency
this.onChange(bool => {
if(bool) {
callback();
}
});
// check initial state
const { value, isError } = this.evaluateToCurrentValue();
if (!isError && value) { callback(); }
return this;
}
onBecomeFalse(callback) {
// setup dependency
this.onChange(bool => {
if(!bool) {
callback();
}
});
// check initial state
const { value, isError } = this.evaluateToCurrentValue();
if(!isError && !value) { callback(); }
return this;
}
dataflow(callback) {
// setup dependency
this.onChange(callback);
// call immediately
// #TODO: duplicated code: we should extract this call
const { value, isError } = this.evaluateToCurrentValue();
if (!isError) {
callback(value, {});
}
return this;
}
/*MD ## Disposing MD*/
dispose() {
if (!this._isDisposed) {
this._isDisposed = true;
AExprRegistry.removeAExpr(this);
this.emit('dispose');
this.logEvent('disposed');
}
}
isDisposed() {
return this._isDisposed;
}
/**
* #TODO: implement
* disposeOnLastCallbackDetached
* chainable
* for some auto-cleanup
* (only triggers, when a callback is detached; not initially, if there are no callbacks)
*/
disposeOnLastCallbackDetached() {
this._shouldDisposeOnLastCallbackDetached = true;
return this;
}
/*MD ## Reflection Information MD*/
meta(annotation) {
if(annotation) {
this._annotations.add(annotation);
return this;
} else {
return this._annotations;
}
}
supportsDependencies() {
return false;
}
initializeEvents() {
this.meta({events : new Array()});
}
logEvent(type, value) {
if(this.isMeta())return;
//if(!this.meta().has('events'))this.meta({events : new Array()});
let events = this.meta().get('events');
events.push({timestamp: new Date(), type, value});
if(events.length > 5000)events.shift();
}
isMeta(value) {
if(value !== undefined)this.meta({isMeta : value});
else return this.meta().has('isMeta') && this.meta().get('isMeta');
}
} |
JavaScript | class CPUPlayer extends Player {
constructor(spriteSheet, x, y, design, team, playerNo, characterSwitch) {
super(spriteSheet, x, y, design, team, playerNo, characterSwitch);
this.firstUpdate = true;
this.playerToTarget = null;
this.timeIntoTurn = 0;
this.isInTurn = false;
this.firedProjectile = null;
this.projectileLandingPoint = null;
}
update(world, controls, deltaT) {
Player.prototype.update.call(this, world, controls, deltaT);
}
updateInputs(world, controls, deltaT) {
this.isShooting = false;
if (this.firstUpdate &&
(!this.playerToTarget || !this.playerToTarget.isActive)) {
// Update the position of the fired projectile to keep track of
// the landing point
if (this.firedProjectile) {
if (this.firedProjectile.active == false) {
this.projectileLandingPoint = new Point(this.firedProjectile.x,
this.firedProjectile.y);
this.firedProjectile = null;
}
}
this.playerToTarget = this.pickPlayerTarget(world);
this.firstUpdate = false;
this.timeIntoTurn = 0;
//this.angle = Math.PI * (3/4) + Math.PI * (1/4) * Math.random();
let deltaX = (this.playerToTarget.x - this.x);
if (deltaX > 0) {
this.angle = Math.PI * (1/4);
} else {
this.angle = Math.PI * (3/4);
}
this.power = 500;
console.log(this.angle);
this.startingX = this.x
}
this.timeIntoTurn += deltaT;
if (this.onGround) {
this.airTimer = 0;
} else {
this.airTimer += deltaT * 100;
}
// Start turn logic
if (this.timeIntoTurn < 2) {
// Move stage
if (this.vel.x == 0) {
// Pick which direction to walk in but don't walk off the edge
if (this.x + 100 > world.map.width) {
this.vel.x = -this.WALK_SPEED;
} else if (this.x - 100 < 0) {
this.vel.x = this.WALK_SPEED;
} else {
this.vel.x = Math.sign(Math.random() - 0.5) * this.WALK_SPEED;
}
} else if (this.vel.x > 0) {
this.shootingAngle.updateQuadrant(1);
} else {
this.shootingAngle.updateQuadrant(0);
}
this.vel.x = Math.sign(this.vel.x) * this.WALK_SPEED;
} else if (this.timeIntoTurn < 4) {
// Aim stage
this.vel.x = 0;
this.acc.x = 0;
// Was our last shot far or near?
if (this.projectileLandingPoint) {
// Keep track of how far the player has moved
this.projectileLandingPoint += this.startingX - this.x;
let missDistance = Math.abs(this.projectileLandingPoint.x - this.playerToTarget.x);
// Adjust by a certain amount depending on how off the last shot was
if (missDistance > 500) {
var powerChange = 400;
var angleChange = Math.PI / 32;
} else if (missDistance > 250) {
var powerChange = 300;
var angleChange = Math.PI / 32;
} else if (missDistance > 100) {
var powerChange = 200;
var angleChange = Math.PI / 32;
} else if (missDistance > 50) {
var powerChange = 100;
var angleChange = Math.PI / 64;
} else {
var angleChange = 0;
var powerChange = 50;
}
if (this.projectileLandingPoint.x > this.playerToTarget.x) {
if (this.x > this.playerToTarget.x) {
// We shot to the left and were a little short
if (this.shootingAngle.supplementaryAngle > Math.PI / 4){
// If we are angling upword a little bit then let's aim down
this.angle -= angleChange;
this.power += powerChange;
} else {
// If we are angling downword a little bit then let's aim up
this.angle += angleChange;
this.power += powerChange;
}
} else {
// We shot to the right and were a little far
if (this.shootingAngle.supplementaryAngle > Math.PI / 4){
// If we are angling upword a little bit then let's aim more up
this.angle -= angleChange;
this.power -= powerChange;
} else {
// If we are angling downword a little bit then let's aim more down
this.angle += angleChange;
this.power -= powerChange;
}
}
} else {
if (this.x > this.playerToTarget.x) {
// We shot to the left and were a little far
if (this.shootingAngle.supplementaryAngle > Math.PI / 4){
// If we are angling upword a little bit then let's aim more up
this.angle -= angleChange;
this.power -= powerChange;
} else {
// If we are angling downword a little bit then let's aim more down
this.angle += angleChange;
this.power -= powerChange;
}
} else {
// We shot to the right and were a little short
if (this.shootingAngle.supplementaryAngle > Math.PI / 4){
// If we are angling upword a little bit then let's aim more up
this.angle += angleChange;
this.power += powerChange;
} else {
// If we are angling downword a little bit then let's aim more down
this.angle -= angleChange;
this.power += powerChange;
}
}
}
this.projectileLandingPoint = null;
} else {
// First shot settings
}
let deltaX = (this.playerToTarget.x - this.x);
if (deltaX > 0) {
this.shootingAngle.updateQuadrant(1);
this.facing = 0;
} else {
this.shootingAngle.updateQuadrant(0);
this.facing = 1;
}
if (this.facing == 1) {
var deltaAngle = this.angle - this.shootingAngle.radians;
} else {
var deltaAngle = this.angle - this.shootingAngle.radians;
}
if (deltaAngle > 0) {
this.shootingAngle.increaseAngle()
} else if (deltaAngle < 0) {
this.shootingAngle.decreaseAngle()
}
} else {
this.currentWeapon.setIndex(Math.round(Math.random()))
ShootingPower.power = this.power;
this.firedProjectile = this.currentWeapon.spawnCurrentWeapon(this.x - 10, this.y - 10, this.shootingAngle);
world.spawn(this.firedProjectile);
ShootingPower.reset()
this.isInTurn = false;
this.firstUpdate = true;
}
// End turn logic
}
pickPlayerTarget(world){
let otherPlayers = world.players.filter((player) => this.team != player.team);
return otherPlayers[Math.floor(Math.random() * otherPlayers.length)];
}
} |
JavaScript | class Worker {
constructor ( name, options ) {
this.options = options || {};
this.ipcListener = new IpcListener();
_.defaultsDeep(options, {
workerType: 'renderer',
url: '',
});
}
/**
* @method start
* @param {object} argv
* @param {function} cb
*
* Starts the worker
*/
start ( argv, cb ) {
if ( typeof argv === 'function' ) {
cb = argv;
argv = undefined;
}
if ( this.options.workerType === 'renderer' ) {
this.nativeWin = new BrowserWindow({
width: 0,
height: 0,
show: false,
});
this.nativeWin.on('closed', () => {
this.ipcListener.clear();
this.dispose();
});
this.nativeWin.webContents.on('dom-ready', () => {
if ( cb ) {
cb ();
}
});
this._load( this.options.url, argv );
}
}
/**
* @method close
*
* Close the worker
*/
close () {
if ( this.options.workerType === 'renderer' ) {
this.nativeWin.close();
}
}
/**
* @method on
* @param {string} message
* @param {...} args
*
* Listen to the ipc mesage come from renderer
*/
on (...args) {
if ( this.options.workerType === 'renderer' ) {
this.ipcListener.on.apply(this.ipcListener, args);
}
}
/**
* @method dispose
*
* Dereference the native window.
*/
dispose () {
// NOTE: Important to dereference the window object to allow for GC
this.nativeWin = null;
}
_load ( editorUrl, argv ) {
let resultUrl = Protocol.url(editorUrl);
if ( !resultUrl ) {
Console.error( `Failed to load page ${editorUrl} for window "${this.name}"` );
return;
}
this._loaded = false;
let argvHash = argv ? encodeURIComponent(JSON.stringify(argv)) : undefined;
let url = resultUrl;
// if this is an exists local file
if ( Fs.existsSync(resultUrl) ) {
url = Url.format({
protocol: 'file',
pathname: resultUrl,
slashes: true,
hash: argvHash
});
this._url = url;
this.nativeWin.loadURL(url);
return;
}
// otherwise we treat it as a normal url
if ( argvHash ) {
url = `${resultUrl}#${argvHash}`;
}
this._url = url;
this.nativeWin.loadURL(url);
}
} |
JavaScript | class MatchCondition {
/**
* Create a MatchCondition.
* @property {array} matchVariables List of match variables
* @property {string} operator Describes operator to be matched. Possible
* values include: 'IPMatch', 'Equal', 'Contains', 'LessThan', 'GreaterThan',
* 'LessThanOrEqual', 'GreaterThanOrEqual', 'BeginsWith', 'EndsWith', 'Regex'
* @property {boolean} [negationConditon] Describes if this is negate
* condition or not
* @property {array} matchValues Match value
* @property {array} [transforms] List of transforms
*/
constructor() {
}
/**
* Defines the metadata of MatchCondition
*
* @returns {object} metadata of MatchCondition
*
*/
mapper() {
return {
required: false,
serializedName: 'MatchCondition',
type: {
name: 'Composite',
className: 'MatchCondition',
modelProperties: {
matchVariables: {
required: true,
serializedName: 'matchVariables',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'MatchVariableElementType',
type: {
name: 'Composite',
className: 'MatchVariable'
}
}
}
},
operator: {
required: true,
serializedName: 'operator',
type: {
name: 'String'
}
},
negationConditon: {
required: false,
serializedName: 'negationConditon',
type: {
name: 'Boolean'
}
},
matchValues: {
required: true,
serializedName: 'matchValues',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
transforms: {
required: false,
serializedName: 'transforms',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'WebApplicationFirewallTransformElementType',
type: {
name: 'String'
}
}
}
}
}
}
};
}
} |
JavaScript | class Textfield extends Component {
constructor(props) {
super(props);
this.theme = getTheme();
this.inputRef = createRef();
this.labelRef = createRef();
this.underlineRef = createRef();
this._onTextChange = (text) => {
this.bufferedValue = text;
this._callback('onTextChange', text);
this._callback('onChangeText', text);
};
this._onFocus = (e) => {
this._aniStartHighlight(true);
this._callback('onFocus', e);
};
this._onBlur = (e) => {
this._aniStopHighlight();
this._callback('onBlur', e);
};
this._doMeasurement = () => {
if (this.inputRef.current) {
this.inputRef.current.measure(this._onInputMeasured);
}
if (this.props.floatingLabelEnabled && this.labelRef.current) {
this.labelRef.current.measure(this._onLabelMeasured);
}
};
this._onLabelMeasured = (left, top, width, height) => {
this.setState({ inputMarginTop: height });
};
this._onInputMeasured = (left, top, width, height) => {
Object.assign(this.inputFrame, { left, top, width, height });
if (this.underlineRef.current) {
this.underlineRef.current.updateLineLength(width, () => {
if (this.bufferedValue || this.isFocused()) {
this._aniStartHighlight(this.isFocused()); // if input not empty, lift the label
}
});
}
};
this.inputFrame = { left: 0, top: 0, width: 0, height: 0 };
this.state = {
inputMarginTop: 0,
};
}
set bufferedValue(v) {
this._bufferedValue = v;
if (v) {
this._aniFloatLabel();
}
}
get bufferedValue() {
return (this._bufferedValue || '').trim();
}
set placeholder(placeholder) {
this.inputRef.current &&
this.inputRef.current.setNativeProps({
placeholder,
text: this._bufferedValue,
});
}
/**
* Requests focus for the given input or view. The exact behavior triggered
* will depend on the platform and type of view.
*/
focus() {
this.inputRef.current && this.inputRef.current.focus();
}
/**
* Checks if the input is currently focused.
*/
isFocused() {
return (this.inputRef.current && this.inputRef.current.isFocused()) === true;
}
/**
* Removes focus from an input or view. This is the opposite of `focus()`.
*/
blur() {
this.inputRef.current && this.inputRef.current.blur();
}
UNSAFE_componentWillMount() {
this.bufferedValue = this.props.value || this.props.defaultValue;
}
UNSAFE_componentWillReceiveProps(nextProps) {
const newText = nextProps.value || nextProps.defaultValue;
if (newText) {
this.bufferedValue = newText;
}
if (nextProps.value) {
this.bufferedValue = nextProps.value;
}
else if (nextProps.defaultValue && this.props.defaultValue !== nextProps.defaultValue) {
// use defaultValue if it's changed
this.bufferedValue = nextProps.defaultValue;
}
}
componentDidMount() {
requestAnimationFrame(this._doMeasurement);
}
render() {
const tfTheme = this.theme.textfieldStyle;
const floatingLabel = this.props.floatingLabelEnabled ? (<FloatingLabel ref={this.labelRef} {...this.props} label={this.props.placeholder} tint={this.props.tint || tfTheme.tintColor} highlightColor={this.props.highlightColor || tfTheme.highlightColor} floatingLabelFont={this.props.floatingLabelFont || tfTheme.floatingLabelFont}/>) : null;
const underline = (<Underline ref={this.underlineRef} {...this.props} tint={this.props.tint || tfTheme.tintColor} highlightColor={this.props.highlightColor || tfTheme.highlightColor} underlineAniDur={this.props.floatingLabelAniDuration}/>);
return (<View style={this.props.style} onLayout={this._doMeasurement}>
{floatingLabel}
<TextInput ref={this.inputRef} {...this.props} {...this.props.additionalInputProps} style={[
{
backgroundColor: MKColor.Transparent,
alignSelf: 'stretch',
paddingTop: 2,
paddingBottom: 2,
marginTop: this.state.inputMarginTop,
},
tfTheme.textInputStyle,
this.props.textInputStyle,
]} onChangeText={this._onTextChange} onFocus={this._onFocus} onBlur={this._onBlur} secureTextEntry={this.props.password} underlineColorAndroid="transparent"/>
{underline}
</View>);
}
startAnimations(animations, cb) {
if (animations.length) {
this.anim && this.anim.stop();
this.anim = Animated.parallel(animations);
this.anim.start(cb);
}
}
_aniFloatLabel() {
if (this.bufferedValue && this.props.floatingLabelEnabled && this.labelRef.current) {
this.startAnimations(this.labelRef.current.aniFloatLabel());
}
}
// animation when textfield focused
_aniStartHighlight(focused) {
if (this.props.floatingLabelEnabled) {
// hide fixed placeholder, if floating
this.placeholder = '';
// and show floating label
// FIXME workaround https://github.com/facebook/react-native/issues/3220
if (this.labelRef.current) {
this.labelRef.current.updateLabel(this.props.placeholder || '');
}
}
if (this.underlineRef.current && this.labelRef.current) {
this.startAnimations([
...this.underlineRef.current.aniStretchUnderline(focused),
...this.labelRef.current.aniFloatLabel(),
]);
}
}
// animation when textfield lost focus
_aniStopHighlight() {
if (this.underlineRef.current && this.labelRef.current) {
const onEnd = () => {
if (this.props.floatingLabelEnabled) {
// show fixed placeholder after floating label collapsed
this.placeholder = this.props.placeholder || '';
// and hide floating label
// FIXME workaround https://github.com/facebook/react-native/issues/3220
if (!this.bufferedValue && this.labelRef.current) {
this.labelRef.current.updateLabel('');
}
}
};
this.startAnimations([
...this.underlineRef.current.aniShrinkUnderline(),
...(!this.bufferedValue ? this.labelRef.current.aniSinkLabel() : []),
], onEnd);
}
}
_callback(prop, evt) {
const props = this.props;
props[prop] && props[prop](evt);
}
} |
JavaScript | class ContentElementTypeRegistry {
constructor() {
this.types = {};
}
/**
* Register a new type of content element.
*
* @param {string} typeName - Name of the content element type.
* @param {Object} options
* @param {React.Component} options.component
* @param {boolean} [options.supportsWrappingAroundFloats] -
* In sections with centered layout, content elements can be
* floated to the left or right. By default all content
* elements are cleared to position them below floating
* elements. If a content element renders mainly text that
* can wrap around floating elements, clearing can be
* disabled via this option.
* @memberof frontend_contentElementTypes
*
* @example
*
* // frontend.js
*
* import {frontend} from 'pageflow-scrolled/frontend';
* import {InlineImage} from './InlineImage';
*
* frontend.contentElementTypes.register('inlineImage', {
* component: InlineImage
* });
*/
register(typeName, options) {
this.types[typeName] = options;
}
getComponent(typeName) {
return this.types[typeName] && this.types[typeName].component;
}
getOptions(typeName) {
return this.types[typeName];
}
consentVendors({contentElements, t}) {
const vendorsByName = {};
contentElements.forEach((contentElement) => {
const type = this.types[contentElement.typeName];
const consentVendors =
typeof type.consentVendors === 'function' ?
type.consentVendors({
configuration: contentElement.configuration,
t
}) :
type.consentVendors || [];
consentVendors.forEach(vendor => {
vendorsByName[vendor.name] = vendor;
});
});
return Object.values(vendorsByName);
}
} |
JavaScript | class ResourceLink {
/**
* Constructor
*
* @param {Object} attributes Attributes
*/
constructor(attributes) {
this.attributes = new Attributes(attributes, DEFAULT_ATTRIBUTES);
}
/**
* Get id
*
* @return {string} Id
*/
get id() {
return this.attributes.get('id');
}
/**
* Get name
*
* @return {string} Name
*/
get name() {
return this.attributes.get('name');
}
/**
* Set name
*
* @param {string} name Name
*/
set name(name) {
this.attributes.set('name', String(name));
}
/**
* Get description
*
* @return {string} Description
*/
get description() {
return this.attributes.get('description');
}
/**
* Set description
*
* @param {string} description Description
*/
set description(description) {
this.attributes.set('description', String(description));
}
/**
* Get type
*
* @return {string} Type
*/
get type() {
return this.attributes.get('type');
}
/**
* Get class id
*
* @return {int} Class Id
*/
get classId() {
return this.attributes.get('classid');
}
/**
* Set class id
*
* @param {string} classId Class Id
*/
set classId(classId) {
this.attributes.set('classid', Number(classId));
}
/**
* Get owner
*
* @return {string} Owner
*/
get owner() {
return this.attributes.get('owner');
}
/**
* Get recycle
*
* @return {bool} Recycle
*/
get recycle() {
return this.attributes.get('recycle');
}
/**
* Set recycle
*
* @param {bool} value True to automatically delete on no reference
*/
set recycle(value) {
this.attributes.set('recycle', Boolean(value));
}
/**
* Get links
*
* @return {array} List of resource paths
*/
get links() {
return this.attributes.get('links');
}
/**
* Set links
*
* @param {array} links List of resource paths
*/
set links(links) {
this.attributes.set('links', links);
}
/**
* To string
*
* @return {string} Id
*/
toString() {
return this.id;
}
} |
JavaScript | class NavbarMain extends Crisp.View {
constructor(params) {
super(params);
HashBrown.Helpers.EventHelper.on('resource', 'navbar', () => { this.reload(); });
HashBrown.Helpers.EventHelper.on('route', 'navbar', () => { this.updateHighlight(); });
$('.page--environment__space--nav').html(this.$element);
this.fetch();
}
/**
* Updates the highlight state
*/
updateHighlight() {
let resourceCategory = location.hash.match(/\#\/([a-z]+)\//)[1];
if(!resourceCategory) { return; }
this.showTab('/' + resourceCategory + '/');
let resourceItem = Crisp.Router.params.id;
if(resourceItem) {
let pane = this.getCurrentPaneInstance();
if(pane) {
pane.highlightItem(resourceItem);
}
}
}
/**
* Gets the current pane
*
* @return {HashBrown.Views.Navigation.NavbarPane} Pane
*/
getCurrentPaneInstance() {
return Crisp.View.get(HashBrown.Views.Navigation.NavbarPane);
}
/**
* Gets a pane by route
*
* @param {String} route
*
* @return {HashBrown.Views.Navigation.NavbarPane} Pane
*/
getPaneByRoute(route) {
for(let pane of this.getPanes()) {
if(pane.route === route) {
return pane;
}
}
return null;
}
/**
* Gets all panes
*
* @return {Array} Panes
*/
getPanes() {
let panes = [];
for(let name in HashBrown.Views.Navigation) {
let pane = HashBrown.Views.Navigation[name];
if(pane.scope && !HashBrown.Context.user.hasScope(pane.scope)) { continue; }
if(pane.prototype instanceof HashBrown.Views.Navigation.NavbarPane) {
panes.push(pane);
}
}
return panes;
}
/**
* Toggles the tab buttons
*
* @param {Boolean} isActive
*/
toggleTabButtons(isActive) {
this.$element.toggleClass('hide-tabs', !isActive);
}
/**
* Shows a tab
*
* @param {String} tabName
*/
showTab(tabRoute) {
for(let element of Array.from(this.element.querySelectorAll('.navbar-main__tab'))) {
element.classList.toggle('active', element.getAttribute('href') === '#' + tabRoute);
}
let oldPaneInstance = this.getCurrentPaneInstance();
let newPaneConstructor = this.getPaneByRoute(tabRoute);
if(oldPaneInstance && oldPaneInstance.constructor === newPaneConstructor) { return; }
let $panes = _.find('.navbar-main__panes');
_.replace($panes[0], new newPaneConstructor());
}
/**
* Flags an item in the bar as loading
*
* @param {String} category
* @param {String} id
*/
async setItemLoading(category, id) {
checkParam(category, 'category', String, true);
checkParam(id, 'id', String, true);
let pane = this.getCurrentPaneInstance();
if(!pane || '/' + category + '/' !== pane.constructor.route) { return; }
let element = pane.getItemElement(id);
if(!element) { return; }
element.classList.toggle('loading', true);
}
/**
* Reloads this view
*/
async reload() {
let pane = this.getCurrentPaneInstance();
if(!pane) { return; }
await pane.reload();
this.updateHighlight();
}
/**
* Static version of the setItemLoading method
*
* @param {String} category
* @param {String} id
*/
static setItemLoading(category, id) {
checkParam(category, 'category', String, true);
checkParam(id, 'id', String, true);
let navbarMain = Crisp.View.get('NavbarMain');
if(!navbarMain) { return; }
navbarMain.setItemLoading(category, id);
}
/**
* Static version of the reload method
*/
static reload() {
Crisp.View.get('NavbarMain').reload();
}
/**
* Clears all content within the navbar
*/
clear() {
this.$element.find('.navbar-main__tabs').empty();
this.$element.find('.navbar-main__panes').empty();
}
/**
* Template
*/
template() {
return _.nav({class: 'navbar-main'},
// Buttons
_.div({class: 'navbar-main__tabs'},
_.a({href: '/', class: 'navbar-main__tab'},
_.img({src: '/svg/logo_white.svg', class: 'navbar-main__tab__icon'}),
_.div({class: 'navbar-main__tab__label'}, 'Dashboard')
),
_.each(this.getPanes(), (i, pane) => {
return _.a({class: 'navbar-main__tab', 'href': '#' + pane.route, title: pane.label},
_.div({class: 'navbar-main__tab__icon fa fa-' + pane.icon}),
_.div({class: 'navbar-main__tab__label'}, pane.label)
);
})
),
// Panes
_.div({class: 'navbar-main__panes'}),
// Toggle button (mobile only)
_.button({class: 'navbar-main__toggle'})
.click((e) => {
$('.page--environment__space--nav').toggleClass('expanded');
})
);
}
} |
JavaScript | class ImpalaClient {
/**
* Creates connection using given props.
*
* @param props {object}
* @param callback {function}
* @returns {function|promise}
*/
connect(props = {}, callback) {
this.host = props.host || '127.0.0.1';
this.port = props.port || 21000;
this.resultType = props.resultType || null;
this.timeout = props.timeout || 1000;
this.transport = props.transport || thrift.TBufferedTransport;
this.protocol = props.protocol || thrift.TBinaryProtocol;
this.options = {
transport: this.transport,
protocol: this.protocol,
timeout: this.timeout
};
const deferred = Q.defer();
const connection = thrift.createConnection(this.host, this.port, this.options);
const client = thrift.createClient(service, connection);
connection.on('error', ImpalaClient.onErrorDeferred(deferred));
connection.on('connect', () => {
deferred.resolve('Connection is established.');
});
this.client = client;
this.connection = connection;
deferred.promise.nodeify(callback);
return deferred.promise;
}
/**
* Closes the current connection.
*
* @param callback {function}
* @returns {function|promise}
*/
close(callback) {
const deferred = Q.defer();
const conn = this.connection;
if (!conn) {
deferred.reject(new Error('Connection was not created.'));
} else {
conn.end();
deferred.resolve('Connection has ended.');
}
deferred.promise.nodeify(callback);
return deferred.promise;
}
/**
* Gets the query plan for a query.
*
* @param sql {string}
* @param callback {function}
* @returns {function|promise}
*/
explain(sql, callback) {
const deferred = Q.defer();
const query = ImpalaClient.createQuery(sql);
const client = this.client;
if (!client) {
deferred.reject(new Error('Connection was not created.'));
} else {
client.explain(query)
.then((explanation) => {
deferred.resolve(explanation);
})
.catch(err => deferred.reject(err));
}
deferred.promise.nodeify(callback);
return deferred.promise;
}
/**
* Gets the result metadata.
*
* @param sql {string}
* @param callback {function}
* @returns {function|promise}
*/
getResultsMetadata(sql, callback) {
const deferred = Q.defer();
const query = ImpalaClient.createQuery(sql);
const client = this.client;
if (!client) {
deferred.reject(new Error('Connection was not created.'));
} else {
client.query(query)
.then(handle =>
[handle, client.get_results_metadata(handle)]
)
.spread((handle, metaData) => {
deferred.resolve(metaData);
return handle;
})
.then((handle) => {
client.clean(handle.id);
client.close(handle);
})
.catch(err => deferred.reject(err));
}
deferred.promise.nodeify(callback);
return deferred.promise;
}
/**
* Transmits SQL command and receives result via Beeswax Service.
* The query runs asynchronously.
*
* @param sql {string}
* @param callback {function}
* @returns {function|promise}
*/
query(sql, callback) {
const deferred = Q.defer();
const query = ImpalaClient.createQuery(sql);
const resultType = this.resultType;
const client = this.client;
const connection = this.connection;
if (!client || !connection) {
deferred.reject(new Error('Connection was not created.'));
} else {
// increase the maximum number of listeners by 1
// while this promise is in progress
connection.setMaxListeners(connection.getMaxListeners() + 1);
const onErrorCallback = ImpalaClient.onErrorDeferred(deferred);
connection.on('error', onErrorCallback);
client.query(query)
.then(handle =>
[handle, client.get_state(handle)]
)
.spread((handle, state) =>
[handle, state, client.fetch(handle)]
)
.spread((handle, state, result) =>
[handle, state, result, client.get_results_metadata(handle)]
)
.spread((handle, state, result, metaData) => {
const schemas = metaData.schema.fieldSchemas;
const data = result.data;
const processedData = ImpalaClient.processData(data, schemas, resultType);
deferred.resolve(processedData);
return handle;
})
.then((handle) => {
client.clean(handle.id);
// this promise is done, so we lower the maximum number of listeners
connection.setMaxListeners(connection.getMaxListeners() - 1);
connection.removeListener('error', onErrorCallback);
client.close(handle);
})
.catch(err => deferred.reject(err));
}
deferred.promise.nodeify(callback);
return deferred.promise;
}
} |
JavaScript | class CacheStorage extends EventEmitter {
/**
* @type {string}
*/
/**
* @type {Map<any, CacheData>}
* @readonly
*/
// will expire after 30 minutes.
/**
* Construct a cache storage.
*
* @param {string?} id The ID of this cache storage.
*/
constructor(id) {
super(); // Set the ID of this cache storage.
_defineProperty(this, "id", 'Default Cache Storage');
_defineProperty(this, "cacheMap", new Map());
_defineProperty(this, "aliveDuration", 30 * 60 * 1000);
if (id) this.id = id; // Register the CLEANUP event. It will clean up
// the expired cache when emitting "CLEANUP" event.
this.on(CacheStorageEvents.CLEANUP, async () => this.removeExpiredCache());
}
/**
* Get the absolute UNIX timestamp the cache will be ended.
* @return {number}
* @constructor
*/
get WillExpireAt() {
return Date.now() + this.aliveDuration;
}
/**
* Get the context for logger().
*
* @param {Record<string, string>?} customContext The additional context.
* @return {Record<string, string>}
*/
getLoggerContext(customContext = {}) {
return { ...customContext,
cacheStorageId: this.id
};
}
/**
* Remove the expired cache.
*/
removeExpiredCache() {
logger$6.debug(this.getLoggerContext(), 'Cleaning up the expired caches...');
this.cacheMap.forEach((cachedData, key) => {
if (cachedData.expireAt <= Date.now()) this.cacheMap.delete(key);
});
}
/**
* Cache the response.
*
* @template T
* @param {any} key the unique key of action to be cached.
* @param {() => Promise<T>} action the action to do and be cached.
* @param {number?} expireAt customize the expireAt of this key.
* @return {Promise<T>}
*/
async cache(key, action, expireAt) {
// Disable the cache when the NO_CACHE = true.
if (process.env.NO_CACHE === 'true') {
return action();
} // Push the CLEANUP task to the event loop - "polling",
// so that it won't block the cache() task.
this.emit(CacheStorageEvents.CLEANUP); // Check if we have cached it before.
// If true, we return the cached value.
const cachedData = this.cacheMap.get(key); // Object.toString() can't bring any useful information,
// we show "Something" instead.
const logKey = typeof key === 'object' ? 'Something' : key;
if (cachedData) {
logger$6.debug(this.getLoggerContext({
logKey
}), `${logKey} hit!`);
return cachedData.data;
} // Cache the response of action() and
// register into our cache map.
logger$6.debug(this.getLoggerContext({
logKey: key
}), `${logKey} did not hit. Storing the execution result...`);
const sourceResponse = await action();
this.cacheMap.set(key, {
data: sourceResponse,
expireAt: new Date(expireAt || this.WillExpireAt)
});
return sourceResponse;
}
} |
JavaScript | class CacheStorageGroup$2 {
/**
* @type {CacheStorageGroup | undefined}
*/
/** @type {Set<CacheStorage>} */
/** @private */
constructor() {
_defineProperty(this, "cacheStorages", new Set());
}
/**
* @return {CacheStorageGroup}
*/
static getInstance() {
if (!CacheStorageGroup$2.instance) CacheStorageGroup$2.instance = new CacheStorageGroup$2();
return CacheStorageGroup$2.instance;
}
cleanup() {
this.cacheStorages.forEach(storage => storage.removeExpiredCache());
}
} |
JavaScript | class Resolu extends Component {
render() {
return (
<div className="resolu">
<InputNumber
size="large"
placeholder="414"
disabled={this.props.disabled}
/>
<span style={{ margin: "auto 10px" }}>x</span>
<InputNumber
size="large"
placeholder="896"
disabled={this.props.disabled}
/>
<span style={{ margin: "auto 30px" }}>
<i>width x height</i>
</span>
</div>
);
}
} |
JavaScript | class GoBuildTools {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.commands = {
'build-go': {
usage: 'Build the go tooling',
lifecycleEvents: ['build'],
},
'deploy-go': {
usage: 'Build and deploy the go tooling',
lifecycleEvents: ['build', 'deploy'],
},
};
this.cli = {
log(prefix = '', message) {
serverless.cli.consoleLog(`[serverless-go-build-tools] ${prefix} ${chalk.yellowBright(message)}`);
},
warn(prefix = '', message) {
serverless.cli.consoleLog(`[serverless-go-build-tools] ${prefix} ${chalk.redBright(message)}`);
},
};
this.hooks = {
'after:deploy:deploy': async () => {
if (options.nogobuild) {
return null;
}
await this.build.bind(this)();
return this.deploy.bind(this)();
},
'build-go:build': this.build.bind(this),
'deploy-go:build': this.build.bind(this),
'deploy-go:deploy': this.deploy.bind(this),
};
}
s3() {
const provider = this.serverless.getProvider('aws');
let awsCredentials;
let region;
if (
provider.cachedCredentials &&
provider.cachedCredentials.accessKeyId &&
provider.cachedCredentials.secretAccessKey &&
provider.cachedCredentials.sessionToken
) {
region = provider.getRegion();
awsCredentials = {
accessKeyId: provider.cachedCredentials.accessKeyId,
secretAccessKey: provider.cachedCredentials.secretAccessKey,
sessionToken: provider.cachedCredentials.sessionToken,
};
} else {
region = provider.getCredentials().region;
awsCredentials = provider.getCredentials().credentials;
}
return new provider.sdk.S3({
region,
credentials: awsCredentials,
});
}
async build() {
const goBuilds = this.serverless.service.custom.goBuilds;
const messagePrefix = 'build-go: ';
if (!Array.isArray(goBuilds)) {
this.cli.warn(messagePrefix, 'No configuration ');
return;
}
const builds = await Promise.all(
_.map(goBuilds, goBuild => {
const {
name,
packagePath,
sourceDirectory = './',
outputPrefix = 'bin/',
buildOptions = '',
architectures = ['amd64'],
operatingSystems = ['linux', 'darwin'],
...destination
} = goBuild;
if (!packagePath) {
throw new Error('No package specified for go build');
}
if (!name) {
throw new Error('No name specified for go build');
}
this.cli.log(messagePrefix, `Building package '${name}' in '${packagePath}`);
const successfulBuilds = _.flatMap(architectures, arch => {
return _.map(operatingSystems, os => {
const suffix = os === 'windows' ? '.exe' : '';
const output = `${outputPrefix}${os}-${arch}${suffix}`;
this.cli.log(messagePrefix, `Building ${output}`);
try {
execSync(`go build ${buildOptions} -o ${output} ${sourceDirectory}`, {
cwd: packagePath,
env: { ...process.env, GOOS: os, GOARCH: arch },
shell: process.env.SHELL,
});
return output;
} catch (error) {
// Don't fail the build if the user doesn't have go installed
this.cli.warn(messagePrefix, `Error building ${output}: ${error}`);
return null;
}
// Remove any build errors from the successfulBuilds array
}).filter(x => x);
});
return { name, packagePath, successfulBuilds, ...destination };
}),
);
this.serverless.variables.successfulGoBuilds = builds;
this.cli.log(messagePrefix, `Finished builds: ${_.map(builds, build => build.name).join(', ')}`);
}
async deploy() {
const goBuilds = this.serverless.variables.successfulGoBuilds;
const messagePrefix = 'deploy-go: ';
const s3 = this.s3();
// eslint-disable-next-line no-restricted-syntax
for (const goBuild of goBuilds) {
const { name, packagePath, successfulBuilds, destinationBucket, destinationPrefix } = goBuild;
// eslint-disable-next-line no-restricted-syntax
for (const build of successfulBuilds) {
const localPath = path.join(packagePath, build);
const s3Prefix = destinationPrefix.endsWith('/')
? `${destinationPrefix}${build}`
: `${destinationPrefix}/${build}`;
this.cli.log(messagePrefix, `Uploading ${localPath} from ${name} to s3://${destinationBucket}/${s3Prefix}`);
const stream = createReadStream(localPath);
// eslint-disable-next-line no-await-in-loop
await s3
.upload(
{
Bucket: destinationBucket,
Key: s3Prefix,
Body: stream,
},
{ partSize: 5 * 1024 * 1024, queueSize: 5 },
)
.promise();
}
}
this.cli.log(messagePrefix, `Finished deployment`);
}
} |
JavaScript | class SearchResponse extends models['Response'] {
/**
* Create a SearchResponse.
* @property {object} [queryContext] An object that contains the query string
* that Bing used for the request. This object contains the query string as
* entered by the user. It may also contain an altered query string that Bing
* used for the query if the query string contained a spelling mistake.
* @property {string} [queryContext.originalQuery] The query string as
* specified in the request.
* @property {string} [queryContext.alteredQuery] The query string used by
* Bing to perform the query. Bing uses the altered query string if the
* original query string contained spelling mistakes. For example, if the
* query string is "saling downwind", the altered query string will be
* "sailing downwind". This field is included only if the original query
* string contains a spelling mistake.
* @property {string} [queryContext.alterationDisplayQuery] AlteredQuery that
* is formatted for display purpose. The query string in the
* AlterationDisplayQuery can be html-escaped and can contain
* hit-highlighting characters
* @property {string} [queryContext.alterationOverrideQuery] The query string
* to use to force Bing to use the original string. For example, if the query
* string is "saling downwind", the override query string will be "+saling
* downwind". Remember to encode the query string which results in
* "%2Bsaling+downwind". This field is included only if the original query
* string contains a spelling mistake.
* @property {boolean} [queryContext.adultIntent] A Boolean value that
* indicates whether the specified query has adult intent. The value is true
* if the query has adult intent; otherwise, false.
* @property {boolean} [queryContext.askUserForLocation] A Boolean value that
* indicates whether Bing requires the user's location to provide accurate
* results. If you specified the user's location by using the
* X-MSEdge-ClientIP and X-Search-Location headers, you can ignore this
* field. For location aware queries, such as "today's weather" or
* "restaurants near me" that need the user's location to provide accurate
* results, this field is set to true. For location aware queries that
* include the location (for example, "Seattle weather"), this field is set
* to false. This field is also set to false for queries that are not
* location aware, such as "best sellers".
* @property {boolean} [queryContext.isTransactional]
* @property {string} [queryContext._type] Polymorphic Discriminator
* @property {object} [places] A list of local entities such as restaurants
* or hotels that are relevant to the query.
* @property {array} [places.value] A list of local entities, such as
* restaurants or hotels.
* @property {object} [lottery]
* @property {object} [lottery.queryContext]
* @property {string} [lottery.queryContext.originalQuery] The query string
* as specified in the request.
* @property {string} [lottery.queryContext.alteredQuery] The query string
* used by Bing to perform the query. Bing uses the altered query string if
* the original query string contained spelling mistakes. For example, if the
* query string is "saling downwind", the altered query string will be
* "sailing downwind". This field is included only if the original query
* string contains a spelling mistake.
* @property {string} [lottery.queryContext.alterationDisplayQuery]
* AlteredQuery that is formatted for display purpose. The query string in
* the AlterationDisplayQuery can be html-escaped and can contain
* hit-highlighting characters
* @property {string} [lottery.queryContext.alterationOverrideQuery] The
* query string to use to force Bing to use the original string. For example,
* if the query string is "saling downwind", the override query string will
* be "+saling downwind". Remember to encode the query string which results
* in "%2Bsaling+downwind". This field is included only if the original query
* string contains a spelling mistake.
* @property {boolean} [lottery.queryContext.adultIntent] A Boolean value
* that indicates whether the specified query has adult intent. The value is
* true if the query has adult intent; otherwise, false.
* @property {boolean} [lottery.queryContext.askUserForLocation] A Boolean
* value that indicates whether Bing requires the user's location to provide
* accurate results. If you specified the user's location by using the
* X-MSEdge-ClientIP and X-Search-Location headers, you can ignore this
* field. For location aware queries, such as "today's weather" or
* "restaurants near me" that need the user's location to provide accurate
* results, this field is set to true. For location aware queries that
* include the location (for example, "Seattle weather"), this field is set
* to false. This field is also set to false for queries that are not
* location aware, such as "best sellers".
* @property {boolean} [lottery.queryContext.isTransactional]
* @property {string} [lottery.queryContext._type] Polymorphic Discriminator
* @property {number} [lottery.totalEstimatedMatches] The estimated number of
* webpages that are relevant to the query. Use this number along with the
* count and offset query parameters to page the results.
* @property {boolean} [lottery.isFamilyFriendly]
* @property {number} [searchResultsConfidenceScore]
*/
constructor() {
super();
}
/**
* Defines the metadata of SearchResponse
*
* @returns {object} metadata of SearchResponse
*
*/
mapper() {
return {
required: false,
serializedName: 'SearchResponse',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: '_type',
clientName: '_type'
},
uberParent: 'ResponseBase',
className: 'SearchResponse',
modelProperties: {
_type: {
required: true,
serializedName: '_type',
isPolymorphicDiscriminator: true,
type: {
name: 'String'
}
},
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
readLink: {
required: false,
readOnly: true,
serializedName: 'readLink',
type: {
name: 'String'
}
},
webSearchUrl: {
required: false,
readOnly: true,
serializedName: 'webSearchUrl',
type: {
name: 'String'
}
},
potentialAction: {
required: false,
readOnly: true,
serializedName: 'potentialAction',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'ActionElementType',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: '_type',
clientName: '_type'
},
uberParent: 'ResponseBase',
className: 'Action'
}
}
}
},
immediateAction: {
required: false,
readOnly: true,
serializedName: 'immediateAction',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'ActionElementType',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: '_type',
clientName: '_type'
},
uberParent: 'ResponseBase',
className: 'Action'
}
}
}
},
preferredClickthroughUrl: {
required: false,
readOnly: true,
serializedName: 'preferredClickthroughUrl',
type: {
name: 'String'
}
},
adaptiveCard: {
required: false,
readOnly: true,
serializedName: 'adaptiveCard',
type: {
name: 'String'
}
},
queryContext: {
required: false,
readOnly: true,
serializedName: 'queryContext',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: '_type',
clientName: '_type'
},
uberParent: 'QueryContext',
className: 'QueryContext'
}
},
places: {
required: false,
readOnly: true,
serializedName: 'places',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: '_type',
clientName: '_type'
},
uberParent: 'ResponseBase',
className: 'Places'
}
},
lottery: {
required: false,
readOnly: true,
serializedName: 'lottery',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: '_type',
clientName: '_type'
},
uberParent: 'ResponseBase',
className: 'SearchResultsAnswer'
}
},
searchResultsConfidenceScore: {
required: false,
readOnly: true,
serializedName: 'searchResultsConfidenceScore',
type: {
name: 'Number'
}
}
}
}
};
}
} |
JavaScript | class OeWorkflowPlayground extends OEAjaxMixin(PolymerElement) {
static get is() {
return 'oe-workflow-playground';
}
static get template() {
return html`
<style include="iron-flex iron-flex-alignment">
paper-dialog{
overflow: auto;
top:64px;
width:100%;
height:100%;
margin:0px;
@apply --layout-vertical;
}
#viewer{
height:68vh;
}
.action-panel paper-button{
margin:0px 8px;
border:1px solid rgba(0,0,0,0.4);
border-radius:4px;
}
.page-content{
@apply --layout-vertical;
height: 100%;
}
.page-content h2{
margin-bottom:0px;
}
iron-pages{
height: 100%;
}
.buttons-container{
@apply --layout-horizontal;
@apply --layout-end-justified;
}
*[hidden]{
display:none !important;
}
</style>
<paper-dialog id="dialog" on-iron-overlay-closed="_endLaunch">
<iron-pages selected=[[selectedPage]] attr-for-selected="page">
<div page="payload" class="page-content">
<oe-combo id="workflow" label="Workflows" displayproperty="name" valueproperty="name" listdata=[[worfklows]]></oe-combo>
<h2>Process Variables</h2>
<oe-json-input class="flex" label="Process Variables" value={{workflowDef.payload}} invalid={{isPayloadInvalid}}></oe-json-input>
<div class="buttons-container">
<paper-button primary on-tap="_executeWorkflow" disabled=[[isPayloadInvalid]]>Simulate</paper-button>
<paper-button dialog-dismiss>Cancel</paper-button>
</div>
</div>
<div page="progress" class="page-content">
<div class="header layout horizontal center justified">
<h2>[[workflowDef.name]]</h2>
<div class="action-panel layout horizontal center-center">
<paper-button on-tap="_zoomIn">Zoom in</paper-button>
<paper-button on-tap="_zoomOut">Zoom out</paper-button>
<paper-button on-tap="_resetZoom">Reset</paper-button>
<paper-button on-tap="refreshProcess">Refresh</paper-button>
</div>
</div>
<div class=" flex">
<oe-bpmn-viewer id="viewer" on-oe-bpmn-viewer-selection="_tokenClicked"></oe-bpmn-viewer>
</div>
<div class="buttons-container">
<paper-button primary on-tap="_gotoPayload">Back</paper-button>
<paper-button dialog-dismiss>Cancel</paper-button>
</div>
</div>
</iron-pages>
</paper-dialog>
`;
}
connectedCallback() {
super.connectedCallback();
var self = this;
this.$.workflow.addEventListener('change',function(event){
self.set('workflowDef', {
name: self.$.workflow.value,
payload: {}
});
})
this.$.viewer.addEventListener('refresh',function(event){
self.refreshProcess();
})
this.$.viewer.addEventListener('wheel', function (event) {
event.preventDefault();
if (event.deltaY > 0) {
self._zoomOut();
} else {
self._zoomIn();
}
});
window.OEUtils.apibaseroute = location.origin;
}
_endLaunch(e){
if(!e.detail.confirmed && (e.detail.confirmed !== undefined)){
this.$.workflow.__resetComponent();
this.set('workflowDef',undefined);
}
}
launch() {
this.set('selectedPage', 'payload');
this.$.dialog.open();
this.set('_selectedToken', {
isVisible: false,
status: '',
message: ''
});
}
_gotoPayload() {
this.set('selectedPage', 'payload');
}
_gotoProgress() {
this.set('selectedPage', 'progress');
}
/** payload page functions */
_executeWorkflow() {
let body = {
workflowDefinitionName: this.workflowDef.name,
processVariables: this.workflowDef.payload
};
this.makeAjaxCall(this.__getApiUrl('/WorkflowInstances'), 'post', body, null, null, null, (err, wfInstance) => {
if (err) {
return console.error(err);
}
this.__getMainProcessForWorkflow(wfInstance.id, (processErr, process) => {
if (processErr) {
return console.error(processErr);
}
this.__getBpmnForProcess(process.processDefinitionName, (bpmnErr, bpmndt) => {
if (bpmnErr) {
return console.error(bpmnErr);
}
this.set('simulationResp', {
workflowInstance: wfInstance,
processInstance: process,
bpmn: bpmndt
});
let bpmnViewer = this.$.viewer;
bpmnViewer.set('bpmnXml', bpmndt[0].xmldata);
bpmnViewer.set('processInstance', process);
this.set('_selectedToken', {
isVisible: false,
status: '',
message: ''
});
this._gotoProgress();
});
//this.$.viewer.set('processInstance', process);
});
});
}
/* BPMN actions */
_zoomIn(e) {
var oeViewer = this.$.viewer;
var zoom = oeViewer.zoom();
oeViewer.zoom(zoom + 0.1);
}
_zoomOut(e) {
var oeViewer = this.$.viewer;
var zoom = oeViewer.zoom();
oeViewer.zoom(zoom - 0.1);
}
_resetZoom() {
let canvas = this.$.viewer.viewer.get('canvas');
var zoomedAndScrolledViewbox = canvas.viewbox();
canvas.viewbox({
x: 0,
y: 0,
width: zoomedAndScrolledViewbox.outer.width,
height: zoomedAndScrolledViewbox.outer.height
});
canvas.zoom('fit-viewport');
}
refreshProcess() {
this.__getMainProcessForWorkflow(this.simulationResp.workflowInstance.id, (err, process) => {
if (err) {
console.log(err);
return;
}
this.set('simulationResp.processInstance', process);
this.$.viewer.set('processInstance', process);
});
}
_tokenClicked(event) {
let
processToken
= event.detail.processToken;
if (!processToken) {
this.set('_selectedToken', {
isVisible: false,
status: '',
message: ''
});
return;
}
let selected = {
name: processToken.name,
status: processToken.status,
isVisible: true
}
let endTimeStr = '';
if (processToken.endTime) {
let end = new Date(processToken.endTime);
endTimeStr = `${end.toDateString()} at ${end.toLocaleTimeString()}`;
}
switch (processToken.status) {
case "complete":
selected.message = `Completed on ${endTimeStr}`;
break;
case "failed":
selected.message = (processToken.error && processToken.error.message) ? processToken.error.message : `Failed on ${endTimeStr}`;
break;
case "pending":
selected.allowAction = !!processToken.isUserTask;
selected.__token = processToken;
break;
default:
selected.message = null;
selected.isVisible = false;
}
this.set('_selectedToken', selected);
}
__or(bool1, bool2) {
return bool1 || bool2;
}
__getApiUrl(url) {
var restApiRoot = (window.OEUtils && window.OEUtils.restApiRoot) ? window.OEUtils.restApiRoot : '/api';
return restApiRoot + url;
}
__getMainProcessForWorkflow(wfInstanceId, cb) {
var self = this;
let url = `/WorkflowInstances/${wfInstanceId}/processes`;
this.makeAjaxCall(this.__getApiUrl(url), 'get', null, null, null, null, function (err, resp) {
if (err) {
cb(err, null);
return;
}
let mainProcess = resp.find(function (proc) {
return proc.processDefinitionName === self.workflowDef.name;
});
cb(null, mainProcess);
});
}
__getBpmnForProcess(processName, cb) {
let url = this.__getApiUrl('/bpmndata');
let bpmnFilter = {
where: {
bpmnname: processName
}
};
this.makeAjaxCall(url, 'get', null, null, {
'filter': bpmnFilter
}, null, function (err, resp) {
if (err) {
cb(err, null);
return;
}
cb(null, resp);
});
}
__getTasksForProcess(processId, cb) {
let url = this.__getApiUrl(`ProcessInstances/${processId}/tasks`);
this.makeAjaxCall(url, 'get', null, null, null, null, function (err, resp) {
if (err) {
cb(err, null);
return;
}
cb(null, resp);
});
}
} |
JavaScript | class Filters extends React.Component {
constructor(props) {
super(props);
this.state = {
adding: false,
editing: null,
filter: {},
};
this.onAdd = this.onAdd.bind(this);
this.onCancel = this.onCancel.bind(this);
this.onRemove = this.onRemove.bind(this);
this.onSubmitFilter = this.onSubmitFilter.bind(this);
}
onAdd(e) {
const { onSwitchView } = this.props;
if (e) {
e.preventDefault();
}
onSwitchView(FORM_VIEW);
this.setState({ adding: true });
}
onCancel() {
const { onSwitchView } = this.props;
onSwitchView(LIST_VIEW);
this.setState({
editing: null,
adding: false,
filter: {},
});
}
onSubmitFilter(filter) {
const { filters, onChange, onSwitchView } = this.props;
const { editing } = this.state;
let newFilters = [];
if (editing) {
const index = filters.findIndex(f => getFilterKey(f) === editing);
newFilters = [...filters];
newFilters[index] = filter;
} else {
newFilters = filters.concat(filter);
}
onChange(newFilters);
onSwitchView(LIST_VIEW);
this.setState({ adding: false, editing: null, filter: {} });
}
onEdit(filter) {
const { onSwitchView } = this.props;
const key = getFilterKey(filter);
return () => {
onSwitchView(FORM_VIEW);
this.setState({
editing: key,
filter,
});
};
}
onRemove(removed) {
const { filters, onChange } = this.props;
return () => {
const newFilters = filters.filter(
filter => !(getFilterKey(removed) === getFilterKey(filter)),
);
onChange(newFilters);
};
}
renderFilters() {
const { operators, filters: propsFilters } = this.props;
const filters = propsFilters.map(filter => {
const key = getFilterKey(filter);
return (
<Filter
onEdit={this.onEdit(filter)}
onRemove={this.onRemove(filter)}
filter={filter}
key={key}
operators={operators}
/>
);
});
return <List className="rc-filters-list">{filters}</List>;
}
renderAction() {
const { editing, adding } = this.state;
const { strings, addCTA, filters } = this.props;
const ctaLabel = strings.addCTA || addCTA;
let jsx;
if (!editing && !adding && filters.length) {
jsx = (
<Button type="text" icon="plus" onClick={this.onAdd}>
{ctaLabel}
</Button>
);
}
return jsx;
}
renderForm() {
const {
removableToggle,
fields,
operators,
strings,
filters,
onUpdate,
} = this.props;
const { filter } = this.state;
let cancellable = true;
if (!filters.length) {
cancellable = false;
}
return (
<Form
cancellable={cancellable}
removable={removableToggle}
fields={fields}
filter={filter}
operators={operators}
onUpdate={onUpdate}
onCancel={this.onCancel}
onSubmit={this.onSubmitFilter}
strings={strings}
/>
);
}
render() {
const { adding, editing } = this.state;
const { filters: rawFilters } = this.props;
const action = this.renderAction();
let filters;
let form;
if (adding || editing || !rawFilters.length) {
form = this.renderForm();
} else {
filters = this.renderFilters();
}
return (
<div className="rc-filters">
{filters}
{action}
{form}
</div>
);
}
} |
JavaScript | class Xw {
/**
* Deep clone an item
* @template T
* @param {T} v Value to be cloned
* @return {T} Cloned value
*/
deepClone(v) {
if (v === null) return null;
if (typeof v !== 'object') return v;
const ret = {};
for (const k in v) {
if (!v.hasOwnProperty(k)) continue;
ret[k] = this.deepClone(v[k]);
}
return ret;
}
/**
* Deep clone element (like a template)
* @param {HTMLElement} elem Element to be cloned
* @return {HTMLElement}
*/
elementClone(elem) {
const _elem = this.requires(elem);
const clonedElem = _elem.cloneNode(true);
clonedElem.id = this.randomId();
return clonedElem;
}
/**
* Create a new random ID
* @return {string} The randomly created ID
*/
randomId() {
return _onRandomId();
}
/**
* Set function to generate a new random ID
* @param {function():string} fn Generator function
*/
onRandomId(fn) {
_onRandomId = fn;
}
/**
* Transfer options from source to target, if available
* @param {object} source Source object
* @param {object} target Target object
* @param {string} key Key name
* @param {string} [renameKey]
*/
optionsTransfer(source, target, key, renameKey) {
const _source = this.requires(source);
const _target = this.requires(target);
const _key = this.requires(key);
const _renameKey = this.defaultable(renameKey, _key);
if (!this.isDefined(_source[_key])) return;
_target[_renameKey] = _source[_key];
}
/**
* Convert any value iterables to array
* @param {Iterator<*>|Iterable<*>|*[]} iterable Input value
* @return {*[]}
*/
toArray(iterable) {
const ret = [];
for (const v of iterable) {
ret.push(v);
}
return ret;
}
/**
* Flatten an item, normally for debugging display purpose
* @param {*} v Value to be flatten
* @return {*}
*/
flatten(v) {
return JSON.parse(JSON.stringify(v));
}
/**
* Check if given item is defined
* @param {*} v Item to be checked
* @return {boolean} If the item is defined
*/
isDefined(v) {
return typeof v !== 'undefined';
}
/**
* Ensure that the given item is provided
* @template T
* @param {T} v Item required
* @return {T} Item as returned
*/
requires(v) {
if (!this.isDefined(v)) throw new Error(_l('Required argument undefined'));
return v;
}
/**
* Get the item, or return an alternative fallback if item unavailable
* @template T
* @param {T} v Item to be checked
* @param {T|null} [alt=null] Alternative fallback value if item unavailable
* @returns {T|null} Item as returned, or its alternative default
*/
defaultable(v, alt) {
const _alt = this.isDefined(alt) ? alt : null;
if (!this.isDefined(v)) return _alt;
return v;
}
/**
* Build a URL using given base and queries
* @param {string} base The base path of the URL
* @param {object} [queries] Queries to the URL
* @param {string} [bookmark] Bookmark of the URL
*/
buildUrl(base, queries, bookmark) {
let ret = base;
if (!this.isDefined(queries)) return ret;
let isFirst = true;
for (const key in queries) {
const outKey = key.trim();
if (outKey === null || outKey === '') continue;
const value = queries[key].trim();
if (isFirst) {
ret += '?';
isFirst = false;
} else {
ret += '&';
}
if (!this.isDefined(value)) {
ret += encodeURIComponent(outKey);
} else {
ret += encodeURIComponent(outKey) + '=' + encodeURIComponent(value);
}
}
if (this.isDefined(bookmark)) {
ret += '#' + bookmark;
}
return ret;
}
/**
* Cause an error for function not implemented
* @throws Error
*/
todo() {
throw new Error(_l('Not implemented'));
}
/**
* Try to read cookie with given key
* @param {string} key The cookie key
* @param {string|null} [defaultValue=null] Default value if not matched
* @return {string|null} The corresponding cookie value
*/
readCookie(key, defaultValue) {
const _key = this.requires(key);
const _defaultValue = this.defaultable(defaultValue, null);
return jsCookieLib.get(_key) || _defaultValue;
}
/**
* Set a cookie with given key and value
* @param {string} key The cookie key
* @param {string} value The cookie value
* @param {object} [options] Relevant options
* @param {string} [options.path] The path to set the cookie
* @param {string} [options.domain] The domain to set the cookie
* @param {Date|number} [options.expires] When the cookie will expire / number of seconds until expires
* @param {boolean} [options.secure] If the cookie must be secured
* @param {string} [options.sameSite] Same site options ('lax', 'strict', 'none')
*/
writeCookie(key, value, options) {
const _key = this.requires(key);
const _value = this.requires(value);
const _options = this.defaultable(options, {});
const _optionsPath = this.defaultable(_options.path);
const _optionsDomain = this.defaultable(_options.domain);
const _optionsExpires = this.defaultable(_options.expires);
const _optionsSecure = this.defaultable(_options.secure, false);
const _optionsSameSite = this.defaultable(_options.sameSite);
const setOptions = {};
if (_optionsPath !== null) setOptions.path = _optionsPath;
if (_optionsDomain !== null) setOptions.domain = _optionsDomain;
if (_optionsSecure) setOptions.secure = true;
if (_optionsSameSite !== null) setOptions.sameSite = _optionsSameSite;
if (_optionsExpires !== null) {
if (typeof _optionsExpires === 'number') {
const newExpires = new Date(Date.now() + (_optionsExpires * 1000));
setOptions.expires = newExpires;
} else if (_optionsExpires instanceof Date) {
setOptions.expires = _optionsExpires;
} else {
throw new XwInvalidDataError();
}
}
jsCookieLib.set(_key, _value, setOptions);
}
/**
* Delete a cookie with the given key
* @param {string} key The cookie key
*/
deleteCookie(key) {
const _key = this.requires(key);
jsCookieLib.remove(_key);
}
/**
* Escape text to be HTML safe
* @param {string} value Text value to be escaped
* @return {string} Text after escaped
*/
escapeHtml(value) {
return escapeHtmlFromLib(value);
}
/**
* Defer execution of function until document is ready
* @param {function()} fn
*/
onDocumentReady(fn) {
const _fn = this.requires(fn);
if (document.readyState === 'complete') {
_fn();
} else {
document.addEventListener('readystatechange', (ev) => {
if (document.readyState !== 'complete') return;
_fn();
});
}
}
/**
* Load javascript from given source
* @param {string} src URL to the javascript
* @param {object} [options] Options
* @param {number} [options.timeoutMs=null] Timeout in milliseconds, do not timeout if not specified
* @return {Promise<void>}
*/
async loadJavascript(src, options) {
const _src = this.requires(src);
const _options = this.defaultable(options, {});
const _optionsTimeoutMs = this.defaultable(_options.timeoutMs);
return new Promise((resolve, reject) => {
const scriptElement = document.createElement('script');
scriptElement.async = true;
scriptElement.src = _src;
// Handle events
scriptElement.onload = () => {
resolve();
}
scriptElement.onreadystatechange = () => {
resolve();
}
scriptElement.onerror = (ev) => {
reject(new Error(_l('Error while loading the javascript')));
};
// Handle timeout
if (_optionsTimeoutMs > 0) {
setTimeout(() => {
reject(new XwTimeoutError());
}, _optionsTimeoutMs);
}
document.body.appendChild(scriptElement);
});
}
/**
* Load JSON from given source using JSONP
* @param {string} src URL to the JSON
* @param {object} [options] Options
* @param {string} [options.callbackArg='callback'] Argument name for the callback query
* @param {number} [options.timeoutMs=null] Timeout in milliseconds, do not timeout if not specified
* @return {Promise<*>}
*/
async loadJsonp(src, options) {
const _src = this.requires(src);
const _options = this.defaultable(options, {});
const _optionsCallbackArg = this.defaultable(_options.callbackArg, 'callback');
const _optionsTimeoutMs = this.defaultable(_options.timeoutMs);
return new Promise((resolve, reject) => {
const _callbackName = 'xwcb_' + random.lowerAlphanumString(8);
// Receive the callback
window[_callbackName] = (data) => {
delete window[_callbackName];
resolve(data);
}
// Handle timeout
if (_optionsTimeoutMs > 0) {
setTimeout(() => {
setTimeout(() => {
// Only delete it very long after
delete window[_callbackName];
}, 600000 /* 10 minutes */);
reject(new XwTimeoutError());
}, _optionsTimeoutMs);
}
const _parsedSrc = new URL(_src, window.location.origin);
_parsedSrc.searchParams.append(_optionsCallbackArg, _callbackName);
const scriptElement = document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.async = true;
scriptElement.src = _parsedSrc.href;
scriptElement.onerror = (ev) => {
delete window[_callbackName];
reject(new Error(_l('Error while loading the JSONP')));
};
document.getElementsByTagName('head')[0].appendChild(scriptElement);
});
}
/**
* Access to custom CSS
* @return {CSSStyleSheet}
*/
getCustomCss() {
if (_customCss !== null) return _customCss;
const style = document.createElement('style');
style.appendChild(document.createTextNode(''));
document.head.appendChild(style);
_customCss = style.sheet;
return _customCss;
}
/**
* Insert a custom CSS (if not already inserted)
* @param {string} name
* @param {string} rule
*/
insertCustomCss(name, rule) {
if (this.isDefined(_customCssNames[name])) return;
const customCss = this.getCustomCss();
customCss.insertRule(rule);
_customCssNames[name] = rule;
}
} |
JavaScript | class SessionPage_OutcomeTests extends React.Component {
/*The array of tests that gets mapped to a dropdown list
for the user to select from. testId is the the id of the
test in firebase while modalToBeViewed is the test
to be viewed in the PDF modal.*/
state = {
testsList: [
'TUG TEST',
'L TEST',
'PEQ TEST',
],
testId: '',
selectedTest: '',
successMessage: '',
alert: null,
modalToBeViewed: {}
}
/*Styles for the button to add an outcome test.*/
style = {
addButton: {
marginTop: 15,
marginLeft: 150
}
}
/*This function sets the selectedTest state variable
to that of the test selected from the testsList
state array via the dropdown menu for tests.*/
selectTest (selectedTest) {
this.setState({
selectedTest
})
}
/*This function executes once a test to be edited has
been selected. the selectedTest variable gets set as well
as the firebase id for the selected test and testId gets
passed into the AddTestModal component which is used to load
pre-existing tests so the proper values can be set in the test
modal.*/
editTest (test, selectedTest) {
this.setState({
testId: test,
selectedTest
});
}
/*React lifecycle method: componentDidMount
This method is invoked after the component has mounted and rendered.
The scrollIntoView npm dependency is used here to automatically scroll
down to the outcome test panel when the component is rendered.*/
componentDidMount() {
scrollIntoView(document.getElementById("outcomeTestPanel"))
alert
}
onDelete (test) {
const getAlert = (test) => (
<SweetAlert
warning
showCancel
confirmBtnText="Delete"
confirmBtnBsStyle="danger"
cancelBtnBsStyle="default"
title="Are you sure?"
onConfirm={() => this.deleteTest(test)}
onCancel={() => this.onCancelAlert()}
>
You will not be able to recover this test!
</SweetAlert>
);
this.setState({
alert: getAlert(test)
});
}
/*This function is executed when the Finish Session button is clicked. At this point
a SweetAlert alert is thrown to warn the user that upon finishing the session, the user
will not be able to make changes to existing tests or add new tests. onConfirm, the completeForm
function will be executed. onCancel, the onCancelAlert function will be executed.*/
onFinish () {
const getAlert = () => (
<SweetAlert
warning
showCancel
confirmBtnText="Finish Session"
confirmBtnBsStyle="success"
cancelBtnBsStyle="default"
title="Are you sure?"
onConfirm={() => this.finishSession()}
onCancel={() => this.onCancelAlert()}
>
Once this session is completed you will not be able to make changes to existing tests or add new tests.
</SweetAlert>
);
/*The alert state variable gets set to the getAlert constant storing the SweetAlert.*/
this.setState({
alert: getAlert()
});
}
/*When either the Preview Information or View Report buttons get clicked (these buttons interchange
depending on whether or not the session is completed or not (Finish Session button has been clicked.))
then the modalToBeViewed state variable is set to the selected test which is passed in as a parameter
of the same variable name.*/
viewPdfModal(modalToBeViewed) {
this.setState({
modalToBeViewed
});
}
/*This function is executed once the onConfirm button of the SweetAlert of the onDelete function is clicked
after the delete button for the particular test is clicked and the test to be deleted is passed in to the
parameter. The test is deleted using a default firebase function and the alert state variable is set to null
to get rid of the SweetAlert*/
deleteTest (test) {
const userId = firebase.auth().currentUser.uid;
firebase.database().ref(`/sessions/${userId}/${this.props.patientInformation.sessionId}/tests/${test.category}/${test.id}`).remove();
this.setState({
alert: null
});
}
/*This function is executed once the onCancel button of the SweetAlert of the onDelete or onFinish function
is clicked after the delete button for the particular test or the Finish Session button is clicked and the
alert state variable is set to null to get rid of the alert.*/
onCancelAlert () {
this.setState({
alert: null
})
}
/*This function will execute once the onConfirm button of the SweetAlert of the onFinish function is clicked.
Using a default firebase function, the completed variable in each firebase session is set to true to indicate
that the session is completed. The alert state variable is set to null to get rid of the SweetAlert and
a success message is thrown to indicate to the user that the session has been completed.*/
finishSession () {
event.preventDefault();
const userId = firebase.auth().currentUser.uid;
firebase.database().ref(`/sessions/${userId}/${this.props.patientInformation.sessionId}`).update({
completed: true
}).then(() => {
this.setState({
alert: null,
successMessage: 'This session has been marked as completed.'
})
});
}
/*Once the save button has been clicked for a test in the AddTestModal component, the test id in firebase (testId)
and the selected test in the form of a string for the test name (selectedTest) are set from the parameters passed in
for the specific test when the function is called. These state variables are then passed in as props to the AddTestModal
component to set the values that were previously set by the user (this is discussing the case where the user clicks
edit to edit a test so the test modal should 'remember' the values that were previously entered).*/
rememberValues (testId, selectedTest) {
this.setState({
testId,
selectedTest
})
}
/*This function parses through the sessionData which contains all
sessions for a clinician and parses just the test information into
into the sessionsParsed array because the session includes patient
information which is not necessary to display.*/
parseSessionDataIntoTests (sessionData) {
let sessionsParsed = [];
Object.keys(sessionData).forEach((testCategory) => {
Object.keys(sessionData[testCategory]).forEach((test) => {
sessionsParsed.push(sessionData[testCategory][test]);
});
});
return sessionsParsed;
}
render() {
/*Using the parseSessionDataIntoTests function that returns
an array of the sessions data correctly parsed into just the tests,
this array gets stored into the allTests constant. The enableFinish
constant stores the allTests constant and is used to disable the Finish
Session button of there are no tests completed.*/
const allTests = this.props.patientInformation.tests ? this.parseSessionDataIntoTests(this.props.patientInformation.tests) : null;
const enableFinish = allTests;
return (
<div id="wrapper">
{/*This is where the SweetAlert is thrown if the delete button
for a test or the Finish Session has been clicked.*/}
{this.state.alert}
<div className="records">
{/*This is where the Outcome Test_Modals History is rendered.*/}
{this.state.successMessage && <div className="alert alert-success">{this.state.successMessage}</div>}
<div className="panel panel-default list-group-panel" id = "outcomeTestPanel">
<div className="panel-body">
<ul className="list-group list-group-header">
<li className="list-group-item list-group-body">
<div className="row">
<div className="panel-heading">
Outcome Test History
</div>
{/*The completed variable of each session in firebase stored in the patientInformation prop
is checked (indicates if the session is completed or not). If the completed variable is
not set to true, then the buttons for adding an outcome test and finishing the session
will be rendered. */}
{this.props.patientInformation.completed !== true && <div className="col-xs-12 pull-left">
<div className="input-group input-group-xs">
<div className="input-group-btn">
{/*This is where the test gets selected*/}
<button type="button" className="btn btn-lg btn-default" data-toggle="dropdown">{this.state.selectedTest || 'Select an Outcome Test'}<span> </span><span className="caret"></span></button>
{/*This is where the dropdown list of tests is rendered and gets
generated based on the testsList state array. When selected the selectTest
function is executed which will set the selectedTest variable which will
then be passed into the AddTestModal component as props to set the test modal fields of input.*/}
<ul className="dropdown-menu btn-lg" role="menu">
{this.state.testsList.map((testCategory, i) => <li key={i}><a onClick={this.selectTest.bind(this, testCategory)}> {testCategory} </a></li>)}
</ul>
{/*This is where the corresponding test modal is rendered once the Add Outcome Test button is clicked.
When selected the editTest function is executed which will set the testId and selectedTest variables
which will then be passed into the AddTestModal component as props to set the test modal fields of input.
By rendering the AddTestModal component in the render function of this component,
it is possible to target divs in this component using the data-target attribute.
Therefore, as shown in the button below, the data-target attribute is set to
the id of the div that renders the test modal in the AddTestModal component.
Therefore, once the Add Outcome Test button is clicked, (which enables once a
test has been selected) the appropriate test modal will be selected.
*/}
<button disabled={!this.state.selectedTest}
onClick={this.editTest.bind(this, '', this.state.selectedTest)}
data-toggle="modal"
id="addOutcomeTestButton"
data-target="#testModal"
className="btn btn-lg btn-default"
type="button"
>
<span className="glyphicon glyphicon-plus">
</span> Add Outcome Test
</button>
</div>
{/*The finish button completes the session not allowing any tests to be added or changed
and is only enabled when at least one test has been successfully saved.*/}
{this.props.patientInformation.completed !== true && <div className="col-xs-5 pull-right">
<Link disabled = {!enableFinish} className="finish-button col-xl-12 btn btn-lg icon-btn btn-success" onClick={this.onFinish.bind(this)}>
Finish Session
</Link></div>
}
</div>
</div>}
</div>
</li>
</ul>
{/*If there any tests successfully saved, this is where they will be displayed by first
checking if any tests exist in the allTests constant.*/}
{allTests && allTests.length > 0 ? <table id="mytable" className="table testTable table-bordred table-striped col-xs-11">
{/*The table header*/}
<thead>
<tr>
<th></th>
<th>Title</th>
<th></th>
<th>Category</th>
<th>Created</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
{/*By using the map function on the allTests constant, each test stored in the allTests
constant gets listed with the formatting shown below.*/}
<tbody>
{allTests && allTests.map((test, i) => <tr className = "striped" key={i}>
<td><span className="yellow glyphicon glyphicon-list-alt" aria-hidden="true" /></td>
<td>{test['title']}</td>
<td></td>
<td>{test['category']}</td>
<td>{moment(test['date'], "MMMM Do YYYY, h:mm:ss a").fromNow()}</td>
{/*This is where buttons are rendered depending on if the completed variable
is true or not. In the case of the completed variable being true, the only
button that renders will be the button to preview the report.*/}
{/*If the test at i in the allTests constant is not completed, (the completed variable
is currently set to false) then the edit, delete, and Preview Report buttons are
rendered.
If the session is not completed then each test can be edited.*/}
{this.props.patientInformation.completed !== true &&
<td>
<p>
<button
onClick={this.editTest.bind(this, test['id'], test['category'])}
onMouseOver={this.editTest.bind(this, test['id'], test['category'])}
data-toggle="modal"
data-target="#testModal"
id = "editTestButton"
className="btn icon-btn btn-info">
<span className="glyphicon glyphicon-pencil">
</span> Edit</button>
</p>
</td>}
{/*If the session is not completed then each test can be deleted.*/}
{this.props.patientInformation.completed !== true &&
<td>
<p>
<button
onClick={this.onDelete.bind(this, test)}
className="btn icon-btn btn-danger">
<span className="glyphicon glyphicon-trash"></span>
Delete
</button>
</p>
</td>}
{/*This is the button for previewing a report (meaning that the test
can still be edited as the session is still not complete) or for
viewing a report (meaning that the tests can no longer be edited and the
session is completed).*/}
{test['completed'] || this.props.patientInformation.completed === false ?
<td>
<p>
<button
onClick={this.viewPdfModal.bind(this, test)}
className="btn btn-default"
data-toggle="modal"
data-target="#pdfModal"
id = "reportButton"
>
<span
className="glyphicon btn-glyphicon glyphicon-eye-open img-circle text-success">
</span> Preview Report
</button>
</p>
</td> :
<td>
<p>
<button
onClick={this.viewPdfModal.bind(this, test)}
className="btn btn-default"
data-toggle="modal"
data-target="#pdfModal"
id = "reportButton"
>
<span
className="glyphicon btn-glyphicon glyphicon-eye-open img-circle text-success">
</span> View Report
</button>
</p>
</td>}
</tr>)}
{/*If the allTests constant contains no data then no tests
are displayed.*/}
</tbody>
</table> : <div className="well">
<h3>No outcome tests have been performed.</h3>
</div>}
</div>
</div>
<span>
Note: If patient information is not visible,
please reload the page. If patient information is
still not visible, then there is no data for this
patient stored locally on this machine.
</span>
</div>
{/*This is where both modal types are called so props can
be passed in. TestModal is the test modal for each test.
Pdf_Clinic_Patient_Info is the modal which reports the interpretation
of results for each test.*/}
<Pdf_Clinic_Patient_Info
settings={this.props.settings}
test={this.state.modalToBeViewed}
patientInformation={this.props.patientInformation}
/>
<TestModal
selectedTest={this.state.selectedTest}
sessionId={this.props.patientInformation.sessionId}
rememberValues={this.rememberValues.bind(this)}
questions={this.props.questions}
tests={this.props.patientInformation.tests}
testId={this.state.testId}
/>
</div>
)
}
} |
JavaScript | class Resource {
/**
* Resource Class.
* @param {string} resourceName The name for the resource.
* @param {string} resourceType The type of resource.
*/
constructor(resourceName, resourceType) {
/**
* The name of the resource.
* @type {string}
*/
this.name = resourceName;
/**
* The type of resource.
* @type {string}
*/
this.resourceType = resourceType;
/**
* Filepath leading to the resource's saved data for web export.
* @type {string}
*/
this.webFilepath = '';
}
/**
* Gets the data necessary to export the resource.
* @return {!Object} The data needed to export the resource.
*/
getExportData() {
throw 'abstract method: getExportData';
}
/**
* Gets the navigation tree-specific JSON object which represents the resource.
*
* @return {!Object} The tree-specific JSON representation of the resource.
*/
// TODO(#219): Move this code to NavigationTree and remove this method.
getNavTreeJson() {
const resourceJson = {
'text': this.name,
};
return resourceJson;
}
/**
* Renames the resource.
* @param {string} newName New name of the resource.
*/
setName(newName) {
this.name = newName;
}
/**
* Modifies the JSON object that comprises the resource's metadata.
* @param {!Object} obj Object to extend with necessary data.
*/
buildMetadata(obj) {
obj.name = this.name;
obj.resourceType = this.resourceType;
/*
* The ReadWriteController will assign a filepath to the object given to
* buildMetadata. If no filepath has been assigned, or the web attribute is
* missing, the buildMetadata will create these fields.
*/
obj.web = {
export: true,
filepath: this.webFilepath
};
}
} |
JavaScript | class Camera {
constructor() {
this.dirty = false;
/**
* World transform. Moves the universal coordinate system to reflect
* the camera's virtual transformation.
*/
this.world = new Transform();
/**
* Projection matrix that distorts points to create the illusion of
* whatever perspective system is desired.
* @type {mat4}
*/
this.proj = mat4.create();
this._mat = mat4.create();
}
/**
* If dirty, regenerates the internal matrix and returns it.
*/
get matrix() {
if (this.dirty || this.world.dirty) {
mat4.mul(this._mat, this.world, this.proj);
this.dirty = false;
}
return this._mat;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.