language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class Frame {
constructor(id, options={}) {
this.id = id;
this.parent = options.parent || null;
this.children = options.children || new Set();
this.time = options.time || {secs: 0, nsecs: 0};
}
} |
JavaScript | class ClassComp {
constructor() {
this.data = {};
this.data.localState = 'local state!';
this._watcherList = [];
observeData(this.data);
}
changeLocal() {
this.data.localState = this.props.msg;
}
render(h) {
return (
<button onClick={this.changeLocal}>{this.data.localState}</button>
);
}
} |
JavaScript | class TradingWalletFacade {
constructor(tradingWalletTransactionBuilder, erc20TokenService, erc20TokenTransactionBuilder,
transactionLib = TransactionLibBuilder.build(), logger = log) {
if (!logger) {
throw new TypeError(`Invalid "logger" value: ${logger}`)
}
this.log = logger.child({ module: this.constructor.name })
if (!tradingWalletTransactionBuilder) {
const errorMessage = `Invalid "tradingWalletTransactionBuilder" value: ${tradingWalletTransactionBuilder}`
throw new TypeError(errorMessage)
}
this.tradingWalletTransactionBuilder = tradingWalletTransactionBuilder
if (!erc20TokenService) {
const errorMessage = `Invalid "erc20TokenService" value: ${erc20TokenService}`
throw new TypeError(errorMessage)
}
this.erc20TokenService = erc20TokenService
if (!erc20TokenTransactionBuilder) {
const errorMessage = `Invalid "erc20TokenTransactionBuilder" value: ${erc20TokenTransactionBuilder}`
throw new TypeError(errorMessage)
}
this.erc20TokenTransactionBuilder = erc20TokenTransactionBuilder
if (!transactionLib) {
const errorMessage = `Invalid "transactionLib" value: ${transactionLib}`
throw new TypeError(errorMessage)
}
this.transactionLib = transactionLib
}
async throwIfTokenWalletEnought(personalWalletAddress, quantity) {
const assetBalance = await this.erc20TokenService.getBalanceOfAsync(personalWalletAddress)
const assetBalanceToBigNumber = this.transactionLib.web3.toBigNumber(assetBalance)
const quantityToBigNumber = this.transactionLib.web3.toBigNumber(quantity)
if (assetBalanceToBigNumber.lt(quantityToBigNumber)) {
const errorMessage = 'The asset balance is < than the quantity to depoist!'
this.log.info({
personalWalletAddress,
quantity,
assetBalance,
fn: 'checkIfTokenWalletEnought',
},
errorMessage)
throw new QuantityNotEnoughError(errorMessage)
}
}
async depositTokenAsync(personalWalletAddress, tradingWalletAddress, quantity, tokenAddress, privateKey) {
this.log.info({
fn: 'depositTokenAsync',
personalWalletAddress,
tradingWalletAddress,
tokenAddress,
quantity,
}, 'Deposit token.')
let approveToZeroTransactionHash = null
let approveTransactionHash = null
await this.throwIfTokenWalletEnought(personalWalletAddress, quantity)
const allowance = await this.erc20TokenService.getAllowanceAsync(personalWalletAddress, tradingWalletAddress)
const allowanceToInt = +allowance
if (quantity > allowance && allowance > 0) {
this.log.info({
personalWalletAddress,
tradingWalletAddress,
quantity,
tokenAddress,
allowance,
fn: 'depositTokenAsync',
},
'The quantity to deposit is not completely allowed!')
const zeroQuantity = 0
approveToZeroTransactionHash = await this.erc20TokenService.approveTransferAsync(
personalWalletAddress,
tradingWalletAddress,
zeroQuantity,
privateKey,
)
}
const approveTransactionDraftObject = await this.erc20TokenTransactionBuilder.buildApproveTrasferTransactionDraft(
personalWalletAddress,
tradingWalletAddress,
quantity,
)
const gasEstimationForApprove = await this.transactionLib.getGasEstimation(approveTransactionDraftObject)
const nonceForApprove = await this.transactionLib.getNonce(personalWalletAddress)
if (allowanceToInt === 0 || (quantity > allowanceToInt && allowanceToInt > 0)) {
const signedApproveData = await this.transactionLib.sign(
approveTransactionDraftObject,
privateKey,
nonceForApprove,
gasEstimationForApprove.gas,
gasEstimationForApprove.gasPrice,
)
approveTransactionHash = await this.transactionLib.execute(signedApproveData)
}
const depositTokenTransactionDraft = await this.tradingWalletTransactionBuilder
.buildDepositTokenTransactionDraft(personalWalletAddress, tradingWalletAddress, quantity, tokenAddress)
const depositTokenFixedGasEstimation = 100000
const signedTransactionDataForDeposit = await this.transactionLib.sign(
depositTokenTransactionDraft,
privateKey,
nonceForApprove + 1,
depositTokenFixedGasEstimation,
gasEstimationForApprove.gasPrice,
)
const depositTransactionHash = await this.transactionLib
.execute(signedTransactionDataForDeposit, privateKey)
this.log.info({
fn: 'depositTokenAsync',
personalWalletAddress,
tradingWalletAddress,
quantity,
tokenAddress,
approveToZeroTransactionHash,
approveTransactionHash,
depositTransactionHash,
},
'Deposit token completed successfully.')
return {
approveToZeroTransactionHash,
approveTransactionHash,
depositTransactionHash,
}
}
} |
JavaScript | class PersonValidator {
constructor(data = {}) {
this.data = data
this.name = data.Name
this.dates = data.Dates
this.rank = data.Rank
this.rankNotApplicable = data.RankNotApplicable
this.relationship = (data.Relationship || {}).values || []
this.relationshipOther = data.RelationshipOther
this.mobileTelephone = data.MobileTelephone
this.otherTelephone = data.OtherTelephone
this.email = data.Email
this.emailNotApplicable = data.EmailNotApplicable
this.address = data.Address
}
validName() {
return validateName(this.name)
}
validDates() {
return validateDates(this.dates)
}
validRank() {
return validateRank(this.rankNotApplicable, this.rank)
}
validRelationship() {
return validateRelationship(this.relationship, this.relationshipOther)
}
validPhones() {
return validatePhones(this.mobileTelephone, this.otherTelephone)
}
validEmail() {
return validateEmail(this.emailNotApplicable, this.email)
}
validAddress() {
return validateAddress(this.address)
}
isValid() {
return validatePerson(this.data)
}
} |
JavaScript | class AbstractPlayer {
/**
* Creates an instance of AbstractPlayer.
* @memberof AbstractPlayer
*/
constructor() {
this.hand = new Hand();
}
/**
* Empties the player's hand of cards.
*
* @memberof AbstractPlayer
*/
resetHand() {
this.hand.reset();
}
/**
* Adds ta new card to the current hand.
*
* @param {*} card
* @memberof AbstractPlayer
*/
add(card) {
this.hand.add(card);
}
/**
* Determines if the player has a hand with a total of 21.
*
* @returns true if hand is worth 21 points.
* @memberof AbstractPlayer
*/
hasBlackjack() {
return this.hand.getTotal() == 21;
}
/**
* Gets the total value for the player's hand.
*
* @returns the total for the player's hand.
* @memberof AbstractPlayer
*/
getHandTotal() {
return this.hand.getTotal();
}
/**
* Sets the current hand's dirty value.
*
* @param {*} option
* @memberof AbstractPlayer
*/
setDirty(option) {
this.hand.setDirty(option);
}
/**
* Returns true if the player's hand exceeds 21
*
* @returns true if the hands value is over 21
* @memberof AbstractPlayer
*/
isBusted() {
return this.getHandTotal() > 21;
}
} |
JavaScript | class Tree {
constructor() {
this._root = null;
}
createNode(value) {}
delete(value) {}
insert(value) {}
toJson() {
return this._root.toJson();
}
} |
JavaScript | class AwsIntegration extends integration_1.Integration {
constructor(props) {
const backend = props.subdomain ? `${props.subdomain}.${props.service}` : props.service;
const type = props.proxy ? integration_1.IntegrationType.AwsProxy : integration_1.IntegrationType.Aws;
const { apiType, apiValue } = util_1.parseAwsApiCall(props.path, props.action, props.actionParameters);
super({
type,
integrationHttpMethod: 'POST',
uri: new cdk.Token(() => {
if (!this.scope) {
throw new Error('AwsIntegration must be used in API');
}
return this.scope.node.stack.formatArn({
service: 'apigateway',
account: backend,
resource: apiType,
sep: '/',
resourceName: apiValue,
});
}),
options: props.options,
});
}
bind(method) {
this.scope = method;
}
} |
JavaScript | class ExamineAction {
/**
* Create a new ExamineAction
*
* @param {String} target - The target object or thing to examine
*/
constructor(target) {
this.target = target;
}
/**
* Execute the action on the character
*
* @param {Character} character - The character to execute on
*/
async execute(character) {
if (!character.room) {
character.sendImmediate('You are floating in a void');
return;
}
if (!this.target) {
character.sendImmediate('What do you want to examine?');
return;
}
let item = character.room.inanimates.findItem(this.target);
if (!item) {
item = character.room.characters.find(c => c.name === this.target);
}
if (!item) {
item = character.inanimates.findItem(this.target);
}
if (!item) {
character.sendImmediate(`You do not see a ${this.target} here.`);
return;
}
let retVal;
retVal = item.toLongText();
character.sendImmediate(retVal);
}
} |
JavaScript | class ExamineFactory {
/**
* The mapping of this factory to the player command
*
* @return {String}
*/
static get name() {
return 'examine';
}
/**
* Create a new factory
*/
constructor() {
}
/**
* Generate a ExamineAction from the provided player input
*
* @param {Array.<String>} tokens - The text the player provided
*
* @return {ExamineAction} On success, the action to execute, or null
*/
generate(tokens) {
if (!tokens || tokens.length === 0) {
return new ErrorAction({ message: 'What do you want to examine?'});
}
return new ExamineAction(tokens.join(' '));
}
} |
JavaScript | class ArrayCombinerField extends React.Component {
static propTypes = {
uiSchema: PropTypes.shape({
"ui:options": PropTypes.shape({
additionalItemsAmount: PropTypes.number
}),
uiSchema: PropTypes.object
}).isRequired,
schema: PropTypes.shape({
type: PropTypes.oneOf(["object"])
}).isRequired,
formData: PropTypes.object.isRequired
}
static getName() {return "ArrayCombinerField";}
getStateFromProps(props) {
const {additionalItemsAmount} = this.getUiOptions();
let itemSchema = {type: "object", properties: {}, required: props.schema.required};
let schema = {type: "array"};
if (additionalItemsAmount) schema.additionalItems = itemSchema;
if ("title" in props.schema) schema.title = props.schema.title;
Object.keys(props.schema.properties).forEach((propertyName) => {
let propertyOrigin = props.schema.properties[propertyName];
let property = propertyOrigin.items;
if (property.type === "object" || property.type === "array") throw "items properties can't be objects or arrays";
if (propertyOrigin.title) property.title = propertyOrigin.title;
itemSchema.properties[propertyName] = property;
});
schema.items = itemSchema;
if (additionalItemsAmount) {
schema.items = Array(additionalItemsAmount).fill(itemSchema);
schema.additionalItems = itemSchema;
}
const uiSchema = Object.keys(props.schema.properties).reduce((_uiSchema, field) => {
if (field in _uiSchema) {
_uiSchema = {..._uiSchema, items: {...(_uiSchema.items || {}), [field]: _uiSchema[field]}};
immutableDelete(_uiSchema, field);
}
return _uiSchema;
}, props.uiSchema);
function objectsToArray(array, objects) {
if (objects) Object.keys(objects).forEach(dataCol => {
if (objects[dataCol]) for (var row in objects[dataCol]) {
let val = objects[dataCol][row];
if (!array[row]) array[row] = {};
array[row][dataCol] = val;
}
});
return array;
}
function rotateErrorSchema(rotatedErrorSchema, errorSchema) {
if (errorSchema) Object.keys(errorSchema).forEach(property => {
const error = errorSchema[property];
if (property === "__errors") {
rotatedErrorSchema.__errors = error;
} else {
if (error) Object.keys(error).forEach(idx => {
if (idx === "__errors") {
rotatedErrorSchema.__errors = rotatedErrorSchema.__errors ?
[...rotatedErrorSchema.__errors, ...error.__errors] :
error.__errors;
} else {
const propertyError = {[property]: error[idx]};
rotatedErrorSchema[idx] = rotatedErrorSchema[idx] ?
merge(rotatedErrorSchema[idx], propertyError) : propertyError;
}
});
}
});
return rotatedErrorSchema;
}
let errorSchema = rotateErrorSchema({}, props.errorSchema);
let formData = objectsToArray([], props.formData);
formData.forEach((obj) => {
Object.keys(itemSchema.properties).forEach((prop) => {
if (!(prop in obj)) {
obj[prop] = getDefaultFormState(itemSchema.properties[prop], undefined, this.props.registry.definitions);
}
});
});
return {schema, errorSchema, formData, uiSchema};
}
onChange(formData) {
let origArraysContainer = {};
if (!formData || formData.length === 0) {
Object.keys(this.props.schema.properties).forEach((prop) => {
origArraysContainer[prop] = [];
});
} else {
formData.forEach((obj) => {
Object.keys(this.props.schema.properties).forEach((arrName) => {
origArraysContainer[arrName] ?
origArraysContainer[arrName].push(obj[arrName]) :
( origArraysContainer[arrName] = [obj[arrName]] );
});
});
}
this.props.onChange(origArraysContainer);
}
} |
JavaScript | class ClickRule extends MethodRule {
/**
* @param {JQueryElements} $container
*/
bind($container) {
const uniqueId = 'gyClickBound_' + this._method;
// Do not re-bind if click event already bound to container.
if($container.data(uniqueId)) {
return;
}
// Bind to click event.
$container.data(uniqueId, true);
$container.on('click.' + uniqueId, this._selector(), (e) => {
// Call Gigya method attached to the clicked element.
this.method({ $el: $(e.target) });
// Cancel default click event.
e.preventDefault();
});
}
} |
JavaScript | class TickTock {
constructor(options={}) {
this.is_running = false
this.timeout = null
this.missed_ticks = null
this.start_time = 0
this.stop_time = 0
this.time = 0
this.tick = 0
this.interval = (
typeof(options.interval) === 'function'
// use given function
? options.interval
: (
Array.isArray(options.interval)
// map tick to list item
? (time, tick) => options.interval[tick]
// map tick to constant value
: (time, tick) => options.interval
)
)
this.callback = options.callback
this.complete = options.complete
this._tick = this._tick.bind(this)
}
start() {
if (this.is_running) {
throw new Error('Cannot start. TickTock is already running.')
}
this._startTimer(performance.now())
}
// Stop the clock and clear the timeout
stop() {
if (!this.is_running) {
throw new Error('Cannot stop. TickTock is not running.')
}
this.stop_time = this.elapsed()
this.is_running = false
clearTimeout(this.timeout)
}
resume() {
if (this.is_running) {
throw new Error('Cannot resume. TickTock is already running.')
}
this._startTimer(performance.now() - this.stop_time)
}
reset() {
this.start_time = 0
this.time = 0
}
// Get the current clock time in ms.
elapsed() {
if (this.is_running) {
return performance.now() - this.start_time
}
return this.stop_time
}
// Called for every tick.
_tick() {
this.callback(this, this.time, this.tick)
const timeout = this.interval(this.time, this.tick)
if (!timeout) {
this.stop()
this.complete && this.complete(this.time, this.tick, this.stop_time)
return
}
this.time += timeout
this.tick += 1
const next_tick_in = this.start_time + this.time - performance.now()
if (next_tick_in <= 0) {
this.missed_ticks = Math.floor(-next_tick_in / timeout)
this.time += this.missed_ticks * timeout
if (this.is_running) {
this._tick()
}
}
else if (this.is_running) {
this.timeout = setTimeout(this._tick, next_tick_in)
}
}
_startTimer(start_time) {
this.start_time = start_time
this.is_running = true
this.time = 0
this.stop_time = 0
this._tick()
}
} |
JavaScript | class Database {
// Method to getAllNotes
async getAllNotes() {
return readFile('db/db.json', { encoding: 'utf8' }).then((notes) => {
try {
return JSON.parse(notes);
} catch (error) {
return JSON.parse([]);
}
});
}
// Method to addNote
async addNote({ title, text }) {
if (!title || !text) {
throw new Error("Note 'title' and 'text' cannot be blank");
}
const note = { title, text, id: uuidv4() };
let allNotes = await this.getAllNotes();
allNotes = [].concat(allNotes, note);
console.log(allNotes);
writeFile('db/db.json', JSON.stringify(allNotes));
return allNotes;
}
// Method to deleteNote
async deleteNote(id) {
console.log(id);
let allNotes = await this.getAllNotes();
allNotes = allNotes.filter((note) => note.id !== id);
writeFile('db/db.json', JSON.stringify(allNotes));
return allNotes;
}
} |
JavaScript | class DataManagerContainer extends React.Component {
static defaultProps = {
renderLoading: () => null,
};
constructor(props, context) {
super(props, context);
this.state = { result: {} };
this.query = props.component.getQuery(props.variables);
this.query.on('update', this._handleDataChanges.bind(this));
this._executeQuery();
}
_executeQuery() {
this._resolved = false;
this.query.execute().then((result) => {
this._resolved = true;
this.setState({ result });
});
}
_handleDataChanges(result) {
if (this._resolved) {
this.setState({ result });
}
}
componentWillUnmount() {
this.query.stop();
}
componentWillReceiveProps(nextProps) {
this.query.updateVariables(nextProps);
}
renderLoading() {
return this.props.renderLoading();
}
render() {
const Component = this.props.component; // eslint-disable-line
return this._resolved
? <Component {...this.props} {...this.state.result} />
: this.renderLoading();
}
} |
JavaScript | class CharacterClass {
/**
*
* @param {CharacterClassProps}
*/
constructor({ name, stats: { health, mana, strength, defense } = {}, abilities = [] }) {
/**
* the name of this CharacterClass
* @type {string}
*/
this.name = name;
/**
* this CharacterClass's attribute ranges
* @type {CharacterClassAttributeRanges}
*/
this.stats = {
health: { min: 0, max: 0, ...health },
mana: { min: 0, max: 0, ...mana },
strength: { min: 0, max: 0, ...strength },
defense: { min: 0, max: 0, ...defense },
};
/**
* this CharacterClass's default abilities
* @type {Array<Ability>}
*/
this.abilities = abilities;
}
/**
*
* @param {string} stat - the type of stat to generate
* @returns {number} a random value in the given stat's range
*/
#generateStat(stat) {
if (this.stats[stat] == null) throw new Error(`no such stat ${stat}`);
const min = this.stats[stat].min ?? 0;
const max = this.stats[stat].max ?? 0;
return min + Math.floor((max - min) * Math.random());
}
/**
*
* @param {CharacterAttributes} bonuses - amounts to add to each generated stat
* @returns {CharacterAttributes} randomly varied CharacterAttributes
*/
generateStats({ health, mana, strength, defense } = {}) {
return {
health: this.#generateStat('health') + (health ?? 0),
mana: this.#generateStat('mana') + (mana ?? 0),
strength: this.#generateStat('strength') + (strength ?? 0),
defense: this.#generateStat('defense') + (defense ?? 0),
};
}
} |
JavaScript | class TabDOMUtil {
/**
* Function generates select div node.
*
* @param {*} label
* @param {*} id
* @param {*} action
* @param {*} options
*/
static createSelectDiv(label, id, action, options) {
let div = document.createElement('div');
if(label != null) {
div.appendChild(document.createTextNode(label + ": "))
}
div.appendChild(TabDOMUtil.createSelect(id, action, options));
return div;
}
/**
* Function generates select node.
*
* @param {*} id
* @param {*} action
* @param {*} options
* @param {*} className
*/
static createSelect(id, action, options, className) {
let select = document.createElement('select');
select.setAttribute("id", id);
if(className) {
select.classList.add(className);
}
select.onchange = action;
TabDOMUtil.appendOptions(select, options);
return select;
}
/**
* Function genearates option nodes.
*
* @param {*} select
* @param {*} options
*/
static appendOptions(select, options) {
let option;
for(let i = 0; i < options.length; i++) {
option = select.appendChild(document.createElement("option"));
option.setAttribute("value", options[i]);
option.innerHTML = options[i];
}
}
/**
* Function generates input text node.
*
* @param {*} size
* @param {*} className
*/
static createTextInput(size, className) {
let input = document.createElement('input');
input.setAttribute("type", "text");
if(size) {
input.setAttribute("size", size);
}
if(className) {
input.classList.add(className);
}
return input;
}
/**
* Function generates button node.
*
* @param {*} label
* @param {*} action
*/
static createButton(label, action, id) {
let btn = document.createElement('button');
btn.setAttribute("type", "button");
btn.setAttribute("id", id);
btn.innerHTML = label;
btn.onclick = action;
return btn;
}
/**
* Function generates label heading node.
*
* @param {*} label
*/
static createSidebarHeading(label) {
let heading = document.createElement('strong');
heading.innerHTML = label;
return heading;
}
/*
* Sets multiple element attributes
*/
static setAttributes(element, keyArray, valueArray){
if (keyArray.length == valueArray.length) {
for (var i = keyArray.length - 1; i >= 0; i--) {
element.setAttribute(keyArray[i], valueArray[i]);
}
}
}
} |
JavaScript | class Storage {
constructor() {
// noinspection JSCheckFunctionSignatures
this._entity1 = new Entity1(new Mongo(config.get('mongodb')));
this._entity2 = new Entity2(redis);
// noinspection JSCheckFunctionSignatures
this._credentials = new Credentials(new Mongo(config.get('mongodb')));
}
/**
* Init stores
* @return {Promise<void>}
*/
async init() {
await Promise.all([
this._entity1.init(),
this._credentials.init(),
]);
}
/**
* Getter for Entity1Store store
* @return {Entity1Store}
*/
get entity1() {
return this._entity1;
}
/**
* Getter for Entity2Store store
* @return {Entity2Store}
*/
get entity2() {
return this._entity2;
}
/**
* Getter for CredentialsStore store
* @return {CredentialsStore}
*/
get credentials() {
return this._credentials;
}
} |
JavaScript | class StringFrom extends AsyncObject {
constructor (obj) {
super(obj)
}
syncCall () {
return (obj) => {
return obj.toString()
}
}
} |
JavaScript | class Database extends Dexie {
// The constructor creates the database titled myDatabase, with a single
// object store for sticky notes.
constructor(namespace) {
// Use the Dexie constructor to create the database and get back a Dexie
// object that represents the database.
super(Database.dbName(namespace));
// Now that we have our Dexie object, we define a sticky notes object store
// using the "stores" method. The indices we put on the store are:
//
// - ++id, which makes the "id" field on our sticky notes an
// auto-incrementing primary key, similar to how in plain IndexedDB you
// would specify autoIncrement: true
// - timestamp, so we can retrieve sticky notes in order by timestamp.
//
// You can see information on all types of indices you can create at
// https://dexie.org/docs/Version/Version.stores()
this.version(1).stores({
notes: '++id,timestamp',
});
// Keep a reference to the notes store, called a dexie Table, so that we
// can then run Dexie methods from that Table.
this.notes = this.table('notes');
}
// addStickyNote adds a sticky note with the text passed in to the "notes"
// object store. Returns a promise that resolves when the sticky note is
// successfully added.
addStickyNote(message) {
return this.notes.add({
text: message,
timestamp: new Date(),
});
}
// getNotes retrieves all sticky notes from the "notes" object store. Returns
// a promise that resolves when we successfully retrieve the sticky notes,
// giving us the notes in an array.
getNotes(reverseOrder) {
return reverseOrder ?
this.notes.orderBy('timestamp').reverse().toArray() :
this.notes.orderBy('timestamp').toArray();
}
// dbName sets up the name of the database using an optional namespace
// parameter for test coverage.
static dbName(namespace) {
return namespace != undefined ?
`my_db_${namespace}` :
'my_db';
}
} |
JavaScript | class Hello {
constructor(...params) {
this._params = params;
}
run() {
console.log(this._params);
}
} |
JavaScript | class Battle extends Event {
static WEIGHT = WEIGHT;
static operateOn(player) {
if(player.level <= SETTINGS.minBattleLevel) return;
if(player.$personalities.isActive('Coward') && Event.chance.bool({ likelihood: 75 })) return;
if(!player.party) {
const partyInstance = new PartyClass({ leader: player });
partyInstance.isBattleParty = true;
}
const monsters = MonsterGenerator.generateMonsters(player.party);
const monsterPartyInstance = new PartyClass({ leader: monsters[0] });
if(monsters.length > 1) {
for(let i = 1; i < monsters.length; i++) {
monsterPartyInstance.playerJoin(monsters[i]);
}
}
const parties = [player.party, monsterPartyInstance];
const introText = this.eventText('battle', player, { _eventData: { parties } });
const battle = new BattleClass({ introText, parties });
this.emitMessage({ affected: player.party.players, eventText: introText, category: MessageCategories.COMBAT, extraData: { battleName: battle._id } });
try {
battle.startBattle();
} catch(e) {
Logger.error('Battle', e, battle.saveObject());
}
if(player.party.isBattleParty) {
player.party.disband();
}
return [player];
}
} |
JavaScript | class UDPConnection {
constructor(address, port, family, socket) {
this.address = address;
this.port = port;
this.family = family;
this.socket = socket;
}
send(buffer, callback) {
this.socket.send(buffer, this.port, this.address, callback);
}
} |
JavaScript | class Injector{
constructor(){
this.includePaths = []; // a list of paths to search for include files
this._fileMap = {}; // a dictionary of filenames to file location
this._field = "LuaScript"; // the name of the field to inject to
this._extension = ".tua";
this.transpile = true;
}
set extension(value){
this._extension = value;
}
get extension(){
return this._extension;
}
set field(value){
this._field = value;
}
get field(){
return this._field;
}
get filemap(){
return structuredClone(this._fileMap);
}
get rootGameObject(){
return structuredClone(this._rootGameObject);
}
clearFilemap(){
this._fileMap = {}
}
/**
* @param {*} projectDirectory Location of project directories and files.
* @param {*} sourceDirectory Location of source files within project directory.
*/
inject(projectDirectory, sourceDirectory = Constants.SCRIPT_DIR){
this.projectDirectory = projectDirectory;
// create a filename -> fullpath dictionary of all files in target directory
const targetDirectory = Path.join(this.projectDirectory, sourceDirectory);
const files = getFiles(targetDirectory);
this._fileMap = Object.assign({}, ...files.map(x=>({[x.name] : x.fullpath})));
const gameFilePath = Path.join(projectDirectory, Constants.STRIPPED_FILE);
this._rootGameObject = this._rootGameObject ?? loadJSON(gameFilePath);
this.injectObject(this._rootGameObject);
return this._rootGameObject;
}
addIncludePath(...paths){
for (const path of paths) this.includePaths.push(path);
}
/**
* If there is a file that matches the object's GUID as determined by getFilename
* then set the "Luascript" field value to the contents of the file.
* @param {} objectState The json object found in the game file
*/
injectObject(objectState){
const filename = Path.basename(getFilename(objectState, this.extension));
/* inject script into object */
if (this._fileMap[filename]){
if (this.transpile){
const tuaTranslator = new TuaTranslator();
tuaTranslator.addIncludePath(...this.includePaths);
tuaTranslator.addSource(this._fileMap[filename]);
tuaTranslator.parseClasses();
objectState[this.field] = tuaTranslator.toString();
} else {
const fileContents = FS.readFileSync(this._fileMap[filename], "utf-8");
objectState[this.field] = fileContents;
}
}
const childStates = objectState["ContainedObjects"] ?? objectState["ObjectStates"];
/* recurse over any contained objects */
if (childStates){
for(const childState of childStates){
this.injectObject(childState);
}
}
}
writeDebugFiles(projectDirectory = ".", objectState = this._rootGameObject){
if (objectState[this.field] !== ""){
const name = getFilename(objectState, this.extension);
const fullpath = Path.join(projectDirectory, Constants.PACKED_DIRECTORY, name);
const dir = Path.dirname(fullpath);
if (!FS.existsSync(dir)) FS.mkdirSync(dir, {recursive : true});
FS.writeFileSync(fullpath, objectState[this.field]);
}
const childStates = objectState["ContainedObjects"] ?? objectState["ObjectStates"];
/* recurse over any contained objects */
if (childStates){
for(const childState of childStates){
this.writeDebugFiles(projectDirectory, childState);
}
}
}
} |
JavaScript | class VigenereCipheringMachine {
constructor(value = true) {
this.direct = value;
this.alphabet = getAlphabeticString("A","Z");
}
encrypt(str, key) {
if (!str || !key){
throw Error("Incorrect arguments!")
}
let crypt_str = ""
let str_upper = str.toUpperCase();
let key_upper = key.toUpperCase();
let key_length = key.length;
let i = 0;
for (let char of str_upper){
let position = this.alphabet.indexOf(char);
if (position > -1) {
if (i > key_length - 1){
i = 0;
}
let position_key = this.alphabet.indexOf(key_upper[i]);
let letter_shift = ((position + position_key) % 26)
crypt_str += this.alphabet[letter_shift];
i++;
} else {
crypt_str += char;
}
}
if (!this.direct){
crypt_str = crypt_str.split(" ")
.map((n)=> n.split("").reverse().join("")).reverse().join(" ");
}
return crypt_str
}
decrypt(str, key) {
if (!str || !key){
throw Error("Incorrect arguments!")
}
let crypt_str = ""
let str_upper = str.toUpperCase();
let key_upper = key.toUpperCase();
let key_length = key.length;
let i = 0;
for (let char of str_upper){
let position = this.alphabet.indexOf(char);
if (position > -1) {
if (i > key_length - 1){
i = 0;
}
let position_key = this.alphabet.indexOf(key_upper[i]);
let letter_shift = (position - position_key) % 26
if (letter_shift <= -1){
crypt_str += this.alphabet[26 + letter_shift];
} else {
crypt_str += this.alphabet[letter_shift];
}
i++;
} else {
crypt_str += char;
}
}
if (!this.direct){
crypt_str = crypt_str.split(" ")
.map((n)=> n.split("").reverse().join("")).reverse().join(" ");
}
return crypt_str
}
get getDirect (){
return this.direct;
}
} |
JavaScript | class AuthRegisterActions{
protectedApiRequest(){
return{
type: AUTH_REGISTER_REQUEST
}
}
protectApiFailure(error, message, json){
if(json.username !== undefined){
message += " Username: "+json.username
}
if(json.password !== undefined){
message += " Password: "+json.password
}
if(json.detail !== undefined){
message += " Detail: "+json.detail
}
return{
type: AUTH_REGISTER_FAILURE,
error: error,
style: "danger",
text: message
}
}
protectedApiSuccess(data){
// Response to successful register : {"id":7,"username":"a","password":"b","merges":[]}
return{
type: AUTH_REGISTER_SUCCESS,
style: "success",
text: "Now you can login."
}
}
} |
JavaScript | class KeyboardInputModule {
constructor() {
/**
* @type {Set<KeyboardEventHandler>}
* @private
*/
this.handlers = new Set();
for (let eventType in KeyboardInputModule.EventTypes) {
let eventName = KeyboardInputModule.EventTypes[eventType];
document.addEventListener(eventName, (event) => {
if (document.activeElement === document.body || document.activeElement === null) {
// Only listen if nothing else is in focus.
// TODO: Make it so that it must be focused on the target element. How?
for (let handler of this.handlers) {
handler(eventName, event.key, event);
}
if (event.keyCode <= 40 && event.keyCode >= 37) {
event.preventDefault();
} else if (event.keyCode === 32) {
event.preventDefault();
}
}
});
}
}
/**
* Attaches an event listener.
* For now, only allow all or nothing.
* The handler should decide what to do with everything else by itself.
* @param {KeyboardEventHandler} handler The event handler to attach
*/
addEventListener(handler) {
this.handlers.add(handler);
}
/**
* Removes an event listener.
* @param {KeyboardEventHandler} handler The handler to remove.
*/
removeEventListener(handler) {
this.handlers.delete(handler);
}
} |
JavaScript | class Room extends EventEmitter {
/**
* A new room for a new day
* @param {string} id Room id (or alias or full url)
* @param {string} [nick] Nickname
* @param {Object} [options] Room options
* @param {string} [options.password] Room password
* @param {string} [options.key] Room key (aka session password)
* @param {Room} [options.other] Other room (to take login info from)
*/
constructor(id, nick, options) {
options = options || {};
const {password = "", key = "", other = null} = options;
id = parseId(id);
if (!id) {
throw new VolaError("No room id provided");
}
super();
this.config = {site: DEFAULT_SITE, loaded: false};
gettable(this, "password");
gettable(this, "key");
this.alias = this.id = id;
this.nick = (other && other.nick) || nick;
verifyNick(this.nick);
this.time_delta = 0;
this._uploadCount = 0;
this.password = password;
this.key = key;
this.ack = this.sack = this.last_sack = -1;
this.users = 0;
this[FILES] = new Map();
this.headers = Object.assign({}, (other && other.headers || HEADERS));
if (!this.headers.Cookie) {
this.headers.Cookie = new CookieJar("allow-download=1");
}
this.userInfo = {};
this.janitor = this.owner = this.admin = this.connected = false;
this.handler = new Handler(this);
this.closed = false;
this._closing = null;
const {Message: MessageCtor = Message} = options;
this.Message = MessageCtor || Message;
const {File: FileCtor = File} = options;
this.File = FileCtor || File;
this.on("file", file => {
this[FILES].set(file.id, file);
});
this.on("delete_file", fid => {
let file = this[FILES].get(fid);
if (file) {
file.removed = true;
this[FILES].delete(fid);
}
});
}
get url() {
const {config = {}} = this;
const {site = "volafile.org"} = config;
return `https://${site}/r/${this.alias}`;
}
get files() {
this.expireFiles();
return Array.from(this[FILES].values());
}
get privileged() {
return this.owner || this.admin || this.janitor;
}
/**
* So you got a password?
* @param {string} password
* @throws {Error} o_O
*/
async login(password) {
await this.ensureConfig();
const resp = await this.callREST("login", {
name: this.nick,
password
});
if (resp.error) {
throw new VolaError(`Failed to log in: ${resp.error.message || resp.error}`);
}
this.session = resp.session;
this.headers.Cookie.set("session", this.session);
debug(this.headers);
this.nick = resp.nick;
if (this.connected) {
this.call("useSession", this.session);
}
}
changeNick(nick) {
verifyNick(nick);
this.call("command", this.nick, "nick", nick);
}
/**
* Without this life is boring!
*/
async connect() {
for (let attempt = 1; ; ++attempt) {
let resolve;
let reject;
const messageWaiter = new Promise((res, rej) => {
resolve = res;
reject = rej;
this.prependOnceListener("connected", resolve);
this.prependOnceListener("error", reject);
});
try {
await this.openConnection();
await messageWaiter;
return;
}
catch (ex) {
if (ex.description && /response: 5\d{2}$/i.test(ex.description.message)) {
await sleep(200 * attempt);
continue;
}
throw ex;
}
finally {
this.removeListener("connected", resolve);
this.removeListener("error", reject);
}
}
}
async openConnection() {
await this.ensureConfig();
this.id = this.config.room_id;
debug(this.config);
const params = new URLSearchParams({
room: this.id,
cs: this.config.checksum2,
nick: this.nick,
rn: Math.random()
});
if (this.password) {
params.append("password", this.password);
}
else if (this.key) {
params.append("key", this.key);
}
const url = `wss://${this.config.site}/api/?${params}`;
const extraHeaders = Object.assign({
Origin: `https://${this.config.site}`,
Referer: this.url,
}, this.headers);
debug(url);
await new Promise((resolve, reject) => {
this.closed = false;
this.eio = new EIO(url, {
path: "/api",
extraHeaders,
transports: ["websocket"],
});
this.eio.on("ping", async () => {
try {
this.sendAck();
await Promise.race([
deadline(20 * 1000),
new Promise(resolve => this.eio.once("pong", resolve)),
]);
}
catch (ex) {
this.emit("error", ex);
try {
await this.close();
}
catch (ex) {
// ignored
}
}
});
this.eio.on("open", () => {
if (this.closed) {
return;
}
this.eio.on("error", data => {
this.closed = true;
/**
* This Room is rekt
* @event Room#error
* @type {Error}
*/
this.emit("error", data);
this.removeAllListeners();
});
this.eio.on("close", data => {
this.closed = true;
/**
* This Room is no mo
* @event Room#close
* @type {object} Close data per socket
*/
this.emit("close", data);
this.removeAllListeners();
reject(data);
});
/**
* Connection is now open, but not necessarily usable.
* @event Room#open
*/
this.emit("open");
resolve();
});
this.eio.on("message", data => {
if (this.closed) {
return;
}
this.handler.onmessage(data);
});
this.eio.once("close", data => {
this.closed = true;
reject(data);
});
this.eio.once("error", data => {
this.closed = true;
reject(data);
});
});
}
/**
* Run until this room somehow closes.
* @returns {reason}
* Resolving when the room is closed or rejecting on error
*/
async run() {
await new Promise((resolve, reject) => {
this.on("error", reject);
this.once("close", resolve);
});
}
/**
* LIFE SHOULD BE BORING!
*/
async close() {
this.closed = true;
if (!this.eio) {
return;
}
if (!this._closing) {
this._closing = this._close();
}
try {
await this._closing;
}
finally {
this._closing = null;
}
}
async _close() {
if (!this.eio) {
return;
}
await this.sendClose();
this.eio.close();
delete this.eio;
}
/**
* Say something profound!
* @param {string} msg MUST BE PROFOUND!
* @param {object} [options] Such as .me and .admin
* @throws {VolaError}
*/
chat(msg, options = {}) {
if (typeof (msg) !== "string") {
throw new VolaError("Not a string message");
}
if (!msg.length) {
throw new VolaError("Empty message");
}
if (msg.length > this.config.chat_max_message_length) {
throw new VolaError("Message too long");
}
const {me = false, admin = false} = options || {};
if (admin) {
if (!this.admin && !this.staff) {
throw new VolaError("Cannot /achat");
}
this.call("command", this.nick, "a", msg);
}
else if (me) {
this.call("command", this.nick, "me", msg);
}
else {
this.call("chat", this.nick, msg);
}
}
/**
* Some specific file you had in mind?
* @param {string} id
* @returns {File}
*/
getFile(id) {
const file = this[FILES].get(id);
if (file && file.expired) {
this[FILES].delete(id);
return null;
}
return file;
}
/**
* Some specific file you had in mind? But wait for it!
* @param {string} id
* @param {number} [timeout]
* @returns {File}
*/
waitFile(id, timeout = 10 * 1000) {
const file = this[FILES].get(id);
if (file && file.expired) {
this[FILES].delete(id);
return null;
}
return Promise.race([
new Promise(resolve => this.once(`file-${id}`, resolve)),
deadline(timeout || 10 * 1000)
]);
}
/**
* Report a room
* @param {string} reason
*/
report(reason) {
this.call("submitReport", {reason});
}
/**
* Cleaning the flow
* @param {string[]} ids
* @throws {VolaPrivilegeError}
*/
deleteFiles(ids) {
if (!this.privileged) {
throw new VolaPrivilegeError();
}
if (!Array.isArray(ids)) {
ids = [ids];
}
this.call("deleteFiles", ids);
}
/**
* Everybody should upload THIS!
* @param {string[]} ids
* @throws {VolaPrivilegeError}
*/
whitelistFiles(ids) {
if (!this.admin) {
throw new VolaPrivilegeError();
}
if (!Array.isArray(ids)) {
ids = [ids];
}
this.call("whitelistFiles", ids);
}
/**
* Remove messages
* @param {string[]} ids
*/
removeMessages(ids) {
if (!this.admin) {
throw new VolaPrivilegeError();
}
if (!Array.isArray(ids)) {
ids = [ids];
}
this.call("removeMessages", ids);
}
/**
* Nobody should upload THIS!
* @param {string[]} ids
* @param {object} [options]
* @throws{VolaPrivilegeError}
*/
blacklistFiles(ids, options) {
if (!this.admin) {
throw new VolaPrivilegeError();
}
const o = Object.assign({}, {
hours: 0,
reason: "",
ban: false,
hellban: false,
mute: false}, options);
if (!o.hours || o.hours <= 0) {
throw new VolaError("Invalid BL duration");
}
if (!Array.isArray(ids)) {
ids = [ids];
}
this.call("blacklistFiles", ids, options);
}
/**
* Ban some moron
* @param {object} spec
* @param {object} [options]
* @throws {VolaPrivilegeError}
* @throws {VolaError}
*/
ban(spec, options) {
if (!this.admin) {
throw new VolaPrivilegeError();
}
spec = toBanSpec(spec);
const o = Object.assign({}, {
hours: 0,
reason: "",
purgeFiles: false,
ban: false,
hellban: false,
mute: false}, options);
if (!o.hours || o.hours <= 0) {
throw new VolaError("Invalid ban duration");
}
if (!o.ban && !o.hellban && !o.mute && !o.purgeFiles) {
throw new VolaError("You gotta do something to a moron");
}
this.call("banUser", spec, o);
}
/**
* Unban some moron
* @param {Object} spec
* @param {object} [options]
* @throws {VolaPrivilegeError}
* @throws {VolaError}
*/
unban(spec, options) {
if (!this.admin) {
throw new VolaPrivilegeError();
}
spec = toBanSpec(spec);
const o = Object.assign({}, {
reason: "",
ban: false,
hellban: false,
mute: false,
timeout: false}, options);
if (!o.ban && !o.hellban && !o.mute && !o.timeout) {
throw new VolaError("You gotta do something to a moron");
}
this.call("unbanUser", spec, o);
}
async setConfig(key, value) {
if (!this.privileged) {
throw new VolaPrivilegeError();
}
const resp = await this.callREST("setRoomConfig", {
room: this.id,
session: this.session,
c: cid++,
config: JSON.stringify({[key]: value}),
});
if (resp.error) {
throw new Error(resp.error.message || resp.error);
}
return resp;
}
/**
* You are the owner, but you really don't wanna be
* @param {string} newOwner Somebody to suffer
*/
async transferOwner(newOwner) {
if (!this.owner && !this.admin) {
throw new VolaPrivilegeError();
}
newOwner = (newOwner || "").trim().toLowerCase();
if (!newOwner) {
throw new Error("newOwner may not be empty");
}
await this.setConfig("owner", newOwner);
}
/**
* Add a janitor
* @param {string} janitor Somebody to suffer (a little less)
*/
async addJanitor(janitor) {
if (!this.owner && !this.admin) {
throw new VolaPrivilegeError();
}
janitor = (janitor || "").trim().toLowerCase();
if (!janitor) {
throw new Error("newOwner may not be empty");
}
if (this.config.janitors.has(janitor)) {
return;
}
const janitors = new Set(this.config.janitors);
janitors.add(janitor);
await this.setConfig("janitors", Array.from(janitors));
this.config.janitors.add(janitor);
}
/**
* Remove a janitor
* @param {string} janitor Somebody to suffer (a little less)
*/
async removeJanitor(janitor) {
if (!this.owner && !this.admin) {
throw new VolaPrivilegeError();
}
janitor = (janitor || "").trim().toLowerCase();
if (!janitor) {
throw new Error("newOwner may not be empty");
}
if (!this.config.janitors.has(janitor)) {
return;
}
const janitors = new Set(this.config.janitors);
janitors.delete(janitor);
await this.setConfig("janitors", Array.from(janitors));
this.config.janitors.delete(janitor);
}
/**
* Uploads a file to this room
* @param {object} options Upload options
* @param {string} [options.file] File to upload (stream has preference!).
* Files are resumable.
* @param {string} [options.name] Name to upload file with. If not given, it
* will be derived from file property. If neither property is given, an
* Error is thrown!
* @param {Object} [options.stream] A supported stream, buffer or string. If
* provided the file property will be ignored (except for deriving a name).
* @param {Number} [options.highWaterMark] A highWaterMark for the file stream
* @param {callback} [options.progress] Upload progress callback.
* @returns {Object} Upload result, containing the file `.id` and
* optionally the local(!) `.checksum` of the file/stream.
*/
async uploadFile(options) {
options = options || {};
let {name = null, stream = null} = options;
const {file = null, progress = null, highWaterMark = 0} = options;
if (!stream) {
if (!file) {
throw new VolaError("Need to provide a .stream or a .file");
}
stream = fs.createReadStream(file, highWaterMark ? {
encoding: null,
highWaterMark
} : {
encoding: null,
});
}
else if (typeof stream === "string") {
stream = Buffer.from(stream, "utf-8");
}
if (!name) {
if (!file) {
throw new VolaError("No .name or .file provided");
}
const {base} = path.parse(file);
name = base;
}
if (progress && typeof progress !== "function") {
throw new VolaError("progress must be a function");
}
const key_info = await this._getUploadKey();
let resumed = 0;
for (;;) {
try {
const rv = await this._uploadFile(name, stream, progress, key_info);
try {
stream.close();
}
catch (ex) {
// ignored
}
if (resumed) {
delete rv.checksum;
}
return rv;
}
catch (ex) {
try {
stream.close();
}
catch (ex) {
// ignored
}
if (!file || ex.toString().match(/user\s*abort/i)) {
throw ex;
}
const {key, server} = key_info;
const qs = {
key,
c: ++this._uploadCount
};
const resume = await this.callREST(`https://${server}/rest/uploadStatus`, qs);
if (resume.ended) {
throw ex;
}
if (!Number.isSafeInteger(resume.receivedBytes)) {
throw ex;
}
key_info.startAt = resume.receivedBytes;
stream = fs.createReadStream(file, highWaterMark ? {
encoding: null,
highWaterMark,
start: key_info.startAt,
} : {
encoding: null,
start: key_info.startAt,
});
key_info.resumed = ++resumed;
}
}
}
async _getUploadKey() {
for (;;) {
const qs = {
name: this.nick,
room: this.id,
c: ++this._uploadCount
};
if (this.password) {
qs.password = this.password;
}
else if (this.key) {
qs.roomKey = this.key;
}
const params = await this.callREST("getUploadKey", qs);
const {key = null, server = null, file_id = null} = params;
if (!key || !server || !file_id) {
const {error = {}} = params;
const {info = {}} = error;
const {timeout = null} = info;
if (timeout) {
/**
* Upload is blocked temporarily by the flood protection, but will
* be retried after the timeout expires
* @event Room#upload_blocked
* @type {Number} Number of ms the block is active
*/
this.emit("upload_blocked", timeout);
await sleep(timeout);
continue;
}
if (error.code === ACCESS_DENIED) {
throw new VolaPrivilegeError(`Failed to get upload key: ${error.name} / ${error.message}`);
}
throw new VolaError(`Failed to get upload key: ${error.name} / ${error.message}`);
}
return {key, server, file_id};
}
}
_uploadFile(name, body, progress_callback, key_info) {
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve, reject) => {
let stream = body;
const error = err => {
reject(err);
};
try {
const {startAt = 0, resumed = 0} = key_info;
const checksum = crypto.createHash("md5");
let form = new FormData();
checksum.on("error", error);
if (Buffer.isBuffer(stream)) {
form.append("file", stream, name);
checksum.end(stream);
}
else {
const opts = {
filename: name,
};
if (stream.knownLength) {
opts.knownLength = stream.knownLength;
}
else if ("httpModule" in stream) {
const {response = {}} = stream;
const {headers = {}} = response;
let {"content-length": length} = headers;
length = +length;
if (isFinite(length) && length) {
opts.knownLength = length;
}
}
stream.on("error", error);
stream = stream.pipe(new TeeTransform(checksum));
form.append("file", stream, opts);
}
const {key, server, file_id} = key_info;
const length = await promisify(form.getLength.bind(form))();
const headers = Object.assign({
"Origin": `https://${this.config.site}`,
"Referer": this.url,
"Connection": "close",
"Content-Length": length,
}, this.headers, form.getHeaders());
if (stream.on) {
stream.on("error", error);
}
form.on("error", error);
if (progress_callback) {
const progress = new ProgressTransform();
let cur = startAt;
progress.on("progress", delta => {
cur += delta;
progress_callback(delta, cur, length, server, resumed);
});
progress.on("error", error);
form = form.pipe(progress);
}
const params = new URLSearchParams({
room: this.id,
key,
filename: name
});
if (startAt > 0) {
params.append("startAt", startAt);
}
if (this.password) {
params.append("password", this.password);
}
else if (this.key) {
params.append("roomKey", this.key);
}
const url = `https://${server}/upload?${params}`;
if (body.resume) {
body.resume();
}
const req = await this.fetch(url, {
method: "POST",
body: form,
headers
});
const resp = await req.text();
if (req.status !== OK) {
throw new VolaError(`Upload failed! ${resp}`);
}
if (!Buffer.isBuffer(stream)) {
checksum.end();
}
resolve({
id: file_id,
checksum: checksum.read().toString("hex")
});
}
catch (ex) {
reject(ex);
}
});
}
call(fn, ...args) {
if (!this.connected) {
throw new VolaError("Room is not connected");
}
const call = JSON.stringify([
this.sack,
[[0, ["call", { fn, args }]], ++this.ack]
]);
this.last_sack = this.sack;
debug("calling", call);
if (this.eio) {
this.eio.send(call);
}
}
callWithCallback(fn, ...args) {
const [id, promise] = this.handler.registerCallback();
args.push(id);
this.call(fn, ...args);
return promise;
}
sendAck() {
if (!this.connected || this.last_sack === this.sack) {
return;
}
const call = JSON.stringify([this.sack]);
this.last_sack = this.sack;
this.eio.send(call);
}
async sendClose() {
if (!this.connected) {
throw new VolaError("Room is not connected");
}
const call = JSON.stringify([
this.sack,
[[2], ++this.ack]
]);
try {
const send = promisify(this.eio.send.bind(this.eio));
await Promise.race([
deadline(10 * 1000),
send(call, null)
]);
}
catch (ex) {
console.error("failed to send close", ex);
}
}
fetch(url, options = {}) {
if (!url.includes(this.config.site)) {
throw new VolaError(`Only use this method with ${this.config.site} resources`);
}
let {headers = {}} = options;
headers = Object.assign({}, this.headers, headers);
return fetch(url, Object.assign({}, options, {headers}));
}
async callREST(endpoint, params) {
params = new URLSearchParams(params);
for (let attempt = 1; ; ++attempt) {
const u = new URL(endpoint, `https://${this.config.site}/rest/`);
u.search = params;
const resp = await this.fetch(
u.toString(), {
method: "GET",
headers: {
Origin: `https://${this.config.site}`,
Referer: this.url
}
});
if (resp.status && resp.status >= 500) {
await sleep(100 * attempt);
continue;
}
try {
return await resp.json();
}
catch (ex) {
if (resp.status && resp.status >= 500) {
await sleep(100 * attempt);
continue;
}
throw ex;
}
}
}
async ensureConfig() {
if (this.config.loaded) {
return;
}
const config = await this.callREST("getRoomConfig", {room: this.id});
if (!config) {
throw new VolaError("Failed to get config");
}
if (config.error) {
throw new VolaError(`${config.error.code}: ${config.error.message}`);
}
this.updateConfig(config);
configurable(this, "motd");
configurable(this, "name");
configurable(this, "adult");
configurable(this, "disabled", true);
configurable(this, "file_ttl", true);
}
updateConfig(config) {
if (config && !config.password) {
// Lain decided it's sane to return an empty password
delete config.password;
}
Object.assign(this.config, DEFAULT_CONFIG, config || {}, {loaded: true});
if ("room_id" in this.config) {
this.id = this.config.room_id;
}
if ("custom_room_id" in this.config) {
this.alias = this.config.custom_room_id;
}
this.config.janitors = new Set(this.config.janitors);
verifyNick(this.nick, this.config);
}
fixTime(time) {
return time - this.time_delta;
}
expireFiles() {
const expired = [];
this[FILES].forEach((file, fid) => {
if (file.expired) {
expired.push(fid);
}
});
for (const e of expired) {
this[FILES].delete(e);
}
}
toString() {
return `<Room(${this.id} (${this.alias}), ${this.nick})>`;
}
} |
JavaScript | class CommentList extends Component {
static propTypes = {
/**
* Comments
*/
comments: PropTypes.object
}
/**
* Creates an instance of CommentList.
* @param {any} props
* @memberof CommentList
*/
constructor(props) {
super(props)
const { comments } = props
this.animatedValue = []
for (var index = 1; index < (Object.keys(comments).length + 1); index++) {
this.animatedValue[index] = new Animated.Value(0)
}
}
animation = () => {
const { comments } = this.props
let animationList = []
Object.keys(comments).forEach((item, index) => {
animationList.push(Animated.timing(this.animatedValue[index+1], {
toValue: 1,
duration: 1000
}))
animationList.push(Animated.timing(this.animatedValue[index+1], {
toValue: 0,
duration: 1000,
delay: 1000
}))
})
Animated.sequence(animationList).start(() => this.animation())
}
fetchComments = () =>{
const { comments } = this.props
let index = 0
return _.map(comments,(comment, key) => {
index++
return <CommentShow key={key} comment={comment} animatedValue={this.animatedValue[index]} animatedkey={index} />
})
}
componentDidMount() {
this.animation()
}
render() {
return (
<Card style={styles.cotainer}>
{this.fetchComments()}
</Card>
)
}
} |
JavaScript | class Sound
{
constructor(name, format, nextSound)
{
this.name = name;
this.format = format;
this.nextSound = nextSound;
}
} |
JavaScript | class SoundException
{
constructor(message)
{
this.message = message;
}
} |
JavaScript | class SoundManager
{
// Possible exceptions
get _exceptions()
{
return {
IncorrectType: new SoundException("sound requested but not the correct type")
};
};
// Logs exceptions
get _exceptionLog()
{
return function(exc)
{
if (exc instanceof SoundException)
{
console.warn(exc.message);
}
};
};
// Throws exceptions
get _throw()
{
return function(exc)
{
if (exc instanceof SoundException)
{
throw exc.message;
}
};
};
// relative path for sounds
get _relPath()
{
return "./resources/sounds/";
};
// Stores sounds
static get sounds()
{
return {
Mp3Loop: new Sound("gameloop", "mp3", 0)
};
};
// Returns array of sound keys:
// [0] = Mp3Loop
// [1] = WavLoop
static get soundsIndexed()
{
return Object.keys(SoundManager.sounds).map((val) => val);
}
// Gets a path to a sound
GetSoundPath(sound)
{
if (sound.constructor.name === Sound.name)
return this._relPath + sound.name + "." + sound.format;
else
{
this._exceptionLog(this._exceptions.IncorrectType);
return undefined;
}
};
// Gets a sound (if possible), returns a sound instance
GetSound(sound)
{
if (sound.constructor.name === Sound.name)
return new Audio(this.GetSoundPath(sound));
else
{
this._exceptionLog(this._exceptions.IncorrectType);
return undefined;
}
};
// Gets a sound instance and plays the sound
GetAndPlay(sound)
{
if (sound.constructor.name === Sound.name)
return this.GetSound(sound).play();
else
{
this._exceptionLog(this._exceptions.IncorrectType);
return undefined;
}
};
// required
static GetAndPlayLooped(sound)
{
Game.instance.sfxMgr.GetAndPlayLooped(sound);
}
// Gets a sound instance and plays the sound looped
GetAndPlayLooped(sound)
{
if (sound.constructor.name === Sound.name)
{
let instance = this.GetSound(sound);
instance.addEventListener('ended', function()
{
if ((sound.nextSound + 1))
{
SoundManager.GetAndPlayLooped(SoundManager.sounds[SoundManager.soundsIndexed[sound.nextSound]]);
}
else
{
this.currentTime = 0;
this.play();
}
}, false);
return instance.play();
}
else
{
this._exceptionLog(this._exceptions.IncorrectType);
return undefined;
}
}
} |
JavaScript | class MongooseStream extends Transform {
/**
* Create a Transform stream which bulkWrite to mongo based on the itemWaterMark.
* model (mongoose Model) is a required field.
* @param {MongooseStreamSettings} opts Configuration for MongoStream. Default value for `itemWaterMark` is 50.
*/
constructor(opts = defaultOpts) {
opts = Object.assign(opts, defaultOpts);
super(opts);
this.itemWaterMark = opts.itemWaterMark;
this.model = opts.model;
this._passThrough_ = opts.passThrough;
this._stack_ = [];
if (!opts.model) {
throw new Error('Mongoose Model must be defined!');
}
}
_transform(chunk, encoding, callback) {
// termination chunk
if (!chunk) {
this.push(chunk);
} else if (this._passThrough_) {
this.push(chunk);
}
if (chunk) {
this._stack_.push({insertOne: {document: chunk}});
if (this._stack_.length >= this.itemWaterMark) {
let job = this._stack_;
this._stack_ = [];
return this.model.bulkWrite(job, (error, res) => {
this.emit('mongoose-bulk-write', res);
if (error) callback(error);
else callback();
});
}
}
callback();
}
_flush(callback) {
if (this._stack_.length > 0) {
let job = this._stack_;
this._stack_ = [];
return this.model.bulkWrite(job, (error, res) => {
this.emit('mongoose-bulk-write', res);
this.push(null);
if (error) callback(error);
else callback();
});
}
this.push(null);
callback();
}
} |
JavaScript | class Mouvement {
/**
* Constructeur.
*
* @param {*} element Element dont on veut gérer les mouvements.
* Doit implémenter les méthodes rotation, getX, getY, setX et setY.
*/
constructor(element) {
this.element = element;
// Translation
this.translation = false;
this.debutTranslation = 0;
this.tempsTrajet = 0;
this.positionInitialeX = element.getX();
this.positionInitialeY = element.getY();
this.positionCibleX = 0;
this.positionCibleY = 0;
this.mouvementTranslation = AG.MouvementMap.Stop;
// Rotation
this.rotation = false;
this.debutRotation = 0;
this.dureeRotation = 0;
this.degres = 0;
this.mouvementRotation = AG.MouvementMap.Stop;
}
/**
* Appelé à chaque frame.
*
* @param {int} tempsRel Temps relatif en millisecondes depuis le début de la map.
*/
tic(tempsRel) {
if(tempsRel > AG.DUREE_PARTIE) {
this.translation = false;
this.rotation = false;
}
if(this.translation && tempsRel >= this.debutTranslation) {
let posX = this.positionInitialeX;
let posY = this.positionInitialeY;
let deplacementX = this.positionCibleX-this.positionInitialeX;
let deplacementY = this.positionCibleY-this.positionInitialeY;
let tempsRelDebutTrans = (tempsRel-this.debutTranslation)/1000;
switch(this.mouvementTranslation) {
case AG.MouvementMap.Boucler:
if(deplacementX != 0) {
posX = this.positionInitialeX + (deplacementX/(this.tempsTrajet/1000)*tempsRelDebutTrans) % deplacementX;
}
if(deplacementY != 0) {
posY = this.positionInitialeY + (deplacementY/(this.tempsTrajet/1000)*tempsRelDebutTrans) % deplacementY;
}
break;
case AG.MouvementMap.AllerRetour:
if(Math.floor((tempsRel-this.debutTranslation)/this.tempsTrajet) % 2 == 0) {
if(deplacementX != 0) {
posX = this.positionInitialeX + (deplacementX/(this.tempsTrajet/1000)*tempsRelDebutTrans) % deplacementX;
}
if(deplacementY != 0) {
posY = this.positionInitialeY + (deplacementY/(this.tempsTrajet/1000)*tempsRelDebutTrans) % deplacementY;
}
}
else {
if(deplacementX != 0) {
posX = this.positionInitialeX + deplacementX - ((deplacementX/(this.tempsTrajet/1000)*tempsRelDebutTrans) % deplacementX);
}
if(deplacementY != 0) {
posY = this.positionInitialeY + deplacementY - ((deplacementY/(this.tempsTrajet/1000)*tempsRelDebutTrans) % deplacementY);
}
}
break;
default:
posX = this.positionInitialeX + deplacementX/(this.tempsTrajet/1000)*tempsRelDebutTrans;
posY = this.positionInitialeY + deplacementY/(this.tempsTrajet/1000)*tempsRelDebutTrans;
if((deplacementX > 0 && posX > this.positionCibleX) || (deplacementX < 0 && posX < this.positionCibleX)) {
this.translation = false;
posX = this.positionCibleX;
posY = this.positionCibleY;
}
}
this.element.setX(posX);
this.element.setY(posY);
}
if(this.rotation && tempsRel >= this.debutRotation) {
let tempsRelDebutRota = (tempsRel-this.debutRotation)/1000;
let angle = 0;
switch(this.mouvementRotation) {
case AG.MouvementMap.Boucler:
angle = this.degres/(this.dureeRotation/1000)*tempsRelDebutRota % (this.degres != 0 ? this.degres : 1);
break;
case AG.MouvementMap.AllerRetour:
if(Math.floor((tempsRel-this.debutRotation)/this.dureeRotation) % 2 == 0) {
angle = this.degres/(this.dureeRotation/1000)*tempsRelDebutRota % (this.degres != 0 ? this.degres : 1);
}
else {
angle = this.degres - (this.degres/(this.dureeRotation/1000)*tempsRelDebutRota % (this.degres != 0 ? this.degres : 1));
}
break;
default:
angle = this.degres/(this.dureeRotation/1000)*tempsRelDebutRota;
if(this.degres > 0 && angle > this.degres || this.degres < 0 && angle < this.degres) {
this.rotation = false;
angle = this.degres;
}
}
this.element.rotation(angle);
}
}
/**
* Permet d'appliquer une translation à l'élement.
*
* @param {int} depart Temps de départ de la translation en millisecondes relatif au départ de la map.
* @param {int} tempsTrajet Temps de trajet de la translation en millisecondes.
* @param {float} cX Position ciblée en x.
* @param {float} cY Position ciblée en y.
* @param {AG.MouvementMap} mouvement Type de mouvement à effectuer (boucler, aller-retour, aller simple).
*/
appliquerTranslation(depart, tempsTrajet, cX, cY, mouvement) {
this.translation = true;
this.debutTranslation = depart;
this.tempsTrajet = tempsTrajet;
this.positionCibleX = cX;
this.positionCibleY = cY;
this.mouvementTranslation = mouvement;
if(this.debutTranslation < 0) {
this.debutTranslation = 0;
}
if(this.tempsTrajet < 1) {
this.tempsTrajet = 1;
}
}
/**
* Permet d'appliquer une rotation à l'élement.
*
* @param {int} depart Temps de départ de la rotation en millisecondes relatif au départ de la map.
* @param {int} dureeRotation Durée de la rotation en millisecondes.
* @param {float} degres Rotation à appliquer sur l'élement en degrés.
* @param {AG.MouvementMap} mouvement Type de mouvement à effectuer (boucler, aller-retour, aller simple).
*/
appliquerRotation(depart, dureeRotation, degres, mouvement) {
this.rotation = true;
this.debutRotation = depart;
this.dureeRotation = dureeRotation;
this.degres = degres;
this.mouvementRotation = mouvement;
if(this.debutRotation < 0) {
this.debutRotation = 0;
}
if(this.dureeRotation < 1) {
this.dureeRotation = 1;
}
}
/**
* Permet de mettre à jour la position initiale d'une forme.
* Utile dans le cas des groupes, car lorsque l'on ajoute une forme la position initiale de
* l'ensemble du groupe est susceptible de changer.
*/
updatePosition() {
this.positionInitialeX = this.element.getX();
this.positionInitialeY = this.element.getY();
}
} |
JavaScript | class Sidebar extends Component {
constructor(props) {
super(props);
this.state = {menu: [
{name: "Home", url: "/", role: 0},
{name: "All Courses", url: "/all-courses", role: 0},
{name: "My Courses", url: "/my-courses", role: 2},
{name: "All Users", url: "/all-users", role: 1},
{name: "Create Course", url: "/create-course", role: 1},
{name: "Create User", url: "/create-user", role: 1}
]}
this.logout = this.logout.bind(this);
}
/** logout is a different function in link list*/
logout(e){
this.props.logoutUser()
}
/** Generating asll links depending on user role*/
generateLinks(menuItems){
return menuItems.map((exp,i) => {
let isResponsive = this.props.isResponsive;
if (isResponsive) {
return (<NavItem key={i} componentClass='span'>
<Link replace to={{pathname: exp.url}}> {exp.name} </Link>
</NavItem>)
}else{
return (<li key={i} className="nav-item nav-item-education">
<Link replace to={{pathname: exp.url}}> {exp.name} </Link>
</li>)
}
})
}
render() {
/*role --> student = 0 and admin = 1*/
let role = this.props.auth.role
let isResponsive = this.props.isResponsive;
let menuItems = this.state.menu.filter(el => {
if (role === 1){
if (el.role === 2) {
return false
}
return true
}
if (role === 0) {
if (el.role === 0 || el.role === 2) {
return true;
}
}
return false
})
let finalLinks = this.generateLinks(menuItems)
if (isResponsive) {
return(<Nav className="hidden-md hidden-lg">
{finalLinks}
<NavItem key="logout" componentClass='span'>
<Link replace to="/login" onClick={this.logout}> Logout </Link>
</NavItem>
</Nav>
)
}else{
return (
<nav className="col-md-2 hidden-xs hidden-sm sidebar">
<div className="sidebar-sticky">
<ul className="nav flex-column">
{finalLinks}
<li key="logout" className="nav-item nav-item-education">
<a href="/login" onClick={this.logout}> Logout </a>
</li>
</ul>
</div>
</nav>
)
}
}
} |
JavaScript | class PurgeManager {
constructor(rushConfiguration, rushGlobalFolder) {
this._rushConfiguration = rushConfiguration;
this._rushGlobalFolder = rushGlobalFolder;
const commonAsyncRecyclerPath = path.join(this._rushConfiguration.commonTempFolder, RushConstants_1.RushConstants.rushRecyclerFolderName);
this._commonTempFolderRecycler = new AsyncRecycler_1.AsyncRecycler(commonAsyncRecyclerPath);
const rushUserAsyncRecyclerPath = path.join(this._rushGlobalFolder.path, RushConstants_1.RushConstants.rushRecyclerFolderName);
this._rushUserFolderRecycler = new AsyncRecycler_1.AsyncRecycler(rushUserAsyncRecyclerPath);
}
/**
* Performs the AsyncRecycler.deleteAll() operation. This should be called before
* the PurgeManager instance is disposed.
*/
deleteAll() {
this._commonTempFolderRecycler.deleteAll();
this._rushUserFolderRecycler.deleteAll();
}
get commonTempFolderRecycler() {
return this._commonTempFolderRecycler;
}
/**
* Delete everything from the common/temp folder
*/
purgeNormal() {
// Delete everything under common\temp except for the recycler folder itself
console.log('Purging ' + this._rushConfiguration.commonTempFolder);
this._commonTempFolderRecycler.moveAllItemsInFolder(this._rushConfiguration.commonTempFolder, this._getMembersToExclude(this._rushConfiguration.commonTempFolder, true));
}
/**
* In addition to performing the purgeNormal() operation, this method also cleans the
* .rush folder in the user's home directory.
*/
purgeUnsafe() {
this.purgeNormal();
// We will delete everything under ~/.rush/ except for the recycler folder itself
console.log('Purging ' + this._rushGlobalFolder.path);
// If Rush itself is running under a folder such as ~/.rush/node-v4.5.6/rush-1.2.3,
// we cannot delete that folder.
// First purge the node-specific folder, e.g. ~/.rush/node-v4.5.6/* except for rush-1.2.3:
this._rushUserFolderRecycler.moveAllItemsInFolder(this._rushGlobalFolder.nodeSpecificPath, this._getMembersToExclude(this._rushGlobalFolder.nodeSpecificPath, true));
// Then purge the the global folder, e.g. ~/.rush/* except for node-v4.5.6
this._rushUserFolderRecycler.moveAllItemsInFolder(this._rushGlobalFolder.path, this._getMembersToExclude(this._rushGlobalFolder.path, false));
if (this._rushConfiguration.packageManager === 'pnpm' &&
this._rushConfiguration.pnpmOptions.pnpmStore === 'global' &&
this._rushConfiguration.pnpmOptions.pnpmStorePath) {
console.warn(colors_1.default.yellow(`Purging the global pnpm-store`));
this._rushUserFolderRecycler.moveAllItemsInFolder(this._rushConfiguration.pnpmOptions.pnpmStorePath);
}
}
_getMembersToExclude(folderToRecycle, showWarning) {
// Don't recycle the recycler
const membersToExclude = [RushConstants_1.RushConstants.rushRecyclerFolderName];
// If the current process is running inside one of the folders, don't recycle that either
// Example: "/home/user/.rush/rush-1.2.3/lib/example.js"
const currentFolderPath = path.resolve(__dirname);
// Example:
// folderToRecycle = "/home/user/.rush/node-v4.5.6"
// relative = "rush-1.2.3/lib/example.js"
const relative = path.relative(folderToRecycle, currentFolderPath);
// (The result can be an absolute path if the two folders are on different drive letters)
if (!path.isAbsolute(relative)) {
// Get the first path segment:
const firstPart = relative.split(/[\\\/]/)[0];
if (firstPart.length > 0 && firstPart !== '..') {
membersToExclude.push(firstPart);
if (showWarning) {
// Warn that we won't dispose this folder
console.log(colors_1.default.yellow("The active process's folder will not be deleted: " + path.join(folderToRecycle, firstPart)));
}
}
}
return membersToExclude;
}
} |
JavaScript | class GetTimeOfDay extends expressionEvaluator_1.ExpressionEvaluator {
/**
* Initializes a new instance of the [GetTimeOfDay](xref:adaptive-expressions.GetTimeOfDay) class.
*/
constructor() {
super(expressionType_1.ExpressionType.GetTimeOfDay, GetTimeOfDay.evaluator(), returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnaryString);
}
/**
* @private
*/
static evaluator() {
return functionUtils_1.FunctionUtils.applyWithError((args) => {
let value;
let error = functionUtils_internal_1.InternalFunctionUtils.verifyISOTimestamp(args[0]);
let thisTime;
if (error) {
error = functionUtils_internal_1.InternalFunctionUtils.verifyTimestamp(args[0]);
if (error) {
return { value, error };
}
else {
if (dayjs_1.default(args[0]).format(convertFromUTC_1.ConvertFromUTC.NoneUtcDefaultDateTimeFormat) === args[0]) {
thisTime = new Date(args[0]).getHours() * 100 + new Date(args[0]).getMinutes();
error = undefined;
}
else {
return { value, error };
}
}
}
else {
// utc iso format
thisTime = new Date(args[0]).getUTCHours() * 100 + new Date(args[0]).getUTCMinutes();
}
if (thisTime === 0) {
value = 'midnight';
}
else if (thisTime > 0 && thisTime < 1200) {
value = 'morning';
}
else if (thisTime === 1200) {
value = 'noon';
}
else if (thisTime > 1200 && thisTime < 1800) {
value = 'afternoon';
}
else if (thisTime >= 1800 && thisTime <= 2200) {
value = 'evening';
}
else if (thisTime > 2200 && thisTime <= 2359) {
value = 'night';
}
return { value, error };
}, functionUtils_1.FunctionUtils.verifyString);
}
} |
JavaScript | class ComponentHostDirective {
/**
* @param {?} viewContainerRef
*/
constructor(viewContainerRef) {
this.viewContainerRef = viewContainerRef;
}
} |
JavaScript | class DeReCrudProviderService {
constructor() {
this._cache = {};
}
/**
* @param {?} name
* @param {?} options
* @return {?}
*/
register(name, options) {
this._cache[name] = options;
}
/**
* @param {?} name
* @return {?}
*/
get(name) {
/** @type {?} */
const options = this._cache[name];
if (!options) {
throw new Error(`Provider '${name}' is not registered. Make sure register(name, options) is called in the applicatio root.`);
}
return options;
}
} |
JavaScript | class FormBuilderService {
/**
* @param {?} fb
*/
constructor(fb) {
this.fb = fb;
}
/**
* @param {?} struct
* @param {?} blockName
* @param {?} blocks
* @param {?} fields
* @param {?=} value
* @return {?}
*/
group(struct, blockName, blocks, fields, value = {}) {
/** @type {?} */
const group = {};
/** @type {?} */
const block = blocks[`${struct}-${blockName}`];
for (const fieldReference of block.fields) {
/** @type {?} */
const field = fields[`${struct}-${fieldReference.field}`];
if (field.type === 'stamp') {
continue;
}
if (field.type === 'linkedStruct') {
/** @type {?} */
const linkedStructField = /** @type {?} */ (field);
const { reference } = linkedStructField;
/** @type {?} */
const array = this.array(reference.struct, reference.block, blocks, fields, value[field.name]);
if (!array.value.length && linkedStructField.minInstances > 0) {
// tslint:disable-next-line:no-increment-decrement
for (let i = 0; i < linkedStructField.minInstances; i++) {
array.push(this.group(reference.struct, reference.block, blocks, fields));
}
}
group[field.name] = array;
continue;
}
/** @type {?} */
const validators = this.getValidators(fieldReference, field);
/** @type {?} */
const initialValue = value[field.name] || field.initialValue;
group[field.name] = [initialValue, validators];
}
/** @type {?} */
const formGroup = this.fb.group(group);
if (!formGroup.value) {
formGroup.patchValue({});
}
return formGroup;
}
/**
* @param {?} struct
* @param {?} blockName
* @param {?} blocks
* @param {?} fields
* @param {?=} value
* @return {?}
*/
array(struct, blockName, blocks, fields, value = []) {
/** @type {?} */
const array = [];
if (value && value.length) {
value.forEach((item) => {
/** @type {?} */
const group = this.group(struct, blockName, blocks, fields, item);
array.push(group);
});
}
/** @type {?} */
const formArray = this.fb.array(array);
if (!formArray.value) {
formArray.setValue([]);
}
return formArray;
}
/**
* @param {?} fieldReference
* @param {?} field
* @return {?}
*/
getValidators(fieldReference, field) {
return (control) => {
/** @type {?} */
const validators = [];
/** @type {?} */
const root = control.root;
/** @type {?} */
const parent = control.parent;
if (parent instanceof FormGroup &&
!fieldReference.condition(parent.value, root.value)) {
return null;
}
if (field.required) {
validators.push(Validators.required, whitespaceValidator);
}
if ((/** @type {?} */ (field)).minLength) {
validators.push(Validators.minLength((/** @type {?} */ (field)).minLength));
}
if ((/** @type {?} */ (field)).maxLength) {
validators.push(Validators.maxLength((/** @type {?} */ (field)).maxLength));
}
if ((/** @type {?} */ (field)).min) {
validators.push(Validators.min((/** @type {?} */ (field)).min));
}
if ((/** @type {?} */ (field)).max) {
validators.push(Validators.max((/** @type {?} */ (field)).max));
}
if (!validators.length) {
return null;
}
return Validators.compose(validators)(control);
};
}
} |
JavaScript | class CollectionFieldHostComponent {
/**
* @param {?} stateService
* @param {?} componentFactoryResolver
* @param {?} providerService
*/
constructor(stateService, componentFactoryResolver, providerService) {
this.stateService = stateService;
this.componentFactoryResolver = componentFactoryResolver;
this.providerService = providerService;
this.onAdd = (e) => {
e.stopPropagation();
e.preventDefault();
/** @type {?} */
const reference = (/** @type {?} */ (this.control.field)).reference;
/** @type {?} */
const form = this.stateService.createForm(this.control.formId, reference.struct, reference.block);
this.control.value.push(form);
/** @type {?} */
const index = this.control.value.controls.indexOf(form);
/** @type {?} */
const childPath = `${this.control.formPath}.${index}`;
if (this.control.layout === 'table') {
this.stateService.pushNavigation(this.control.formId, reference.struct, reference.block, childPath, this.control.formPath);
}
this.control.onChange(null);
};
}
/**
* @return {?}
*/
ngOnInit() {
this.state = this.stateService.get(this.control.formId);
this.render();
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
if (changes["control"] && !changes["control"].firstChange) {
this.updateInputs();
}
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this._componentRef) {
this._componentRef.destroy();
this._componentRef = null;
}
}
/**
* @return {?}
*/
render() {
if (this._componentRef) {
this._componentRef.destroy();
this._componentRef = null;
}
/** @type {?} */
let controlComponent;
/** @type {?} */
const providerOptions = this.providerService.get(this.state.options.provider);
switch (this.control.layout) {
case 'inline':
controlComponent = providerOptions.inlineComponent;
break;
case 'table':
controlComponent = providerOptions.tableComponent;
break;
default:
console.error(`${this.control.layout} layout is not supported.`, JSON.stringify(this.control.field));
return;
}
/** @type {?} */
const viewContainerRef = this.componentHost.viewContainerRef;
viewContainerRef.clear();
/** @type {?} */
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(controlComponent);
this._componentRef = viewContainerRef.createComponent(componentFactory);
this.updateInputs();
}
/**
* @return {?}
*/
updateInputs() {
if (!this._componentRef) {
return;
}
/** @type {?} */
const componentRenderer = /** @type {?} */ (this._componentRef.instance);
/** @type {?} */
const control = Object.assign({}, this.control, { onAdd: this.onAdd });
/** @type {?} */
const previousControl = componentRenderer.control;
componentRenderer.control = control;
/** @type {?} */
const onComponentChange = (/** @type {?} */ (this._componentRef.instance)).ngOnChanges;
if (onComponentChange) {
/** @type {?} */
const change = {
previousValue: previousControl,
currentValue: control,
firstChange: typeof previousControl === 'undefined',
isFirstChange: () => change.firstChange
};
onComponentChange.call(componentRenderer, { control: change });
}
}
} |
JavaScript | class InputFieldHostComponent {
/**
* @param {?} stateService
* @param {?} componentFactoryResolver
* @param {?} providerService
*/
constructor(stateService, componentFactoryResolver, providerService) {
this.stateService = stateService;
this.componentFactoryResolver = componentFactoryResolver;
this.providerService = providerService;
this._componentRefs = [];
this.onFocus = () => {
this._valueOnFocus = this.form.root.get(this.formPath).value;
};
this.onBlur = () => {
/** @type {?} */
const newValue = this.form.root.get(this.formPath).value;
if (this._valueOnFocus !== newValue) {
this.stateService.onChange(this.formId, this.formPath, newValue, 'blur');
}
};
this.onChange = (e) => {
/** @type {?} */
const newValue = this.form.root.get(this.formPath).value;
this.stateService.onChange(this.formId, this.formPath, newValue, e ? 'change' : null);
};
}
/**
* @return {?}
*/
get formPath() {
/** @type {?} */
let formPath = this.field.name;
if (this.parentPath) {
/** @type {?} */
let parentPath = this.parentPath;
if (this.parentForm instanceof FormArray) {
/** @type {?} */
const index = this.parentForm.controls.indexOf(this.form);
parentPath += '.' + index;
}
formPath = `${parentPath}.${formPath}`;
}
return formPath;
}
/**
* @return {?}
*/
ngOnInit() {
this.state = this.stateService.get(this.formId);
/** @type {?} */
const fieldReference = this.state.blocks[`${this.struct}-${this.block}`].fields.find(x => x.field === this.field.name);
this.fieldReference = fieldReference;
this._submissionErrorsChangeSubscription = this.state.onSubmissionErrorsChange.subscribe(() => {
this.updateInputs();
});
this._formChangeSubscription = this.form.valueChanges.subscribe(() => {
if (!this.shouldRender()) {
this.destroyRefs();
}
else if (!this._componentRefs.length) {
this.render();
}
else {
this.updateInputs();
}
});
this.render();
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
if (changes["formId"] && !changes["formId"].isFirstChange()) {
this.ngOnDestroy();
this.ngOnInit();
return;
}
this.updateInputs();
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this._submissionErrorsChangeSubscription) {
this._submissionErrorsChangeSubscription.unsubscribe();
}
if (this._formChangeSubscription) {
this._formChangeSubscription.unsubscribe();
}
this.destroyRefs();
}
/**
* @return {?}
*/
destroyRefs() {
if (this._componentRefs.length) {
this._componentRefs.forEach(x => x.destroy());
this._componentRefs = [];
}
}
/**
* @return {?}
*/
shouldRender() {
return this.fieldReference && this.fieldReference.condition(this.form.value, this.state.form.root.value);
}
/**
* @return {?}
*/
render() {
this.destroyRefs();
if (!this.shouldRender()) {
return;
}
/** @type {?} */
let controlComponent;
/** @type {?} */
const providerOptions = this.providerService.get(this.state.options.provider);
switch (this.field.type) {
case 'text':
case 'integer':
case 'date':
controlComponent = providerOptions.inputComponent;
break;
case 'boolean':
controlComponent = providerOptions.checkboxComponent;
break;
case 'list':
case 'foreignKey':
controlComponent = providerOptions.selectComponent;
break;
case 'linkedStruct':
controlComponent = CollectionFieldHostComponent;
break;
default:
console.error(`${this.field.type} control is not supported.`, JSON.stringify(this.field));
return;
}
/** @type {?} */
const viewContainerRef = this.componentHost.viewContainerRef;
viewContainerRef.clear();
/** @type {?} */
const containerComponentFactory = this.componentFactoryResolver.resolveComponentFactory(providerOptions.containerComponent);
/** @type {?} */
const controlComponentFactory = this.componentFactoryResolver.resolveComponentFactory(controlComponent);
/** @type {?} */
const controlComponentRef = viewContainerRef.createComponent(controlComponentFactory);
/** @type {?} */
const containerComponentRef = viewContainerRef.createComponent(containerComponentFactory, 0, undefined, [[controlComponentRef.location.nativeElement]]);
this._componentRefs.push(controlComponentRef, containerComponentRef);
this.updateInputs();
}
/**
* @return {?}
*/
updateInputs() {
if (this.shouldRender() && !this._componentRefs.length) {
this.render();
return;
}
if (!this._componentRefs.length) {
return;
}
/** @type {?} */
const formPath = this.formPath;
/** @type {?} */
const value = this.form.root.get(formPath);
/** @type {?} */
const control = {
value,
formPath,
field: this.field,
formId: this.formId,
submissionErrors: (this.state.submissionErrors &&
this.state.submissionErrors[formPath]) ||
[],
form: this.form,
rendererType: this.mapType(this.field.type),
htmlId: `${this.formId}-${formPath}`,
onFocus: this.onFocus,
onBlur: this.onBlur,
onChange: this.onChange
};
switch (this.field.type) {
case 'list':
case 'foreignKey': {
/** @type {?} */
const listField = /** @type {?} */ (this.field);
/** @type {?} */
const selectControl = /** @type {?} */ (control);
if (this.field.type === 'foreignKey') {
selectControl.options = () => [];
}
else {
selectControl.options = () => listField.options;
}
break;
}
case 'linkedStruct': {
/** @type {?} */
const collectionControl = /** @type {?} */ (control);
/** @type {?} */
const linkedStructField = /** @type {?} */ (this.field);
const { reference } = linkedStructField;
/** @type {?} */
const blockFields = this.state.blocks[`${this.struct}-${this.block}`].fields;
const { hints } = /** @type {?} */ (blockFields.find(x => x.field === linkedStructField.name));
/** @type {?} */
const referenceBlock = (hints && hints.block) || reference.block;
/** @type {?} */
const fieldReferences = /** @type {?} */ (this.state
.blocks[`${reference.struct}-${referenceBlock}`].fields);
/** @type {?} */
const nestedFields = [];
for (const fieldReference of fieldReferences) {
/** @type {?} */
const field = this.state.fields[`${reference.struct}-${fieldReference.field}`];
nestedFields.push(field);
}
/** @type {?} */
const nestedValues = [];
for (const nestedValue of collectionControl.value.controls) {
nestedValues.push(/** @type {?} */ (nestedValue));
}
collectionControl.stamp = {
text: control.field.label,
headerSize: this.state.options.headerSize
};
collectionControl.canAdd = !linkedStructField.maxInstances || nestedValues.length < linkedStructField.maxInstances;
collectionControl.nestedValues = nestedValues;
collectionControl.nestedFields = nestedFields;
collectionControl.layout = (hints && hints.layout) || 'inline';
break;
}
}
for (const componentRef of this._componentRefs) {
/** @type {?} */
const componentRenderer = /** @type {?} */ (componentRef.instance);
/** @type {?} */
const previousControl = componentRenderer.control;
componentRenderer.control = control;
/** @type {?} */
const onComponentChange = (/** @type {?} */ (componentRef.instance)).ngOnChanges;
if (onComponentChange) {
/** @type {?} */
const change = {
previousValue: previousControl,
currentValue: control,
firstChange: typeof previousControl === 'undefined',
isFirstChange: () => change.firstChange
};
onComponentChange.call(componentRenderer, { control: change });
}
}
}
/**
* @param {?} type
* @return {?}
*/
mapType(type) {
switch (type) {
case 'integer':
return 'number';
default:
return type;
}
}
} |
JavaScript | class ButtonHostComponent {
/**
* @param {?} stateService
* @param {?} componentFactoryResolver
* @param {?} providerService
*/
constructor(stateService, componentFactoryResolver, providerService) {
this.stateService = stateService;
this.componentFactoryResolver = componentFactoryResolver;
this.providerService = providerService;
this.click = new EventEmitter();
this.onClick = (e) => {
this.click.emit(e);
};
}
/**
* @return {?}
*/
ngOnInit() {
this.state = this.stateService.get(this.formId);
this.render();
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
if (changes["formId"] && !changes["formId"].isFirstChange()) {
this.ngOnDestroy();
this.ngOnInit();
return;
}
this.updateInputs();
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this._componentRef) {
this._componentRef.destroy();
this._componentRef = null;
}
}
/**
* @return {?}
*/
render() {
if (this._componentRef) {
this._componentRef.destroy();
this._componentRef = null;
}
/** @type {?} */
const providerOptions = this.providerService.get(this.state.options.provider);
/** @type {?} */
const viewContainerRef = this.componentHost.viewContainerRef;
viewContainerRef.clear();
/** @type {?} */
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(providerOptions.buttonComponent);
this._componentRef = viewContainerRef.createComponent(componentFactory);
this.updateInputs();
}
/**
* @return {?}
*/
updateInputs() {
if (!this._componentRef) {
return;
}
const { options: { struct, submitButtonStyle, cancelButtonStyle }, structs } = this.state;
/** @type {?} */
const isSubmit = this.type === 'submit';
/** @type {?} */
let style = null;
switch (this.type) {
case 'submit':
style = submitButtonStyle;
break;
case 'cancel':
style = cancelButtonStyle;
break;
}
/** @type {?} */
let text = (style && style.text) || this.text;
if (isSubmit &&
submitButtonStyle &&
submitButtonStyle.appendSchemaLabel) {
text = `${text} ${structs[struct].label}`;
}
/** @type {?} */
const extraClasses = [];
if (this.state.options.extraButtonClasses) {
extraClasses.push(...this.state.options.extraButtonClasses);
}
if (this.extraClasses) {
if (typeof this.extraClasses === 'string') {
extraClasses.push(...this.extraClasses.split(' '));
}
else {
extraClasses.push(...this.extraClasses);
}
}
/** @type {?} */
const componentRenderer = /** @type {?} */ (this._componentRef.instance);
componentRenderer.button = {
text,
extraClasses,
type: isSubmit ? 'submit' : 'button',
disabled: this.disabled,
onClick: this.onClick,
class: (style && style.class) || undefined
};
}
} |
JavaScript | class StampFieldHostComponent {
/**
* @param {?} stateService
* @param {?} componentFactoryResolver
* @param {?} providerService
*/
constructor(stateService, componentFactoryResolver, providerService) {
this.stateService = stateService;
this.componentFactoryResolver = componentFactoryResolver;
this.providerService = providerService;
}
/**
* @return {?}
*/
ngOnInit() {
this.state = this.stateService.get(this.formId);
/** @type {?} */
const fieldReference = this.state.blocks[`${this.struct}-${this.block}`].fields.find(x => x.field === this.field.name);
this.fieldReference = fieldReference;
this.render();
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
if (changes["formId"] && !changes["formId"].isFirstChange()) {
this.ngOnDestroy();
this.ngOnInit();
return;
}
this.updateInputs();
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this._componentRef) {
this._componentRef.destroy();
this._componentRef = null;
}
}
/**
* @return {?}
*/
shouldRender() {
return this.fieldReference.condition(this.form.value, this.state.form.root.value);
}
/**
* @return {?}
*/
render() {
if (this._componentRef) {
this._componentRef.destroy();
this._componentRef = null;
}
if (!this.shouldRender()) {
return;
}
/** @type {?} */
let controlComponent;
/** @type {?} */
const providerOptions = this.providerService.get(this.state.options.provider);
switch (this.field.type) {
case 'stamp':
controlComponent = providerOptions.stampComponent;
break;
default:
console.error(`${this.field.type} control is not supported.`, JSON.stringify(this.field));
return;
}
/** @type {?} */
const viewContainerRef = this.componentHost.viewContainerRef;
viewContainerRef.clear();
/** @type {?} */
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(controlComponent);
this._componentRef = viewContainerRef.createComponent(componentFactory);
this.updateInputs();
}
/**
* @return {?}
*/
updateInputs() {
if (!this._componentRef) {
return;
}
/** @type {?} */
const componentRenderer = /** @type {?} */ (this._componentRef.instance);
/** @type {?} */
const stampField = /** @type {?} */ (this.field);
/** @type {?} */
const stamp = {
text: stampField.label,
headerSize: this.state.options.headerSize
};
if (stampField.hints) {
if (stampField.hints.headerSize) {
stamp.headerSize = stampField.hints.headerSize;
}
if (stampField.hints.displayClassNames) {
stamp.classes = stampField.hints.displayClassNames;
}
}
/** @type {?} */
const previousStamp = componentRenderer.stamp;
componentRenderer.stamp = stamp;
/** @type {?} */
const onComponentChange = (/** @type {?} */ (this._componentRef.instance))
.ngOnChanges;
if (onComponentChange) {
/** @type {?} */
const change = {
previousValue: previousStamp,
currentValue: stamp,
firstChange: typeof previousStamp === 'undefined',
isFirstChange: () => change.firstChange
};
onComponentChange.call(componentRenderer, { control: change });
}
}
} |
JavaScript | class FormHostComponent {
/**
* @param {?} stateService
*/
constructor(stateService) {
this.stateService = stateService;
}
/**
* @return {?}
*/
get struct() {
return this._struct || this.state.options.struct;
}
/**
* @param {?} value
* @return {?}
*/
set struct(value) {
this._struct = value;
}
/**
* @return {?}
*/
get block() {
return this._block || this.state.options.block;
}
/**
* @param {?} value
* @return {?}
*/
set block(value) {
this._block = value;
}
/**
* @return {?}
*/
ngOnInit() {
this.state = this.stateService.get(this.formId);
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
if (changes["formId"] && !changes["formId"].isFirstChange()) {
this.ngOnInit();
return;
}
}
} |
JavaScript | class FormComponent {
/**
* @param {?} stateService
*/
constructor(stateService) {
this.stateService = stateService;
this.valueChange = new EventEmitter();
this.submit = new EventEmitter();
this.cancel = new EventEmitter();
}
/**
* @return {?}
*/
get cancelVisible() {
return !!this.state.navigationStack.length || this._cancelVisible;
}
/**
* @param {?} value
* @return {?}
*/
set cancelVisible(value) {
this._cancelVisible = value;
}
/**
* @return {?}
*/
get submitEnabled() {
return !this.submitting && this.form.valid;
}
/**
* @return {?}
*/
get cancelEnabled() {
return !this.submitting;
}
/**
* @return {?}
*/
get struct() {
const { navigationStack } = this.state;
/** @type {?} */
const navigationStackCount = navigationStack.length;
return navigationStackCount
? navigationStack[navigationStackCount - 1].struct
: this.state.options.struct;
}
/**
* @return {?}
*/
get block() {
const { navigationStack } = this.state;
/** @type {?} */
const navigationStackCount = navigationStack.length;
return navigationStackCount
? navigationStack[navigationStackCount - 1].block
: this.state.options.block;
}
/**
* @return {?}
*/
get form() {
const { navigationStack } = this.state;
/** @type {?} */
const navigationStackCount = navigationStack.length;
return navigationStackCount
? this.state.form.get(navigationStack[navigationStackCount - 1].path)
: this.state.form;
}
/**
* @return {?}
*/
get parentPath() {
const { navigationStack } = this.state;
/** @type {?} */
const navigationStackCount = navigationStack.length;
return navigationStackCount
? navigationStack[navigationStackCount - 1].parentPath
: null;
}
/**
* @return {?}
*/
get parentForm() {
const { navigationStack } = this.state;
/** @type {?} */
const navigationStackCount = navigationStack.length;
return navigationStackCount
? this.state.form.get(navigationStack[navigationStackCount - 1].parentPath)
: null;
}
/**
* @return {?}
*/
ngOnInit() {
this.state = this.stateService.create(this.options, this.value, this.errors);
this.update();
this._navigationChangeSubscription = this.state.onNavigationChange.subscribe(() => {
this.update();
});
this._formChangeSubscription = this.state.onValueChange.subscribe((change) => {
this.valueChange.emit(change);
});
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
if (changes["value"] && !changes["value"].firstChange) {
this.stateService.update(this.state.id, changes["value"].currentValue);
}
if (changes["errors"] && !changes["errors"].firstChange) {
this.stateService.setErrors(this.state.id, changes["errors"].currentValue);
}
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this._navigationChangeSubscription) {
this._navigationChangeSubscription.unsubscribe();
}
if (this._formChangeSubscription) {
this._formChangeSubscription.unsubscribe();
}
this.stateService.remove(this.state.id);
}
/**
* @return {?}
*/
update() {
const { options, navigationStack } = this.state;
/** @type {?} */
let struct;
/** @type {?} */
let block;
/** @type {?} */
const child = navigationStack[navigationStack.length - 1];
if (child) {
({ struct, block } = child);
}
else {
({ struct, block } = options);
}
/** @type {?} */
const blockFields = this.getBlockFields(struct, block);
this.fields = blockFields;
}
/**
* @param {?} struct
* @param {?} blockName
* @return {?}
*/
getBlockFields(struct, blockName) {
const { blocks, fields } = this.state;
if (!blocks || !fields) {
// TODO: Log error
return [];
}
/** @type {?} */
const block = blocks[`${struct}-${blockName}`];
if (!block) {
// TODO: Log error
return [];
}
/** @type {?} */
const references = block.fields;
/** @type {?} */
const blockFields = [];
for (const reference of references) {
blockFields.push(fields[`${struct}-${reference.field}`]);
}
return blockFields;
}
/**
* @param {?} e
* @return {?}
*/
onCancel(e) {
e.stopPropagation();
e.preventDefault();
if (!this.cancelEnabled) {
return;
}
if (this.state.navigationStack.length) {
this.stateService.popNavigation(this.state.id);
return;
}
this.cancel.emit();
this.state.form.reset();
}
/**
* @param {?} e
* @return {?}
*/
onSubmit(e) {
e.stopPropagation();
e.preventDefault();
if (!this.submitEnabled) {
return;
}
if (this.state.navigationStack.length) {
this.stateService.completeNavigation(this.state.id);
return;
}
this.submitting = true;
this.submit.emit({
value: this.state.form.value,
onComplete: (errors) => {
if (!errors) {
this.stateService.clearErrors(this.state.id);
this.state.form.reset();
}
else {
this.stateService.setErrors(this.state.id, errors);
}
this.submitting = false;
}
});
}
} |
JavaScript | class ValidationErrorHelper {
/**
* @param {?} control
* @return {?}
*/
static getFormControlIfErrorFound(control) {
/** @type {?} */
const formControl = control.form.get(control.field.name);
if ((!formControl.errors || !formControl.touched) &&
!control.submissionErrors.length) {
return null;
}
return formControl;
}
/**
* @param {?} control
* @return {?}
*/
static hasError(control) {
return !!this.getFormControlIfErrorFound(control);
}
/**
* @param {?} control
* @return {?}
*/
static getErrors(control) {
/** @type {?} */
const formControl = this.getFormControlIfErrorFound(control);
if (!formControl) {
return null;
}
/** @type {?} */
const sortedErrors = [];
/** @type {?} */
const unsortedErrors = [];
if (formControl.errors && formControl.touched) {
for (const key of Object.keys(formControl.errors)) {
/** @type {?} */
const sort = this._errorSort[key];
/** @type {?} */
const metadata = formControl.errors[key];
if (typeof sort === 'undefined') {
unsortedErrors.push({ key, metadata });
}
else {
sortedErrors.push({ key, metadata, sort });
}
}
}
return sortedErrors
.sort(x => x.sort)
.concat(unsortedErrors)
.map(this.getErrorMessage)
.concat(control.submissionErrors);
}
/**
* @param {?} error
* @return {?}
*/
static getErrorMessage(error) {
switch (error.key) {
case 'required':
return 'This field is required.';
case 'minlength':
return `This field must have at least ${error.metadata.requiredLength} characters.`;
case 'maxlength':
return `This field can not exceed ${error.metadata.requiredLength} characters.`;
default:
return `Validation failed with error: ${error}`;
}
}
} |
JavaScript | class Bootstrap3ControlContainerRendererComponent {
/**
* @return {?}
*/
getClasses() {
/** @type {?} */
const hasError = ValidationErrorHelper.hasError(this.control);
return {
'has-error': hasError,
'has-feedback': hasError
};
}
} |
JavaScript | class Bootstrap3ButtonRendererComponent {
/**
* @return {?}
*/
get classes() {
/** @type {?} */
let classes;
if (this._classes) {
classes = this._classes;
}
if (this.button.extraClasses) {
classes = (classes || []).concat(this.button.extraClasses);
}
return classes;
}
/**
* @return {?}
*/
ngOnInit() {
this.updateClasses();
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
if (changes["button"]) {
if (changes["button"].currentValue.type !==
changes["button"].previousValue.type) {
this.updateClasses();
}
}
}
/**
* @return {?}
*/
updateClasses() {
if (this.button.class) {
this._classes = [this.button.class];
return;
}
switch (this.button.type) {
case 'submit':
this._classes = ['btn-primary'];
break;
default:
this._classes = ['btn-default'];
break;
}
}
} |
JavaScript | class Bootstrap3TableRendererComponent {
/**
* @param {?} field
* @param {?} value
* @return {?}
*/
getValue(field, value) {
/** @type {?} */
const fieldValue = value[field.name];
if (fieldValue == null || typeof fieldValue === 'undefined') {
return ' ';
}
return fieldValue;
}
} |
JavaScript | class Bootstrap3HelpRendererComponent {
/**
* @return {?}
*/
hasError() {
return ValidationErrorHelper.hasError(this.control);
}
} |
JavaScript | class Bootstrap3ValidationErrorsRendererComponent {
/**
* @return {?}
*/
hasError() {
return ValidationErrorHelper.hasError(this.control);
}
/**
* @return {?}
*/
getErrors() {
return ValidationErrorHelper.getErrors(this.control);
}
} |
JavaScript | class Bootstrap3DeReCrudProviderModule {
/**
* @param {?} providerService
*/
constructor(providerService) {
providerService.register('bootstrap3', {
stampComponent: Bootstrap3StampRendererComponent,
containerComponent: Bootstrap3ControlContainerRendererComponent,
inputComponent: Bootstrap3InputRendererComponent,
selectComponent: Bootstrap3SelectRendererComponent,
buttonComponent: Bootstrap3ButtonRendererComponent,
tableComponent: Bootstrap3TableRendererComponent,
inlineComponent: Bootstrap3InlineRendererComponent,
checkboxComponent: Bootstrap3CheckboxRendererComponent
});
}
} |
JavaScript | class HTTPError extends Error {
/**
* The HTTP Status code.
*/
/**
* The additional parameters sent to the exception.
*/
/**
* Constructor of the HTTPError.
*
* @param message The message of the exception.
* @param status The status code of the exception.
* @param parameters Some extra parameters sent to the error.
*/
constructor(message, status = _HTTPStatus.default.SERVER_ERROR, // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
parameters) {
super(message);
_defineProperty(this, "status", _HTTPStatus.default.SERVER_ERROR);
_defineProperty(this, "parameters", null);
this.status = status;
this.parameters = parameters;
}
} |
JavaScript | class Command extends NameTypeSettingsLoggable
{
/**
* Creates an instance of Command, do not use directly but in a sub class.
* @extends Loggable
* @abstract
*
* A Command configuration is a simple object with this common attributes:
* - name:string - command unique name.
* - type:string - type of commnand from command factory known types list (example: display).
* - label:string - displayable short descriptive string.
*
* API
* ->get_name():string - get command name (INHERITED).
* ->get_type():string - get command type (INHERITED).
* ->get_settings():object - get instance type (INHERITED).
* ->is_valid():boolean - check if instance is valid (settings...) (INHERITED).
*
* ->do():Promise - do command.
* ->undo():Promise - undo command.
*
* @param {object} arg_runtime - runtime.
* @param {object} arg_settings - instance settings.
* @param {string|undefined} arg_log_context - context of traces of this instance (optional).
*
* @returns {nothing}
*/
constructor(arg_runtime, arg_settings, arg_log_context)
{
const log_context = arg_log_context ? arg_log_context : context
super(arg_runtime, arg_settings, log_context)
this.is_command = true
}
/**
* Do command.
*
* @returns {Promise}
*/
do()
{
this.enter_group('do')
let promise = undefined
try {
promise = this._do()
}
catch(e) {
promise = Promise.reject(context + ':do:an exception occures:' + e.toString())
}
this.leave_group('do:async')
return promise
}
/**
* Do command.
*
* @returns {Promise}
*/
_do()
{
return Promise.reject(context + ':do:not yet implemented')
}
/**
* Undo command.
*
* @returns {Promise}
*/
undo()
{
this.enter_group('undo')
let promise = undefined
try {
promise = this._undo()
}
catch(e) {
promise = Promise.reject(context + ':undo:an exception occures:' + e.toString())
}
this.leave_group('undo:async')
return promise
}
/**
* Undo command.
*
* @returns {Promise}
*/
_undo()
{
return Promise.reject(context + ':undo:not yet implemented')
}
} |
JavaScript | class ReviewService {
/**
* Constructs a new ReviewService.
*/
constructor($http, $q, $log) {
'ngInject';
this.$http = $http;
this.$q = $q;
this.$log = $log;
}
/**
* Returns a promise that resolves with the review information.
*
* @param {String} id the id of the review to return the
* information for
* @returns {Promise} promise a promise that resolves with an object
* containing the review information
*/
getReview(id) {
this.$log.debug('ReviewService.getReview(%s)', id);
const deferred = this.$q.defer();
const request = {
method : 'GET',
url : settings.API.BASE_URL + settings.API.ENDPOINT.SEARCH,
params: {
q: ('id:' + id)
}
};
//send request
this.$http(request)
.then((response) => {
this.$log.debug('Fetch by id successful. response: %o', response);
//build domain object
let result = this.toResult(response);
//resolve with results
deferred.resolve(result);
}, (errorResponse) => {
this.$log.error('Failed to fetch review for id %s. An error was returned', id, errorResponse);
deferred.reject();
});
return deferred.promise;
}
/**
* Transforms the given response to a domain result
* object to be used within the review detail UI.
*
* @param {Object} response the search response object
* @returns {Object} result a domain object containing the review information
*/
toResult(response){
const data = response.data || {};
response = data.response || {};
const docs = response.docs || [];
let result = {};
if(docs.length > 0){
result = docs[0];
}
return result;
}
} |
JavaScript | class GeneralSettingsPanel extends _react.Component {
constructor(...args) {
super(...args);
_defineProperty(this, "handleChange", queryParam => {
const {
onQueryParamChange
} = this.props;
if (typeof onQueryParamChange === "function") {
onQueryParamChange(queryParam);
}
});
}
render() {
const {
className,
paramNames,
query,
style,
supportedModes
} = this.props;
const configWrapper = {
modes: supportedModes
};
return /*#__PURE__*/_react.default.createElement(Styled.GeneralSettingsPanel, {
className: className,
style: style
}, paramNames.map(param => {
const paramInfo = _queryParams.default.find(qp => qp.name === param); // Check that the parameter applies to the specified routingType
if (!paramInfo.routingTypes.includes(query.routingType)) return null; // Check that the applicability test (if provided) is satisfied
if (typeof paramInfo.applicable === "function" && !paramInfo.applicable(query, configWrapper)) {
return null;
} // Create the UI component based on the selector type
switch (paramInfo.selector) {
case "DROPDOWN":
return /*#__PURE__*/_react.default.createElement(_DropdownSelector.default, {
key: paramInfo.name,
name: paramInfo.name,
value: query[paramInfo.name] || paramInfo.default,
label: (0, _query.getQueryParamProperty)(paramInfo, "label", query),
options: (0, _query.getQueryParamProperty)(paramInfo, "options", query),
onChange: this.handleChange
});
case "CHECKBOX":
return /*#__PURE__*/_react.default.createElement(_CheckboxSelector.default, {
key: paramInfo.label,
name: paramInfo.name,
value: query[paramInfo.name],
label: (0, _query.getQueryParamProperty)(paramInfo, "label", query),
onChange: this.handleChange
});
default:
return null;
}
}));
}
} |
JavaScript | class App extends Component {
render() {
return (
// All the following divs have been made to style the webpage
<div className="wrapper">
<div className="main">
<div className="container">
{/* Title is rendered here */}
<div className="title-container">
<Title />
</div>
{/* Form will be rendered here during the further tasks */}
<div className="form-container">
</div>
</div>
</div>
</div>
);
}
} |
JavaScript | class PixelmatchHelper extends Helper {
/**
* Relative path to the folder that contains relevant images.
*
* @type {{expected: string, actual: string, diff: string}}
*/
globalDir = {
expected: '',
actual: '',
diff: ''
};
/**
* Default tolserance level for comparisons.
*
* @type {float}
*/
globalTolerance = 0;
/**
* Default threshold for all comparisons.
*
* @type {float}
*/
globalThreshold = 0.05;
/**
* Filename prefix for generated difference files.
* @type {string}
*/
globalDiffPrefix = 'Diff_';
/**
* Whether to save the intermediate images to the global output folder,
* after applying the bounds and ignore-boxes.
*
* Useful for debugging tests, but not recommended for production usage.
*
* @type {boolean}
*/
globalDumpIntermediateImage = false;
/**
* Whether to capture a new screenshot and use it as actual image, instead
* of loading the image from the `dirActual` folder.
*
* The new screenshot is saved to the `dirActual` folder before comparison,
* and will replace an existing file with the same name!
*
* @type {boolean|'missing'}
*/
globalCaptureActual = 'missing';
/**
* Whether to update the expected base image with a current screenshot
* before starting the comparison.
*
* The new screenshot is saved to the `dirExpected` folder, and will
* replace an existing file with the same name!
*
* @type {boolean|'missing'}
*/
globalCaptureExpected = 'missing';
/**
* Contains the image paths for the current test.
*
* @type {{expected: string, actual: string, diff: string}}
*/
path = {
expected: '',
actual: '',
diff: ''
};
/**
* Comparison options.
*
* @type {object}
*/
options = {
// Percentage of pixels that are allowed to differ between both images.
tolerance: 0,
// Defines a custom comparison image name.
compareWith: '',
// Only compare a single HTML element. Used to calculate a bounding box.
element: '',
// Only used, when element is not set. Only pixels inside this box are compared.
bounds: {
left: 0,
top: 0,
width: 0,
height: 0
},
// List of boxes to ignore. Each box is an object with {left, top, width, height}.
ignore: [],
// Arguments that are passed to the pixelmatch library.
args: {
threshold: 0.1,
alpha: 0.5,
includeAA: false,
diffMask: false,
aaColor: [128, 128, 128],
diffColor: [255, 0, 0],
diffColorAlt: null
},
// Whether to dump intermediate images before comparing them.
dumpIntermediateImage: false,
// Whether to take a screenshot for the actual image before comparison.
captureActual: 'missing',
// Whether to take a screenshot for the expected image before comparison.
captureExpected: 'missing'
};
/**
* Name of the image to compare.
*
* @type {string}
*/
imageName = '';
/**
* Holds comparison results.
*
* @type {{match: boolean, difference: float, diffImage: string, diffPixels: integer,
* totalPixels: integer, relevantPixels: integer}}
*/
result = {
match: true,
difference: 0,
diffImage: '',
diffPixels: 0,
totalPixels: 0,
relevantPixels: 0,
variation: '',
variations: []
};
/**
* Constructor that initializes the helper.
* Called internally by CodeceptJS.
*
* @param {object} config
*/
constructor(config) {
super(config);
if (config.dirExpected) {
this.globalDir.expected = this._resolvePath(config.dirExpected);
} else {
this.globalDir.expected = this._resolvePath('./tests/screenshots/base/');
}
if ('undefined' !== typeof config.dirDiff) {
if (config.dirDiff) {
this.globalDir.diff = this._resolvePath(config.dirDiff);
} else {
this.globalDir.diff = false;
}
} else {
this.globalDir.diff = this._resolvePath('./tests/screenshots/diff/');
}
if (config.dirActual) {
this.globalDir.actual = this._resolvePath(config.dirActual);
} else {
this.globalDir.actual = global.output_dir + '/';
}
this.globalDir.output = global.output_dir + '/';
if ('undefined' !== typeof config.tolerance) {
this.globalTolerance = Math.min(100, Math.max(0, parseFloat(config.tolerance)));
}
if ('undefined' !== typeof config.threshold) {
this.globalThreshold = Math.min(1, Math.max(0, parseFloat(config.threshold)));
}
this.globalDiffPrefix = config.diffPrefix ? config.diffPrefix : 'Diff_';
this.globalDumpIntermediateImage = this._toBool(config.dumpIntermediateImage);
if ('undefined' !== typeof config.captureActual) {
this.globalCaptureActual = this._toBool(config.captureActual, ['missing']);
}
if ('undefined' !== typeof config.captureExpected) {
this.globalCaptureExpected = this._toBool(config.captureExpected, ['missing']);
}
}
/**
* Compares the given screenshot with the expected image. When too many
* differences are detected, the test will fail.
*
* I.checkVisualDifferences('dashboard.png');
* I.checkVisualDifferences('dashboard.png', { screenshot: true });
*
* @param {string} image - Name of the input image to compare.
* @param {object} options - Optional options for the comparison.
* @return {Promise}
*/
checkVisualDifferences(image, options) {
return new Promise(async (resolve, reject) => {
try {
await this.getVisualDifferences(image, options);
} catch (err) {
reject(err);
}
const res = this.result;
this.debug(`Difference: ${res.difference}% | ${res.diffPixels} / ${res.relevantPixels} pixels`);
if (res.match) {
resolve(res);
} else {
const msg = [];
msg.push(`Images are different by ${res.difference}%`);
if (res.diffImage) {
msg.push(`differences are displayed in '${res.diffImage}'`);
}
reject(msg.join(' - '));
}
});
}
/**
* Compares the given screenshot with the expected image and updates the
* class member `this.result` with details. This function does to trigger an
* assertion but can throw an error, when the images cannot be compared.
*
* @param {string} image - Name of the input image to compare.
* @param {object} options - Optional options for the comparison.
* @return {{match: boolean, difference: float}} Comparison details.
*/
async getVisualDifferences(image, options) {
await this._setupTest(image, options);
const opts = this.options;
const res = this.result;
this.debug(`Check differences in ${image} ...`);
await this._maybeCaptureImage('actual', opts.captureActual);
await this._maybeCaptureImage('expected', opts.captureExpected);
const expectedImages = this._getExpectedImagePaths();
if (!expectedImages.length) {
throw new Error('No expected base image found');
}
const imgActual = this._loadPngImage('actual');
if (!imgActual.height) {
throw new Error('Current screenshot is empty (zero height)');
}
const width = imgActual.width;
const height = imgActual.height;
const totalPixels = width * height;
const ignoredPixels = this._applyBounds(imgActual);
const results = [];
let bestIndex = 0;
let bestDifference = totalPixels;
let bestImgDiff;
const imgDiff = new PNG({
width,
height
});
if (opts.dumpIntermediateImage) {
this._savePngImage('output', imgActual, 'actual');
}
// Compare the actual image with every base image in the list.
for (let i = 0; i < expectedImages.length; i++) {
const imgPath = expectedImages[i];
const imgExpected = this._loadPngImage(imgPath);
if (imgExpected.width !== imgActual.width || imgExpected.height !== imgActual.height) {
throw new Error('Image sizes do not match');
}
this._applyBounds(imgExpected);
if (opts.dumpIntermediateImage) {
this._savePngImage('output', imgExpected, 'expected.' + (i ? i : ''));
}
results[i] = {};
results[i].diffPixels = pixelmatch(
imgExpected.data,
imgActual.data,
imgDiff.data,
width,
height,
opts.args
);
results[i].totalPixels = totalPixels;
results[i].relevantPixels = totalPixels - ignoredPixels;
const difference = 100 * results[i].diffPixels / results[i].relevantPixels;
results[i].difference = parseFloat(difference.toFixed(4));
results[i].match = results[i].difference <= opts.tolerance;
if (-1 !== imgPath.indexOf('~')) {
results[i].variation = imgPath.replace(/\.png$|^.*~/g, '');
} else {
results[i].variation = '';
}
if (!results[i].match && this.globalDir.diff) {
results[i].diffImage = this._getFileName('diff', i);
} else {
results[i].diffImage = '';
}
// Keep track of the best match.
if (results[i].diffPixels < bestDifference) {
// Remember the serialized PNG, because the imgDiff object is
// a reference that might be updated before the loop ends.
bestImgDiff = PNG.sync.write(imgDiff);
bestDifference = results[i].diffPixels;
bestIndex = i;
}
}
// Use the best match as return value.
for (const key in res) {
if (!res.hasOwnProperty(key)) {
continue;
}
res[key] = results[bestIndex][key];
}
// Add the dynamic property `variations` that lists all comparisons.
res.variations = results;
// Only create a diff-image of the best-matching variation.
if (!res.match) {
this._savePngImage('diff', bestImgDiff, res.variation);
}
return res;
}
/**
* Take screenshot of individual element.
*
* @param {string} name - Name of the output image.
* @param {'actual'|'expected'} which - Optional. Whether the screenshot is
* the expected bas eimage, or an actual image for comparison.
* Defaults to 'actual'.
* @param {string} element - Optional. Selector of the element to
* screenshot, or empty to screenshot current viewport.
* @returns {Promise}
*/
async takeScreenshot(name, which, element) {
await this._setupTest(name);
if (element) {
await this._takeElementScreenshot(name, which, element);
} else {
await this._takeScreenshot(name, which);
}
}
/**
* Takes a screenshot of the entire viewport and saves it as either an
* actual image, or an expected base-image.
*
* @param {string} name - Name of the output image.
* @param {'actual'|'expected'} which - Optional. Whether the screenshot is
* the expected bas eimage, or an actual image for comparison.
* Defaults to 'actual'.
* @param {string} element - Optional. Selector of the element to
* screenshot, or empty to screenshot current viewport.
* @private
*/
async _takeElementScreenshot(name, which, element) {
const driver = this._getDriver();
// The output path where the screenshot is saved to.
const outputFile = this._buildPath('expected' === which ? which : 'actual');
// Screenshot a single element.
await driver.waitForVisible(element);
const els = await driver._locate(element);
if ('TestCafe' === driver._which) {
if (!await els.count) {
throw new Error(`Element ${element} couldn't be located`);
}
await driver.t.takeElementScreenshot(els, outputFile);
} else {
if (!els.length) {
throw new Error(`Element ${element} couldn't be located`);
}
const el = els[0];
switch (driver._which) {
case 'Playwright':
case 'Puppeteer':
await el.screenshot({path: outputFile});
break;
case 'WebDriver':
case 'Appium':
await el.saveScreenshot(outputFile);
break;
}
}
}
/**
* Takes a screenshot of the entire viewport and saves it as either an
* actual image, or an expected base-image.
*
* @param {string} name - Name of the output image.
* @param {'actual'|'expected'} which - Optional. Whether the screenshot is
* the expected bas eimage, or an actual image for comparison.
* Defaults to 'actual'.
* @private
*/
async _takeScreenshot(name, which) {
const driver = this._getDriver();
// The output path where the screenshot is saved to.
const outputFile = this._buildPath('expected' === which ? which : 'actual');
// We need a dynamic temp-name here: When the helper is used with
// the `run-workers` option, multiple workers might access a temp
// file at the same time.
const uid = Math.random().toString(36).slice(-5);
const tempName = `~${uid}.temp`;
// Screenshot the current viewport into a temp file.
await driver.saveScreenshot(tempName);
this._deleteFile(outputFile);
// Move the temp file to the correct folder and rename the file.
fs.renameSync(global.output_dir + '/' + tempName, outputFile);
this._deleteFile(global.output_dir + '/' + tempName);
}
/**
* Clears pixels in the specified image that are outside the bounding rect
* or inside an ignored area.
*
* @param {PNG} png - The image to modify.
* @return {int} Number of cleared pixels.
* @private
*/
_applyBounds(png) {
const opts = this.options;
let cleared = 0;
const useBounds = opts.bounds.left
|| opts.bounds.top
|| opts.bounds.width
|| opts.bounds.height;
// Apply a bounding box to only compare a section of the image.
if (useBounds) {
this.debug(`Apply bounds to image ...`);
const box = {
x0: 0,
x1: opts.bounds.left,
x2: opts.bounds.left + opts.bounds.width,
x3: png.width,
y0: 0,
y1: opts.bounds.top,
y2: opts.bounds.top + opts.bounds.height,
y3: png.height
};
cleared += this._clearRect(png, box.x0, box.y0, box.x1, box.y3);
cleared += this._clearRect(png, box.x1, box.y0, box.x3, box.y1);
cleared += this._clearRect(png, box.x1, box.y2, box.x3, box.y3);
cleared += this._clearRect(png, box.x2, box.y1, box.x3, box.y2);
}
// Clear areas that are ignored.
for (let i = 0; i < opts.ignore.length; i++) {
cleared += this._clearRect(
png,
opts.ignore[i].left,
opts.ignore[i].top,
opts.ignore[i].left + opts.ignore[i].width,
opts.ignore[i].top + opts.ignore[i].height
);
}
return cleared;
}
/**
* Determines the bounding box of the given element on the current viewport.
*
* @param {string} selector - CSS|XPath|ID selector.
* @returns {Promise<{boundingBox: {left: int, top: int, right: int, bottom: int, width: int,
* height: int}}>}
*/
async _getBoundingBox(selector) {
const driver = this._getDriver();
await driver.waitForVisible(selector);
const els = await driver._locate(selector);
let location, size;
if ('TestCafe' === driver._which) {
if (await els.count != 1) {
throw new Error(`Element ${selector} couldn't be located or isn't unique on the page`);
}
} else if (!els.length) {
throw new Error(`Element ${selector} couldn't be located`);
}
const density = parseInt(await driver.executeScript(() => {
return window.devicePixelRatio;
})) || 1;
switch (driver._which) {
case 'Puppeteer':
case 'Playwright': {
const el = els[0];
const box = await el.boundingBox();
size = location = box;
}
break;
case 'WebDriver':
case 'Appium': {
const el = els[0];
location = await el.getLocation();
size = await el.getSize();
}
break;
case 'WebDriverIO':
location = await driver.browser.getLocation(selector);
size = await driver.browser.getElementSize(selector);
break;
case 'TestCafe': {
const box = await els.boundingClientRect;
location = {
x: box.left,
y: box.top
};
size = {
width: box.width,
height: box.height
};
}
}
if (!size) {
throw new Error('Cannot get element size!');
}
const boundingBox = {
left: density * location.x,
top: density * location.y,
right: density * (size.width + location.x),
bottom: density * (size.height + location.y),
width: density * size.width,
height: density * size.height
};
this.debugSection(`Bounding box of ${selector}:`, JSON.stringify(boundingBox));
return boundingBox;
}
/**
* Captures the expected or actual image, depending on the captureFlag.
*
* @param {string} which - Which image to capture: 'expected', 'actual'.
* @param {bool|string} captureFlag - Either true, false or 'missing'.
* @private
*/
async _maybeCaptureImage(which, captureFlag) {
if (false === captureFlag) {
return;
}
if ('missing' === captureFlag) {
const path = this._buildPath(which);
if (this._isFile(path, 'read')) {
// Not missing: Exact image match.
return;
}
if ('expected' === which && this._getExpectedImagePaths().length) {
// Not missing: Expected image variation(s) found.
return;
}
}
await this._takeScreenshot(this.imageName, which);
}
/**
* Sanitizes the given options and updates all relevant class members with
* either the new, sanitized value, or with a default value.
*
* @param {string} image - Name of the image to compare.
* @param {object|undefined} options - The new options to set.
* @private
*/
async _setupTest(image, options) {
// Set the name of the current image.
this.imageName = image.replace(/(~.+)?\.png$/, '');
// Reset the previous test results.
this.result = {
match: true,
difference: 0,
diffImage: '',
diffPixels: 0,
totalPixels: 0,
relevantPixels: 0,
variation: '',
variations: []
};
// Define the default options.
const newValues = {
tolerance: this.globalTolerance,
compareWith: '',
element: '',
bounds: {
left: 0,
top: 0,
width: 0,
height: 0
},
ignore: [],
args: {
threshold: this.globalThreshold,
alpha: 0.5,
includeAA: false,
diffMask: false,
aaColor: [128, 128, 128],
diffColor: [255, 0, 0],
diffColorAlt: null
},
dumpIntermediateImage: this.globalDumpIntermediateImage,
captureActual: this.globalCaptureActual,
captureExpected: this.globalCaptureExpected
};
if (options && 'object' === typeof options) {
// Sanitize the allowed tolerance [percent].
if ('undefined' !== typeof options.tolerance) {
newValues.tolerance = Math.max(0, parseFloat(options.tolerance));
}
// Maybe define a custom filename for the expected image file.
if ('undefined' !== typeof options.compareWith) {
newValues.compareWith = options.compareWith;
}
// Set bounding box, either via element selector or a rectangle.
if (options.element) {
const bounds = await this._getBoundingBox(options.element);
newValues.element = options.element;
newValues.bounds.left = bounds.left;
newValues.bounds.top = bounds.top;
newValues.bounds.width = bounds.width;
newValues.bounds.height = bounds.height;
} else if (options.bounds && 'object' === typeof options.bounds) {
newValues.bounds.left = parseInt(options.bounds.left);
newValues.bounds.top = parseInt(options.bounds.top);
newValues.bounds.width = parseInt(options.bounds.width);
newValues.bounds.height = parseInt(options.bounds.height);
}
// Sanitize ignored regions.
if (options.ignore) {
for (let i = 0; i < options.ignore.length; i++) {
const item = options.ignore[i];
if (
'object' === typeof item
&& 'undefined' !== typeof item.left
&& 'undefined' !== typeof item.top
&& 'undefined' !== typeof item.width
&& 'undefined' !== typeof item.height
) {
newValues.ignore.push({
left: parseInt(item.left),
top: parseInt(item.top),
width: parseInt(item.width),
height: parseInt(item.height)
});
}
}
}
// Add pixelmatch arguments.
if (options.args && 'object' === typeof options.args) {
for (const key in options.args) {
if (!options.args.hasOwnProperty(key)) {
continue;
}
newValues.args[key] = options.args[key];
}
}
// Debug: Dump intermediate images.
if ('undefined' !== typeof options.dumpIntermediateImage) {
newValues.dumpIntermediateImage = this._toBool(options.dumpIntermediateImage);
}
// Capture screenshots before comparison?
if ('undefined' !== typeof options.captureActual) {
newValues.captureActual = this._toBool(options.captureActual, ['missing']);
}
if ('undefined' !== typeof options.captureExpected) {
newValues.captureExpected = this._toBool(options.captureExpected, ['missing']);
}
}
this.options = newValues;
// Prepare paths for the current operation.
this.path.expected = this._buildPath('expected');
this.path.actual = this._buildPath('actual');
// Diff-image generation might be disabled.
if (this.globalDir.diff) {
this.path.diff = this._buildPath('diff');
}
}
/**
* Returns the instance of the current browser driver.
*
* @return {Puppeteer|WebDriver|Appium|WebDriverIO|TestCafe}
* @private
*/
_getDriver() {
let driver = null;
if (this.helpers['Puppeteer']) {
driver = this.helpers['Puppeteer'];
driver._which = 'Puppeteer';
} else if (this.helpers['WebDriver']) {
driver = this.helpers['WebDriver'];
driver._which = 'WebDriver';
} else if (this.helpers['Appium']) {
driver = this.helpers['Appium'];
driver._which = 'Appium';
} else if (this.helpers['WebDriverIO']) {
driver = this.helpers['WebDriverIO'];
driver._which = 'WebDriverIO';
} else if (this.helpers['TestCafe']) {
driver = this.helpers['TestCafe'];
driver._which = 'TestCafe';
} else if (this.helpers['Playwright']) {
driver = this.helpers['Playwright'];
driver._which = 'Playwright';
} else {
throw new Error(
'Unsupported driver. The pixelmatch helper supports [Playwright|WebDriver|Appium|Puppeteer|TestCafe]');
}
return driver;
}
/**
* Recursively creates the specified directory.
*
* @param dir
* @private
*/
_mkdirp(dir) {
fs.mkdirSync(dir, {recursive: true});
}
/**
* Deletes the specified file, if it exists.
*
* @param {string} file - The file to delete.
* @private
*/
_deleteFile(file) {
try {
if (this._isFile(file)) {
fs.unlinkSync(file);
}
} catch (err) {
throw new Error(`Could not delete target file "${file}" - is it read-only?`);
}
}
/**
* Tests, if the given file exists..
*
* @param {string} file - The file to check.
* @param {string} mode - Optional. Either empty, or 'read'/'write' to
* validate that the current user can either read or write the file.
* @private
*/
_isFile(file, mode) {
let accessFlag = fs.constants.F_OK;
if ('read' === mode) {
accessFlag |= fs.constants.R_OK;
} else if ('write' === mode) {
accessFlag |= fs.constants.W_OK;
}
try {
// If access permission fails, an error is thrown.
fs.accessSync(file, accessFlag);
return true;
} catch (err) {
if ('ENOENT' !== err.code) {
console.error(err.code + ': ' + file);
}
return false;
}
}
/**
* Builds the absolute path to a relative folder.
*
* @param {string} dir - The relative folder name.
* @returns {string}
* @private
*/
_resolvePath(dir) {
if (!path.isAbsolute(dir)) {
return path.resolve(global.codecept_dir, dir) + '/';
}
return dir;
}
/**
* Returns the filename of an image.
*
* @param {string} which - Which image to return (expected, actual, diff).
* @param {string} suffix - Optional. A suffix to append to the filename.
* @private
*/
_getFileName(which, suffix) {
let filename;
// Define a custom filename for the expected image.
if ('expected' === which && this.options.compareWith) {
filename = this.options.compareWith;
} else {
filename = this.imageName;
}
if ('.png' !== filename.substr(-4)) {
filename += '.png';
}
if ('diff' === which) {
const parts = filename.split(/[\/\\]/);
parts[parts.length - 1] = this.globalDiffPrefix + parts[parts.length - 1];
filename = parts.join(path.sep);
}
if (suffix) {
suffix = '.' + suffix.toString().replace(/(^\.+|\.+$)/g, '') + '.png';
filename = filename.substr(0, filename.length - 4) + suffix;
}
return filename;
}
/**
* Builds an image path using the current image name and the specified folder.
*
* @param {string} which - The image to load (expected, actual, diff).
* @param {string} suffix - Optional. A suffix to append to the filename.
* @returns {string} Path to the image.
* @private
*/
_buildPath(which, suffix) {
let fullPath;
const dir = this.globalDir[which];
if (!dir) {
if ('diff' === which) {
// Diff image generation is disabled.
return '';
}
if (path.isAbsolute(which) && this._isFile(which)) {
fullPath = which;
} else {
throw new Error(`No ${which}-folder defined.`);
}
} else {
fullPath = dir + this._getFileName(which, suffix);
this._mkdirp(path.dirname(fullPath));
}
return fullPath;
}
/**
* Returns a list of absolute image paths of base images for the comparison.
* All files in the returned list exist in the filesystem.
*
* Naming convention:
*
* Files that contain a trailing "~<num>" suffix are considered part of the
* matching list.
*
* For example:
*
* image: "google-home"
* files:
* "google-home.png" # exact match
* "google-home~1.png" # variation
* "google-home~83.png" # variation
*
* @return {string[]}
* @private
*/
_getExpectedImagePaths() {
const list = [];
const fullPath = this._buildPath('expected');
const dir = path.dirname(fullPath);
const file = path.basename(fullPath);
const re = new RegExp('^' + file.replace('.png', '(:?~.+)?\\.png') + '$');
this._mkdirp(dir);
fs.readdirSync(dir).map(fn => {
if (fn.match(re)) {
list.push(`${dir}/${fn}`);
}
});
return list;
}
/**
* Loads the specified image and returns a PNG blob.
*
* @param {string} which - The image to load (expected, actual, diff).
* @param {string} suffix - Optional. A suffix to append to the filename.
* @return {object} An PNG object.
* @private
*/
_loadPngImage(which, suffix) {
const path = this._buildPath(which, suffix);
if (!path) {
throw new Error(`No ${which}-image defined.`);
}
this.debug(`Load image from ${path} ...`);
if (!this._isFile(path, 'read')) {
throw new Error(`The ${which}-image does not exist at "${path}"`);
}
const data = fs.readFileSync(path);
return PNG.sync.read(data);
}
/**
* Saves the specified PNG image to the filesystem.
* .
* @param {string} which - The image to load (expected, actual, diff).
* @param {object} png - An PNG image object.
* @param {string} suffix - Optional. A suffix to append to the filename.
* @private
*/
_savePngImage(which, png, suffix) {
const path = this._buildPath(which, suffix);
if (!path) {
if ('diff' === which) {
// Diff generation can be disabled by setting the path to
// false/empty. This is not an error.
return;
} else {
throw new Error(`No ${which}-image defined.`);
}
}
this.debug(`Save image to ${path} ...`);
if (this._isFile(path) && !this._isFile(path, 'write')) {
throw new Error(`Cannot save the ${which}-image to ${path}. Maybe the file is read-only.`);
}
let data;
if (png instanceof PNG) {
data = PNG.sync.write(png);
} else if (png instanceof Buffer) {
data = png;
}
if (data && data instanceof Buffer) {
fs.writeFileSync(path, data);
}
}
/**
* Clears a rectangular area inside the given PNG image object. The change
* is only applied in-memory and does not affect the saved image.
*
* @param {object} png - The PNG object.
* @param {int} x0
* @param {int} y0
* @param {int} x1
* @param {int} y1
* @return {int} Number of cleared pixels.
* @private
*/
_clearRect(png, x0, y0, x1, y1) {
let count = 0;
x0 = Math.min(png.width, Math.max(0, parseInt(x0)));
x1 = Math.min(png.width, Math.max(0, parseInt(x1)));
y0 = Math.min(png.height, Math.max(0, parseInt(y0)));
y1 = Math.min(png.height, Math.max(0, parseInt(y1)));
if (x0 === x1 || y0 === y1) {
return 0;
}
if (x1 < x0) {
const xt = x1;
x1 = x0;
x0 = xt;
}
if (y1 < y0) {
const yt = y1;
y1 = y0;
y0 = yt;
}
const numBytes = 4 + (x1 - x0);
for (let y = y0; y < y1; y++) {
for (let x = x0; x < x1; x++) {
const k = 4 * (x + png.width * y);
if (png.data[k + 3] > 0) {
count++;
}
png.data.fill(0, k, k + 4);
}
}
this.debug(`Clear Rect ${x0}/${y0} - ${x1}/${y1} | ${count} pixels cleared`);
// Return the real number of cleared pixels.
return count;
}
/**
* Casts the given value into a boolean. Several string terms are translated
* to boolean true. If validTerms are specified, and the given value matches
* one of those validTerms, the term is returned instead of a boolean.
*
* Sample:
*
* _toBool('yes') --> true
* _toBool('n') --> false
* _toBool('any') --> false
* _toBool('ANY', ['any', 'all']) --> 'any'
*
* @param {any} value - The value to cast.
* @param {array} validTerms - List of terms that should not be cast to a
* boolean but returned directly.
* @return {bool|string} Either a boolean or a lowercase string.
* @private
*/
_toBool(value, validTerms) {
if (true === value || false === value) {
return value;
}
if (value && 'string' === typeof value) {
value = value.toLowerCase();
return -1 !== ['1', 'on', 'y', 'yes', 'true', 'always'].indexOf(value);
}
if (validTerms && Array.isArray(validTerms) && -1 !== validTerms.indexOf(value)) {
return value;
}
return !!value;
}
} |
JavaScript | class Middleware {
/**
* Middleware initialization
*
* @param {String} middleware name
*/
constructor(name='') {
this.name = name;
}
/**
* Invoked by the app before an ajax request is sent or
* during the DOM loading (document.readyState === 'loading').
* See Application#_callMiddlewareEntered documentation for details.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @public
*/
entered(request) { }
/**
* Invoked by the app before a new ajax request is sent or before the DOM is unloaded.
* See Application#_callMiddlewareExited documentation for details.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @public
*/
exited(request) { }
/**
* Invoked by the app after an ajax request has responded or on DOM ready
* (document.readyState === 'interactive').
* See Application#_callMiddlewareUpdated documentation for details.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @param {Object} response
* @public
*/
updated(request, response) { }
/**
* Invoked by the app when an ajax request has failed.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @param {Object} response
* @public
*/
failed(request, response) { }
/**
* Allow the hand over to the next middleware object or function.
*
* Override this method and return `false` to break execution of
* middleware chain.
*
* @return {Boolean} `true` by default
*
* @public
*/
next() {
return true;
}
} |
JavaScript | class Shadow extends PIXI.Sprite {
constructor(range, intensity, pointCount, scatterRange) {
super(PIXI.RenderTexture.create(range * 2, range * 2));
this._range = range;
this._pointCount = pointCount || 20; //The number of lightpoins
this._scatterRange = scatterRange || (this._pointCount == 1 ? 0 : 15);
this._intensity = intensity || 1;
this._radialResolution = 800;
this._depthResolution = 1; //per screen pixel
this._darkenOverlay = false;
this._overlayLightLength = Infinity;
this.anchor.set(0.5);
this._ignoreShadowCaster;
this.__createShadowMapSources();
}
// Create the texture to apply this mask filter to
__updateTextureSize() {
this.texture.destroy();
this.texture = PIXI.RenderTexture.create(
this._range * 2,
this._range * 2
);
}
// Create the resources that create the shadow map
__createShadowMapSources() {
if (this._shadowMapSprite) this._shadowMapSprite.destroy();
if (this._shadowMapResultSprite) this._shadowMapResultSprite.destroy();
if (this._shadowMapResultTexture)
this._shadowMapResultTexture.destroy();
// A blank texture/sprite to apply the filter to
this._shadowMapResultTexture = PIXI.RenderTexture.create(
this._radialResolution,
this._pointCount
);
this._shadowMapResultTexture.baseTexture.scaleMode =
PIXI.SCALE_MODES.NEAREST;
this._shadowMapSprite = new PIXI.Sprite(this._shadowMapResultTexture);
this._shadowMapSprite.filters = [new ShadowMapFilter(this)];
// The resulting texture/sprite after the filter has been applied
this._shadowMapResultSprite = new PIXI.Sprite(
this._shadowMapResultTexture
);
// Create the mask filter
var filter = new ShadowMaskFilter(this);
filter.blendMode = PIXI.BLEND_MODES.ADD;
this.shadowFilter = filter;
this.filters = [filter];
}
// Properly dispose all the created resources
destroy() {
if (this._shadowMapSprite) this._shadowMapSprite.destroy();
if (this._shadowMapResultSprite) this._shadowMapResultSprite.destroy();
if (this._shadowMapResultTexture)
this._shadowMapResultTexture.destroy();
this.texture.destroy();
return super.destroy();
}
// Don't render this sprite unless we are in the dedicated render step called by the shadow filter
renderAdvancedWebGL(renderer) {
if (this.renderStep) super.renderAdvancedWebGL(renderer);
}
// Update the map to create the mask from
update(renderer, shadowCasterSprite, shadowOverlaySprite) {
this._shadowCasterSprite = shadowCasterSprite;
this._shadowOverlaySprite = shadowOverlaySprite;
renderer.render(
this._shadowMapSprite,
this._shadowMapResultTexture,
true,
null,
true
);
}
// Attribute setters
/**
* @type {number} The radius of the lit area in pixels.
*/
set range(range) {
this._range = range;
this.__updateTextureSize();
}
/**
* @type {number} The number of points that makes up this light, for soft shadows. (More points = softer shadow edges + more intensive).
*/
set pointCount(count) {
this._pointCount = count;
this.__createShadowMapSources();
}
/**
* @type {number} The opacity of the lit area. (may exceed 1).
*/
set scatterRange(range) {
this._scatterRange = range;
}
/**
* @type {number} The radius at which the points of the light should be scattered. (Greater range = software shadow).
*/
set intensity(intensity) {
this._intensity = intensity;
}
/**
* @type {number} The number of rays to draw for the light. (Higher resolution = more precise edges + more intensive).
*/
set radialResolution(resolution) {
this._radialResolution = resolution;
this.__createShadowMapSources();
}
/**
* @type {number} The of steps to take per pixel. (Higher resolution = more precise edges + more intensive).
*/
set depthResolution(resolution) {
this._depthResolution = resolution;
}
/**
* @type {PIXI.Sprite} A shadow caster to ignore while creating the shadows. (Can be used if sprite and light always overlap).
*/
set ignoreShadowCaster(sprite) {
this._ignoreShadowCaster = sprite;
}
/**
* @type {boolean} Whther or not overlays in shadows should become darker (can create odd artifacts, is very experimental/unfinished)
*/
set darkenOverlay(bool) {
this._darkenOverlay = bool;
}
/**
* @type {number} How many pixels of the overlay should be lit up by the light
*/
set overlayLightLength(length) {
this._overlayLightLength = length;
}
// Attribute getters
get range() {
return this._range;
}
get pointCount() {
return this._pointCount;
}
get scatterRange() {
return this._scatterRange;
}
get intensity() {
return this._intensity;
}
get radialResolution() {
return this._radialResolution;
}
get depthResolution() {
return this._depthResolution;
}
get ignoreShadowCaster() {
return this._ignoreShadowCaster;
}
get darkenOverlay() {
return this._darkenOverlay;
}
get overlayLightLength() {
return this._overlayLightLength;
}
} |
JavaScript | class LinkedHashMap {
/**
* Creates a linked hash map instance
* @public
*/
constructor() {
this._data = new Map();
this._link = new Map();
this._head = undefined;
this._tail = undefined;
}
/**
* Add or update an item to the list
* @public
* @param {any} key
* @param {any} item
* @param {boolean} head add to the head if true; tail otherwise
*/
put(key, item, head = false) {
if (this.has(key)) {
this._data.set(key, item);
return;
}
this._data.set(key, item);
this._link.set(key, {
previous: undefined,
next: undefined
});
if (this._head == null) {
this._head = key;
this._tail = key;
} else if (head) {
this._link.get(this._head).previous = key;
this._link.get(key).next = this._head;
this._head = key;
} else {
this._link.get(this._tail).next = key;
this._link.get(key).previous = this._tail;
this._tail = key;
}
}
/**
* Returns the head key and item
* @public
* @returns {any} key, item, next(), previous()
*/
head() {
return ({
key: this._head, value: this.get(this._head), next: () => this.next(this._head), previous: () => null
});
}
/**
* Returns the tail key and item
* @public
* @returns {any} key, item, next(), previous()
*/
tail() {
return ({
key: this._tail, value: this.get(this._tail), next: () => null, previous: () => this.previous(this._tail)
});
}
/**
* Returns an item from the map by key
* @public
* @param {any} key
* @returns {any} item
*/
get(key) {
return this._data.get(key);
}
/**
* Returns previous key item of the key
* @public
* @param {any} key
* @returns {any} key
*/
previousKey(key) {
const link = this._link.get(key);
return link != null ? link.previous : undefined;
}
/**
* Returns previous item of the key
* @public
* @param {any} key
* @returns {any} item
*/
previousValue(key) {
return this.get(this.previousKey(key));
}
/**
* Returns previous key, item of the key
* @public
* @param {any} key
* @returns {any} key, item, next(), previous()
*/
previous(key) {
const prevKey = this.previousKey(key);
return ({
key: prevKey,
value: this.get(prevKey),
next: () => this.next(prevKey),
previous: () => this.previous(prevKey)
});
}
/**
* Returns next key of the key
* @public
* @param {any} key
* @returns {any} key
*/
nextKey(key) {
const link = this._link.get(key);
return link != null ? link.next : undefined;
}
/**
* Returns next item of the key
* @public
* @param {any} key
* @returns {any} item
*/
nextValue(key) {
return this.get(this.nextKey(key));
}
/**
* Returns next key, item of the key
* @public
* @param {any} key
* @returns {any} key, item, next(), previous()
*/
next(key) {
const nextKey = this.nextKey(key);
return ({
key: nextKey,
value: this.get(nextKey),
next: () => this.next(nextKey),
previous: () => this.previous(nextKey)
});
}
/**
* Removes and returns an item from the map
* @public
* @param {any} key
* @returns {any} item
*/
remove(key) {
const item = this._data.get(key);
if (item != null) {
if (this.size() === 1) {
this.reset();
} else {
if (key === this._head) {
const headLink = this._link.get(this._head);
this._link.get(headLink.next).previous = null;
this._head = headLink.next;
} else if (key === this._tail) {
const tailLink = this._link.get(this._tail);
this._link.get(tailLink.previous).next = null;
this._tail = tailLink.previous;
} else {
const cur = this._link.get(key);
const prev = this._link.get(cur.previous);
const nex = this._link.get(cur.next);
prev.next = cur.next;
nex.previous = cur.previous;
}
this._link.delete(key);
this._data.delete(key);
}
}
return item;
}
/**
* Return if the key exists in the map
* @public
* @param {any} key;
* @returns {boolean}
*/
has(key) {
return this._data.has(key);
}
/**
* Returns the size of the map
* @public
* @returns {number}
*/
size() {
return this._data.size;
}
/**
* Empties the map
* @public
*/
reset() {
this._data.clear();
this._link.clear();
this._head = undefined;
this._tail = undefined;
}
/**
* Returns an iterator of keys
* @public
* @returns {Iterator[key]}
*/
keys() {
return this._data.keys();
}
/**
* Returns an iterator of values
* @public
* @returns {Iterator[value]}
*/
values() {
return this._data.values();
}
/**
* Returns an iterator of keys and values
* @public
* @returns {Iterator[key, value]}
*/
entries() {
return this._data.entries();
}
/**
* Returns array representation of the map values
* @public
* @param {'orderByInsert' | 'orderByLink'} order return by inserting order (default) or link order
* @returns {Array<{key: any, value: any}>}
*/
toArray(order = 'orderByInsert') {
if (order !== 'orderByInsert') {
const linkOrderArr = [];
let next = this._head;
while (next != null) {
linkOrderArr.push({ key: next, value: this.get(next) });
next = this.nextKey(next);
}
return linkOrderArr;
}
return Array.from(this.keys()).map((k) => ({ key: k, value: this.get(k) }));
}
} |
JavaScript | class WasheeDataService {
getWasheeById(id) {
return axios.get(`${WASHEE_API_URL}/${id}`);
}
getAllWashees() {
return axios.get(`${WASHEE_API_URL}`);
}
getFavorites(id){
return axios.get(`${WASHEE_API_URL}/${id}/favorites`)
}
addFavorite(id, favorite){
return axios.post(`${WASHEE_API_URL}/${id}/addFavorite`, favorite)
}
removeFavorite(id, index){
return axios.post(`${WASHEE_API_URL}/${id}/${index}`)
}
register(firstName, lastName, email, password, phoneNo, accountType, companyName, acceptsMarketingEmails, addresses, aboutMe, paymentMethods) {
var payload = {
"firstName": firstName,
"lastName": lastName,
"email": email,
"password": password,
"phoneNo": phoneNo,
"accountType": accountType,
"companyName": companyName,
"userType":"WASHEE",
"acceptsMarketingEmails": acceptsMarketingEmails,
"addresses": addresses,
"aboutMe": aboutMe,
"paymentMethods":paymentMethods,
"image":"https://cdn0.iconfinder.com/data/icons/basic-ui-1-line/64/Artboard_18-512.png"
};
// console.log(payload);
return axios.post(WASHEE_API_URL + '/register', payload);
}
} |
JavaScript | class Enemy {
constructor(dx, dy) {
// Variables applied to each of our instances go here,
// we've provided one for you to get started
// The image/sprite for our enemies, this uses
// a helper we've provided to easily load images
this.sprite = 'images/enemy-bug.png';
this.sx = 1;
this.sy = 76;
this.sWidth = 99;
this.sHeight = 69;
this.dx = dx;
this.dy = dy;
this.dWidth = 99;
this.dHeight = 69;
this.width = 101;
this.height = 171;
}
// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
update(dt) {
if (this.dx < 505) {
this.s = Math.random() * 300;
this.dx = this.dx + this.s * dt;
}
else if (this.dx > 505) {
this.dx = 0;
}
// You should multiply any movement by the dt parameter
// which will ensure the game runs at the same speed for
// all computers.
}
// Draw the enemy on the screen, required method for game
render() {
ctx.drawImage(Resources.get(this.sprite), this.sx, this.sy, this.sWidth, this.sHeight, this.dx, this.dy, this.dWidth, this.dHeight);
}
} |
JavaScript | class Player {
constructor(dx, dy, event) {
this.sprite = 'images/players/char-boy.png';
this.h = 101;
this.v = 80;
this.sx = 19;
this.sy = 59;
this.sWidth = 69;
this.sHeight = 76;
this.dx = dx;
this.dy = dy;
this.dWidth = 69;
this.dHeight = 76;
this.lives = 3;
this.score = 0;
this.wins = 0;
this.gems = 0;
this.won = false;
this.collision = false;
this.collection = false;
this.restart = false;
this.avatarSwitch = false;
this.tickerScore = document.getElementById("ticker-score");
this.tickerWins = document.getElementById("ticker-won");
this.tickerLives = document.getElementById("ticker-lives");
this.tickerGems = document.getElementById("ticker-gems");
this.tickerMessage = document.getElementById("ticker-update");
this.players = ['images/players/char-boy.png',
'images/players/char-cat-girl.png',
'images/players/char-horn-girl.png',
'images/players/char-pink-girl.png',
'images/players/char-princess-girl.png',
];
}
// This class requires an update(), render() and
// a handleInput() method.
update() {
if (this.dx > 505 - this.dWidth - this.sx) {
this.dx = 505 - this.dWidth - this.sx;
}
else if (this.dx < 0) {
this.dx = this.sx;
}
if (this.dy > 606 - this.dHeight - this.sy) {
this.dy = 606 - this.dHeight - this.sy;
}
else if (this.dy < 0) {
this.dy = 47.5;
// scores(this.dy);
}
}
render() {
// console.log(this.sprite);
ctx.drawImage(Resources.get(this.sprite), this.sx, this.sy, this.sWidth, this.sHeight, this.dx, this.dy, this.dWidth, this.dHeight);
}
handleInput(keyCode) {
switch (keyCode) {
case 'left':
this.dx = this.dx - this.h;
break;
case 'up':
this.dy = this.dy - this.v;
break;
case 'right':
this.dx = this.dx + this.h;
break;
case 'down':
this.dy = this.dy + this.v;
break;
}
}
//Ramdomly select an avatar from the player avatar array
avatar() {
this.sprite = this.players[Math.floor(Math.random() * this.players.length)];
}
// Game start and restart method
start() {
if (this.restart == true) {
console.log(this.restart == true);
this.score = 0;
this.lives = 3;
this.wins = 0;
this.gems = 0;
this.tickerScore.innerHTML = this.score;
this.tickerLives.innerHTML = this.lives;
this.tickerScore.innerHTML = this.score;
this.tickerGems.innerHTML = this.gems;
this.tickerWins.innerHTML = this.wins;
this.tickerMessage.innerHTML = "GOOD LUCK! Each succesful crossing earns you 100 points and one extra life! Don't squash the bugs on the way that'll cost you a life!";
this.restart = false;
}
}
// Bug collision update method
collide() {
if (this.collision == true) {
console.log(this.collision == true);
this.lives--;
this.score = this.score - 100;
this.tickerScore.innerHTML = this.score;
this.tickerLives.innerHTML = this.lives;
this.tickerScore.innerHTML = this.score;
this.tickerGems.innerHTML = this.gems;
this.tickerWins.innerHTML = this.wins;
this.tickerMessage.innerHTML = "OOPS, BE CAREFUL! Don't squash the bugs!";
this.collision = false;
if (this.lives == 0) {
this.tickerMessage.innerHTML = "GAME OVER! Each bug you squash is a life and you only have three! Click START GAME to plan again!";
this.score = 0;
this.lives = 0;
this.wins = 0;
this.gems = 0;
this.tickerScore.innerHTML = this.score;
this.tickerLives.innerHTML = this.lives;
this.tickerScore.innerHTML = this.score;
this.tickerGems.innerHTML = this.gems;
this.tickerWins.innerHTML = this.wins;
this.dx = 505;
this.dy = 606;
}
}
}
// Feature collection method
collect() {
if (this.collection == true) {
console.log(features.imgFeatures[0]);
switch (features.feature) {
case features.imgFeatures[0]:
this.score = 200 + this.score;
this.gems++;
this.tickerScore.innerHTML = this.score;
this.tickerGems.innerHTML = this.gems;
this.tickerMessage.innerHTML = `Nice! The Blue Gem earned you 200 points!`;
this.collection = false;
break;
case features.imgFeatures[1]:
this.score = 500 + this.score;
this.gems++;
this.tickerScore.innerHTML = this.score;
this.tickerGems.innerHTML = this.gems;
this.tickerMessage.innerHTML = `Awesome! The Green Gem earned you 500 points!`;
this.collection = false;
break;
case features.imgFeatures[2]:
this.score = 100 + this.score;
this.gems++;
this.tickerScore.innerHTML = this.score;
this.tickerGems.innerHTML = this.gems;
this.tickerMessage.innerHTML = `Way-to-go! The Orange Gem earned you 100 points!`;
this.collection = false;
break;
case features.imgFeatures[3]:
this.lives++;
this.tickerLives.innerHTML = this.lives;
this.tickerMessage.innerHTML = `You won my heart! The Heart earned you another life!`;
this.collection = false;
break;
case features.imgFeatures[4]:
this.lives++;
this.lives++;
this.tickerLives.innerHTML = this.lives;
this.tickerMessage.innerHTML = `The key to succuss! That Golden Key earned you 2 lives!`;
this.collection = false;
break;
case features.imgFeatures[5]:
this.lives++;
this.tickerLives.innerHTML = this.lives;
this.tickerMessage.innerHTML = `You are a STAR! That star just earned you another life!`;
this.collection = false;
break;
case features.imgFeatures[6]:
this.score = -300 + this.score;
this.lives--;
this.tickerLives.innerHTML = this.lives;
this.tickerScore.innerHTML = this.score;
this.tickerMessage.innerHTML = `Whoops, watch out! The Rock just took away 1 life and 300 points!`;
this.collection = false;
break;
default:
}
}
}
// Successful crossing method
success() {
if (this.dy == 47.50) {
console.log(this.dy == 47.50);
this.won = true;
this.score += 100;
this.wins += 1;
this.lives += 1;
this.dx = 505;
this.dy = 606;
this.tickerScore.innerHTML = this.score;
this.tickerLives.innerHTML = this.lives;
this.tickerWins.innerHTML = this.wins;
// this.tickerMessage.innerHTML = `WELL DONE! You had it... that's worth 1 extra life and 100 points!`;
this.avatar();
features.select();
}
}
} |
JavaScript | class Features {
constructor(dx, dy, feature) {
this.sprite = 'images/features/Gem-Blue.png';
this.sx = 0;
this.sy = 52;
this.sWidth = 101;
this.sHeight = 119;
this.dx = dx;
this.dy = dy;
this.dWidth = 101;
this.dHeight = 119;
this.feature = feature;
this.imgFeatures = [
'images/features/Gem-Blue.png',
'images/features/Gem-Green.png',
'images/features/Gem-Orange.png',
'images/features/Heart.png',
'images/features/Key.png',
'images/features/Star.png',
'images/features/Rock.png',
];
}
// Method to randomly select and place a feature
select() {
this.sprite = this.imgFeatures[Math.floor(Math.random() * this.imgFeatures.length)];
this.feature = this.sprite;
this.dx = Math.floor(((Math.random() * 5) * 100));
this.dy = Math.floor((Math.random() * 3) * 75 + 75);
this.render(this.sprite, this.dx, this.dy);
}
// Method to provide game feature only after first succussful crossing
update() {
if (Player.won == true) {
this.render();
}
}
// Render feature based on it's dimensions and the select method
render() {
ctx.drawImage(Resources.get(this.sprite), this.sx, this.sy, this.sWidth, this.sHeight, this.dx, this.dy, this.dWidth, this.dHeight);
}
} |
JavaScript | class BleServer extends EventEmitter {
/**
* Create a BleServer instance.
* @param {Bleno} bleno - a Bleno instance.
* @param {string} name - the name used in advertisement.
* @param {PrimaryService[]} - the GATT service instances.
*/
constructor(bleno, name, services) {
super();
this.state = 'stopped'; // stopped | starting | started | connected
this.bleno = bleno;
this.name = name;
this.services = services;
this.uuids = services.map(s => s.uuid);
this.bleno.on('accept', this.onAccept.bind(this));
this.bleno.on('disconnect', this.onDisconnect.bind(this));
this.bleno.startAdvertisingAsync = util.promisify(this.bleno.startAdvertising);
this.bleno.stopAdvertisingAsync = util.promisify(this.bleno.stopAdvertising);
this.bleno.setServicesAsync = util.promisify(this.bleno.setServices);
}
/**
* Advertise and wait for connection.
*/
async start() {
if (this.state !== 'stopped') {
throw new Error('already started');
}
this.state = 'starting';
await once(this.bleno, 'stateChange');
await this.bleno.startAdvertisingAsync(this.name, this.uuids);
await this.bleno.setServicesAsync(this.services);
this.state = 'started';
}
/**
* Disconnect any active connection and stop advertising.
*/
async stop() {
if (this.state === 'stopped') return;
await this.bleno.stopAdvertisingAsync();
this.bleno.disconnect();
}
/**
* Handle connection from a Bluetooth LE Central device (client).
* @param {string} address - MAC address of device.
* @emits BleServer#connect
* @private
*/
onAccept(address) {
/**
* Connect event.
* @event BleServer#connect
* @type {string} address - MAC address of device.
*/
this.emit('connect', address);
}
/**
* Handle disconnection of a Bluetooth LE Central device.
* @param {string} address - MAC address of device.
* @emits BleServer#disconnect
* @private
*/
onDisconnect(address) {
/**
* Disconnect event.
* @event BleServer#disconnect
* @type {string} address - MAC address of device.
*/
this.emit('disconnect', address);
}
} |
JavaScript | class TwitchApi {
/**
* Gets the data to every user in the users parameter
* Calls the callback function with the JSON Data when request finished
* @param {string} users comma separated list with usernames
* @param {object} context sets the Object 'this' is referring to in the callback function
* @param {function} callback function(data) that gets called after the request finished
*/
static getUsers(users, context, callback) {
$.ajax({
context: context,
url: ('https://api.twitch.tv/helix/users'),
dataType: 'json',
headers: {
'Client-ID': TwitchConstants.CLIENT_ID,
'Authorization': ('Bearer ' + localStorage.accessToken),
},
data: {login: users},
async: true,
}).done(callback).fail(function(jqXHR, textStatus) {
console.log("Request failed: " + textStatus);
console.log(jqXHR);
});
}
/**
* Gets the data to the user the OAuth token is from
* @return {data}
*/
static async getUserFromOAuth() {
return await $.ajax({
statusCode: {
401: function() {
window.location.replace(TwitchConstants.AUTHORIZE_URL);
},
},
url: ('https://id.twitch.tv/oauth2/validate'),
dataType: 'json',
headers: {
'Authorization': ('OAuth ' + localStorage.accessToken),
},
});
}
/**
* Gets the names of all chatters in the specified chat
* @param {string} chatName name of the chat
* @param {object} context sets the Object 'this' is referring to in the callback function
* @param {function} callback function(data) that gets called after the request finished
*/
static getChatterList(chatName, context, callback) {
$.ajax({
context: context,
url: ('https://tmi.twitch.tv/group/user/' + chatName
+ '/chatters'),
headers: {'Accept': 'application/vnd.twitchtv.v5+json'},
dataType: 'jsonp',
async: true,
}).done(callback);
}
// noinspection JSUnusedGlobalSymbols
/**
* Gets recent messages from the specified chat
* @param {string} chatName
* @param {object} context sets the Object 'this' is referring to in the callback function
* @param {function} callback function(data) that gets called after the request finished
*/
static getRecentMessages(chatName, context, callback) {
// Download recent messages
$.ajax({
context: context,
type: 'GET',
url: ('https://recent-messages.robotty.de/api/v2/recent-messages/' + chatName),
async: true,
}).done(callback);
}
} |
JavaScript | class AppUser {
/**
* @constructor
*/
constructor() {
/** @private */
this.userName_ = '';
// noinspection JSUnusedGlobalSymbols
/** @private */
this.userNameLC_ = '';
// noinspection JSUnusedGlobalSymbols
/** @private */
this.userId_ = '';
}
/**
* Getter
* @return {string} this.userName_
*/
getUserName() {
return this.userName_;
}
/**
* Getter
* @return {string} this.userId_
*/
getUserId() {
return this.userId_;
}
/**
* Sends an ajax request to twitch to receive userName_ and userId_ of the AppUser
* @return {Promise}
*/
async requestAppUserData() {
return await TwitchApi.getUserFromOAuth().then((data) => {
if (typeof(data.login) !== 'undefined') {
this.userName_ = data.login;
// noinspection JSUnusedGlobalSymbols
this.userNameLC_ = data.login.toLowerCase();
// noinspection JSUnusedGlobalSymbols
this.userId_ = data.user_id;
} else {
alert('Error while getting username');
}
});
}
} |
JavaScript | class TwitchIRCConnection {
/**
* @param {AppUser} appUser
* @constructor
*/
constructor(appUser) {
/** @private */
this.appUser_ = appUser;
if (new.target === TwitchIRCConnection) {
throw new TypeError('Cannot construct abstract instances ' +
'of TwitchIRCConnection directly');
}
this.isLoaded_ = false;
this.connection_ = new WebSocket(TwitchConstants.WEBSOCKET_URL);
this.connection_.onopen = this.onOpen_.bind(this);
this.connection_.onerror = TwitchIRCConnection.onError_.bind(this);
}
/**
* Gets called when the connection established
* @private
*/
onOpen_() {
this.connection_.send('CAP REQ :twitch.tv/membership');
this.connection_.send('CAP REQ :twitch.tv/tags');
this.connection_.send('CAP REQ :twitch.tv/commands');
this.connection_.send('PASS oauth:' + localStorage.accessToken);
this.connection_.send('NICK ' + this.appUser_.getUserName());
this.isLoaded_ = true;
}
/**
* @return {boolean}
*/
isLoaded() {
return this.isLoaded_;
}
/**
* Gets called on error
* @private
*/
static onError_() {
console.log('WebSocket Error ' + error);
alert('ERROR: ' + error);
}
// noinspection JSUnusedGlobalSymbols
/**
* Gets called on message
* @param {object} event event triggered by the Websocket connection
* @private
* @abstract
*/
onMessage_(event) {};
/**
* Leave the specified chat
* @param {string} chatName
*/
leaveChat(chatName) {
this.connection_.send('PART #' + chatName);
}
/**
* Join the specified chat
* @param {string} chatName
*/
joinChat(chatName) {
this.connection_.send('JOIN #' + chatName);
}
/**
* Sends the specified message to the Websocket connection
* @param {string} message
*/
send(message) {
this.connection_.send(message);
}
} |
JavaScript | class SendIRCConnection extends TwitchIRCConnection {
/**
* @param {AppUser} appUser
* @constructor
*/
constructor(appUser) {
super(appUser);
this.connection_.onmessage = this.onMessage_.bind(this);
}
/**
* @param {object} event event triggered by the Websocket connection
* @private
*/
onMessage_(event) {
let messages = event.data.split('\n');
for (let i = 0; i < messages.length; i++) {
let msg = messages[i];
if (msg.length <= 1) {
continue;
}
if (msg.startsWith('PING :tmi.twitch.tv')) {
this.connection_.send('PONG :tmi.twitch.tv');
}
}
}
} |
JavaScript | class ReceiveIRCConnection extends TwitchIRCConnection {
/**
* @param {AppUser} appUser
* @param {MessageParser} messageParser
* @param {ChatManager} chatManager
* @constructor
*/
constructor(appUser, messageParser, chatManager) {
super(appUser);
this.messageParser_ = messageParser;
this.chatManager_ = chatManager;
this.connection_.onmessage = this.onMessage_.bind(this);
}
/**
* @param {object} event event triggered by the Websocket connection
* @private
*/
onMessage_(event) {
let messages = event.data.split('\n');
for (let i = 0; i < messages.length; i++) {
let msg = messages[i];
if (msg.startsWith('PING :tmi.twitch.tv')) {
this.connection_.send('PONG :tmi.twitch.tv');
} else if (msg.length > 1) {
let chatMessages = this.messageParser_.parseMessage(msg);
this.chatManager_.addMessages(chatMessages);
}
}
}
} |
JavaScript | class BadgeManager {
/**
* @constructor
*/
constructor() {
this.badgesChannels_ = {};
// noinspection JSUnusedGlobalSymbols
this.badgesGlobal_ = null;
this.downloadGlobalBadges_();
}
/**
* @return {Object}
*/
getBadgesChannels() {
return this.badgesChannels_;
}
/**
* @return {Object}
*/
getBadgesGlobal() {
return this.badgesGlobal_;
}
/**
* Downloads the JSON information for global badges
* @private
*/
downloadGlobalBadges_() {
// Download Global Badges JSON
$.ajax({
context: this,
url: (TwitchConstants.GLOBAL_BADGES_API_URL),
headers: {
'Accept': 'application/vnd.twitchtv.v5+json',
'Client-ID': TwitchConstants.CLIENT_ID,
},
async: true,
}).done(function(data) {
// noinspection JSUnusedGlobalSymbols
this.badgesGlobal_ = data.badge_sets;
});
}
/**
* @param {string} channelLC
* @param {string} channelId
*/
downloadChannelBadges(channelLC, channelId) {
// Download Channel Badges
$.ajax({
context: this,
url: ('https://badges.twitch.tv/v1/badges/channels/'
+ channelId + '/display'),
headers: {
'Accept': 'application/vnd.twitchtv.v5+json',
'Client-ID': TwitchConstants.CLIENT_ID,
},
async: true,
}).done(function(data) {
this.badgesChannels_[channelLC] = data.badge_sets;
});
}
} |
JavaScript | class EmoteManager {
/**
* @param {AppUser} appUser
* @constructor
*/
constructor(appUser) {
this.appUser_ = appUser;
this.userEmotes_ = {};
this.bttvChannels_ = {};
this.bttvGlobal_ = {};
this.ffzChannels_ = {};
this.ffzGlobal_ = {};
this.downloadGlobalEmotes_();
}
/**
* @return {Object}
*/
getUserEmotes() {
return this.userEmotes_;
}
/**
* @return {Object}
*/
getBttvGlobal() {
return this.bttvGlobal_;
}
/**
* @return {Object}
*/
getFfzGlobal() {
return this.ffzGlobal_;
}
/**
* @return {Object}
*/
getBttvChannels() {
return this.bttvChannels_;
}
/**
* @return {Object}
*/
getFfzChannels() {
return this.ffzChannels_;
}
/**
* Downloads the global Twitch, BTTV and FFZ Emote JSONs
* @private
*/
downloadGlobalEmotes_() {
// Gets a list of the emojis and emoticons that the specified
// user can use in chat.
$.ajax({
context: this,
url: ('https://api.twitch.tv/kraken/users/' + this.appUser_.getUserId() + '/emotes'),
headers: {
'Accept': 'application/vnd.twitchtv.v5+json',
'Client-ID': TwitchConstants.CLIENT_ID,
'Authorization': ('OAuth ' + localStorage.accessToken),
},
async: true,
}).done(function(data) {
this.userEmotes_ = data.emoticon_sets;
// console.log(data.emoticon_sets);
});
// Download Global BTTV Emotes JSON
$.ajax({
context: this,
url: ('https://api.betterttv.net/2/emotes'),
async: true,
}).done(function(data) {
this.bttvGlobal_ = data.emotes;
});
// Download Global FFZ Emotes JSON
$.ajax({
context: this,
url: ('https://api.frankerfacez.com/v1/set/global'),
async: true,
}).done(function(data) {
// console.log(data);
this.ffzGlobal_ = data;
});
}
/**
*
* @param {string} channelLC
*/
downloadChannelEmotes(channelLC) {
this.downloadFfzChannelEmotes_(channelLC);
this.downloadBttvChannelEmotes_(channelLC);
}
/**
*
* @param {string} channelLC
* @private
*/
downloadBttvChannelEmotes_(channelLC) {
// Download BTTV Channel Emotes
$.ajax({
context: this,
url: ('https://api.betterttv.net/2/channels/' + channelLC),
async: true,
dataType: 'json',
error: function(xhr) {
if (xhr.status === 404) {
// Ignore - No BTTV emotes in this channel
console.log('No BTTV Emotes in Channel: ' + channelLC);
}
},
}).done(function(data) {
this.bttvChannels_[channelLC] = data.emotes;
});
}
/**
*
* @param {string} channelLC
* @private
*/
downloadFfzChannelEmotes_(channelLC) {
// Download FFZ Channel Emotes/Moderator Channel Badge
$.ajax({
context: this,
url: ('https://api.frankerfacez.com/v1/room/' + channelLC),
async: true,
dataType: 'json',
error: function(xhr) {
if (xhr.status === 404) {
// Ignore - No FFZ emotes in this channel
console.log('No FFZ Emotes in Channel: ' + channelLC);
}
},
}).done(function(data) {
this.ffzChannels_[channelLC] = data;
});
}
} |
JavaScript | class FavoritesList {
/**
* @param {BadgeManager} badgeManager
* @param {EmoteManager} emoteManager
* @param {ChatManager} chatManager
* @constructor
*/
constructor(badgeManager, emoteManager, chatManager) {
this.isVisible_ = true;
this.badgeManager_ = badgeManager;
this.emoteManager_ = emoteManager;
this.chatManager_ = chatManager;
$('#addFavFromInput').click(this.addFavToList.bind(this));
$('#newFavInput').keydown(function(event) {
if (event.keyCode === 13) {
$('#addFavFromInput').click();
}
});
document.getElementById('channelListToggle').addEventListener('click', this.toggleFavList);
this.loadFavoritesFromLocalStorage_();
}
/**
* @private
*/
loadFavoritesFromLocalStorage_() {
try {
let channelsArray = JSON.parse(localStorage.getItem('channels'));
if (channelsArray !== null) {
while (channelsArray.length) {
let channels = channelsArray.splice(0, 98);
this.addFavToList(channels);
}
} else {
let channels = [];
localStorage.setItem('channels', JSON.stringify(channels));
}
} catch (err) {
alert('Error: ' + err);
let channels = [];
localStorage.setItem('channels', JSON.stringify(channels));
}
}
/**
* If the favorites list is enabled, disable it.
* If its disabled, enable it.
*/
toggleFavList() {
this.isVisible_ = !this.isVisible_;
if (!this.isVisible_) {
document.getElementById('fav-channel-list').style.display
= 'inline-block';
$('.container').css({'width': 'calc(100% - 250px)'});
document.getElementById('channelListToggle').style.backgroundImage
= 'url(./img/arrow_down.svg)';
} else {
document.getElementById('fav-channel-list').style.display = 'none';
$('.container').css({'width': '100%'});
document.getElementById('channelListToggle').style.backgroundImage
= 'url(./img/arrow_up.svg)';
}
}
/**
* Add a channel to the list of favorites
*
* @param {Array.<string>} channelArray channel name or null
*/
addFavToList(channelArray) {
let channels;
if ($.isArray(channelArray)) {
channels = channelArray;
} else {
channels = document.getElementById('newFavInput').value.replace(/\s+/g, '').split(',');
}
let channelsCount = channels.length;
TwitchApi.getUsers(channels, this, function(data) {
data = data.data;
let notExistingChannelsCount = channelsCount - data._total;
for (let i = 0; i < data.length; i++) {
let channel = data[i].display_name;
let channelId = data[i].id;
let profilePicURL = data[i].profile_image_url;
// ToDo: Check if next line is necessary
document.getElementById('newFavInput').placeholder = '';
// noinspection JSPotentiallyInvalidUsageOfClassThis
this.addFavLine_(channel, profilePicURL, channelId);
}
if (notExistingChannelsCount > 0) {
// noinspection JSPotentiallyInvalidUsageOfClassThis
this.showChannelDoesNotExistInfo_(notExistingChannelsCount);
}
});
}
/**
* @param {number} notExistingChannelsCount
* @private
*/
showChannelDoesNotExistInfo_(notExistingChannelsCount) {
document.getElementById('newFavInput').value = '';
$('#newFavInput').queue(function(next) {
let info = (notExistingChannelsCount > 1) ? ' Channels do not exist.' :
' Channel does not exist.';
$(this).attr('placeholder', notExistingChannelsCount + info);
next();
}).delay(5000).queue(function(next) {
$(this).attr('placeholder', '');
next();
});
}
/**
* @param {string} channel channel name
* @param {string} profilePicURL URL to profile image file
* @param {string} channelId channel id
*/
addFavLine_(channel, profilePicURL, channelId) {
let channelLC = channel.toLowerCase();
this.badgeManager_.downloadChannelBadges(channelLC, channelId);
this.emoteManager_.downloadChannelEmotes(channelLC);
if (channel.length > 0
&& $('.favEntry[id$=\'' + channelLC + '\']').length === 0) {
document.getElementById('newFavInput').value = '';
let favList = $('#fav-channel-list');
favList.append('<div class="favEntry" id="' + channelLC
+ '"><img class="profilePic" src="' + ((profilePicURL != null)
? profilePicURL : '/img/defaultProfile.png')
+ '" alt="Pic." /><input class="favEntryAddChatButton" ' +
'id="' + channelLC + '" type="button" value="' + channel
+ '"><input class="favEntryRemoveButton" ' +
'id="' + channelLC + '" type="button" ></div>');
$(document).on('click', '.favEntryAddChatButton[id$=\''
+ channelLC + '\']', this, function(event) {
event.data.chatManager_.addChat(channel, channelId);
});
$(document).on('click', '.favEntryRemoveButton[id$=\'' + channelLC + '\']', this,
function(event) {
$(this).parent().remove();
event.data.removeChannelFromLocalStorage_(channelLC);
});
// ToDo: is it needed to do channelList.sortable() every time when an entry is added?
favList.sortable({
axis: 'y',
animation: 300,
cursor: 'move',
revert: 200,
scroll: true,
containment: 'parent',
});
}
this.storeChannelInLocalStorage_(channelLC);
}
// noinspection JSMethodCanBeStatic
/**
* @param {string} channelName Twitch channel id of the channel that is stored
* @private
*/
storeChannelInLocalStorage_(channelName) {
let channels = JSON.parse(localStorage.getItem('channels'));
let index = channels.indexOf(channelName);
if (index > -1) {
channels.splice(index, 1);
}
channels.push(channelName);
localStorage.setItem('channels', JSON.stringify(channels));
}
// noinspection JSMethodCanBeStatic
/**
* @param {string} channelLC Twitch channel id of the channel that gets deleted
* @private
*/
removeChannelFromLocalStorage_(channelLC) {
let channels = JSON.parse(localStorage.getItem('channels'));
let index = channels.indexOf(channelLC);
if (index > -1) {
channels.splice(index, 1);
}
localStorage.setItem('channels', JSON.stringify(channels));
}
} |
JavaScript | class ChatMessage {
/**
* @param {string} chatName Name of the chat the message is for
* @param {string} content The actual content of the message
* @constructor
*/
constructor(chatName, content) {
this.chatName_ = chatName;
/** @private */
this.timestamp_ = this.getCurrentTimeFormatted_();
/** @private */
this.content_ = content.trim();
/** @private */
}
/**
* @return {string}
*/
getContent() {
return this.content_;
}
/**
* @return {string}
*/
getTimestamp() {
return this.timestamp_;
}
/**
* @return {string}
*/
getChatName() {
return this.chatName_;
}
// noinspection JSMethodCanBeStatic
/**
* Returns the current time in 24h format
* @return {string} time in format HH:MM
* @private
*/
getCurrentTimeFormatted_() {
let currentDate = new Date();
let time;
if (currentDate.getHours() >= 10 && currentDate.getMinutes() >= 10) {
time = currentDate.getHours() + ':' + currentDate.getMinutes();
} else if (currentDate.getHours() < 10 && currentDate.getMinutes() >= 10) {
time = '0' + currentDate.getHours() + ':' + currentDate.getMinutes();
} else if (currentDate.getHours() >= 10 && currentDate.getMinutes() < 10) {
time = currentDate.getHours() + ':0' + currentDate.getMinutes();
} else {
time = '0' + currentDate.getHours() + ':0' + currentDate.getMinutes();
}
return time;
}
/**
* @return {string} HTML Code
*/
getHtml() {
return '<li style="border-top: 1px solid #673ab7;' +
'border-bottom: 1px solid #673ab7;padding-top: 3px; ' +
'padding-bottom: 3px;"><span style="color: gray;' +
'font-size: 11px;">' + this.timestamp_ + '</span> ' +
this.content_
+ '</li>';
}
} |
JavaScript | class RoomStateMessage extends ChatMessage {
/**
* @param {string} chatName Name of the chat the message is for
* @param {string} content The actual content of the message
* @constructor
*/
constructor(chatName, content) {
super(chatName, content);
}
/**
* @return {string} HTML Code
*/
getHtml() {
return '<p style="color: gray; font-size: 11px;' +
'padding-left: 10px;font-weight: 200;">' + this.getContent() + '</p>';
}
} |
JavaScript | class Chat {
/**
* Adds the chat column for channelName to the app
*
* @param {string} channelName Name of the channel
* @param {string} channelId
* @param {EmoteManager} emoteManager
* @param {ReceiveIRCConnection} receiveIrcConnection
* @param {SendIRCConnection} sendIrcConnection
* @param {MessageParser} messageParser
*/
constructor(channelName, channelId, emoteManager, receiveIrcConnection, sendIrcConnection,
messageParser) {
/** @private */
this.channelName_ = channelName;
/** @private */
this.channelId_ = channelId;
/** @private */
this.channelNameLC_ = channelName.toLowerCase();
/** @private */
this.emoteManager_ = emoteManager;
/** @private */
this.receiveIrcConnection_ = receiveIrcConnection;
/** @private */
this.sendIrcConnection_ = sendIrcConnection;
/** @private */
this.messageParser_ = messageParser;
/** @private */
this.messageCount_ = 0;
/** @private */
this.containerCount_ = 0;
/** @private
* @const */
this.MESSAGE_LIMIT_ = 200000;
/** @private
* @const */
this.MESSAGES_IN_CONTAINER_ = 100;
this.loadRecentMessages_();
}
/**
* @param {Object.<ChatMessage>} chatMessage
*/
addMessage(chatMessage) {
if (chatMessage instanceof RoomStateMessage) {
let chatInput = $('.chatInput#' + chatMessage.getChatName().toLowerCase());
chatInput.append(chatMessage.getHtml());
} else {
let chatMessageList = $('#' + this.channelName_.toLowerCase() + 'contentArea');
if (chatMessageList.children('div').length === 0 ||
(chatMessageList.children('div').length !== 0 &&
chatMessageList.children('div:last')
.children('li').length >= this.MESSAGES_IN_CONTAINER_)) {
chatMessageList.append('<div></div>');
this.containerCount_++;
}
chatMessageList.children('div:last').append(chatMessage.getHtml());
this.messageCount_++;
this.limitMessages_();
this.hideNotVisibleMessages();
this.correctScrollPosition_();
}
}
/**
* Downloads recent chat messages and adds them to the chat
* @private
*/
loadRecentMessages_() {
TwitchApi.getRecentMessages(this.channelName_, this, function(data) {
if (typeof data === 'object' && data !== null && data.hasOwnProperty('messages')) {
let recentMessages = data.messages;
for (let j = 0; j < recentMessages.length; j++) {
let chatMessages = this.messageParser_.parseMessage(recentMessages[j]);
for (let i = 0; i < chatMessages.length; i++) {
// noinspection JSPotentiallyInvalidUsageOfClassThis
this.addMessage(chatMessages[i]);
}
}
} else {
console.log('Recent messages could not be loaded for channel '
+ this.channelName_ + '!');
}
});
}
/**
* Checks whether there are more than this.MESSAGE_LIMIT_ messages in chat.
* If yes than remove the first div with messages
* @private
*/
limitMessages_() {
if (this.messageCount_ >= this.MESSAGE_LIMIT_) {
$('#' + this.channelName_ + ' .chatContent .chatMessageList div:first').remove();
// noinspection JSUnusedGlobalSymbols
this.messageCount_ -= this.MESSAGES_IN_CONTAINER_;
this.containerCount_--;
}
}
/**
* When chat is scrolled to bottom, this hides all message containers except the last 3
*/
hideNotVisibleMessages() {
// Hide all divs with 100 messages each which are not the last 3 to improve performance
if (this.containerCount_ > 3 && this.isScrolledToBottom()) {
let chatMessageList = $('#' + this.channelName_ + 'contentArea');
chatMessageList.children('div:visible').slice(0, -3).hide();
}
}
/**
* Checks if the Chat is scrolled to the bottom
* @return {boolean} True if on bottom, false if not
*/
isScrolledToBottom() {
let bottom = false;
let chatContent = $('#' + this.channelNameLC_ + 'scrollArea');
if (chatContent[0].scrollHeight - chatContent.scrollTop()
< chatContent.outerHeight() + 50) bottom = true;
return bottom;
}
/**
* @private
*/
correctScrollPosition_() {
// Scroll to bottom
let bottom = this.isScrolledToBottom();
let chatContent = $('#' + this.channelNameLC_ + 'scrollArea');
if (bottom) {
let contentHeight = chatContent[0].scrollHeight;
chatContent.scrollTop(contentHeight + 50);
// chatContent.stop(true, false).delay(50)
// .animate({ scrollTop: contentHeight }, 2000, 'linear');
$('#' + this.channelNameLC_ + ' .chatContent .chatMessageList')
.find('p:last').imagesLoaded(function() {
setTimeout(function() {
contentHeight = chatContent[0].scrollHeight;
chatContent.scrollTop(contentHeight + 50);
// chatContent.stop(true, false).delay(50)
// .animate({ scrollTop: contentHeight }, 2000, 'linear');
// alert("wub");
}, 50);
});
} else if (!bottom
&& $('#' + this.channelNameLC_ + ' .chatNewMessagesInfo').is(':hidden')) {
let contentHeight = chatContent[0].scrollHeight;
chatContent.scrollTop(contentHeight + 50);
// chatContent.stop(true, false).delay(50)
// .animate({ scrollTop: contentHeight }, 2000, 'linear');
}
}
/**
* @return {string} HTML Code for the chat
*/
getHtml() {
let channelLC = this.channelName_.toLowerCase();
return `<div class="chat" id="${channelLC}">
<div class="chatHeader">
<button class="toggleViewerList" id="${channelLC}"></button>
<span>${this.channelName_}</span>
<button class="removeChat" id="${channelLC}"></button>
<button class="toggleStream" id="${channelLC}"></button>
</div>
<div class="chatContent" id="${channelLC}scrollArea">
<div class="chatMessageList" id="${channelLC}contentArea"></div>
</div>
<div class="chatInput" id="${channelLC}">
<div class="chatNewMessagesInfo" id="${channelLC}">More messages below.</div>
<img class="kappa" src="/img/Kappa.png" alt="E"/><textarea maxlength="500"
class="chatInputField"
id="${channelLC}"
placeholder="Send a message..."></textarea>
<div class="emoteMenu"><div class="emotes">
<div class="bttvEmotes" style="width: 100%;"><h3>BTTV Emotes</h3></div>
<div class="bttvChannelEmotes" style="width: 100%;"><h3>BTTV Channel Emotes</h3>
</div>
<div class="ffzEmotes" style="width: 100%;"><h3>FFZ Emotes</h3></div>
<div class="ffzChannelEmotes" style="width: 100%;"><h3>FFZ Channel Emotes</h3></div>
</div>
</div>
</div>
<div class="chatViewerList" id="${channelLC}"></div>
</div>`;
}
/**
* Adds all abilities to the Chat (Button actions etc.)
*/
addAbilities() {
this.addEmotesToEmoteMenu_();
this.addEmoteMenuImgClickAbility_();
this.addEmoteMenuGroupClickAbility_();
this.addEmoteMenuToggleAbility_();
this.addEmoteMenuDraggableAbility_();
this.addEmoteMenuResizableAbility_();
this.addStreamIframeAbility_();
this.addResizeAbility_();
this.addChatterListAbility_();
this.addSendMessagesAbility_();
this.addNewMessageInfoAbility_();
}
/**
* @private
*/
addEmotesToEmoteMenu_() {
let channelLC = this.channelName_.toLowerCase();
let userEmotes = this.emoteManager_.getUserEmotes();
// Twitch Global/Channel
for (let j in userEmotes) {
if ({}.hasOwnProperty.call(userEmotes, j)) {
let emoteSet = userEmotes[j];
$('.chatInput[id$=\'' + channelLC + '\'] .emoteMenu .emotes')
.prepend('<div class="' + j + '" style="width: 100%;">' +
'<h3>' + j + '</h3></div>');
for (let k in emoteSet) {
if ({}.hasOwnProperty.call(emoteSet, k)) {
$('.chatInput[id$=\'' + channelLC
+ '\'] .emoteMenu .emotes .' + j)
.append('<img ' +
'src=\'https://static-cdn.jtvnw.net/emoticons/v1/'
+ emoteSet[k].id + '/1.0\' alt=\''
+ emoteSet[k].code + '\' />');
}
}
}
}
// BTTV Global
let bttvGlobal = this.emoteManager_.getBttvGlobal();
for (let i = 0; i < bttvGlobal.length; i++) {
if (bttvGlobal[i].channel == null) {
$('.chatInput[id$=\'' + channelLC + '\'] .emoteMenu .bttvEmotes')
.append('<img src="https://cdn.betterttv.net/emote/'
+ bttvGlobal[i].id + '/1x" alt="' + bttvGlobal[i].code
+ '" />');
}
}
// FFZ Global
let ffzGlobal = this.emoteManager_.getFfzGlobal();
for (let j = 0; j < ffzGlobal.default_sets.length; j++) {
let emoteSetGlobal = ffzGlobal.default_sets[j];
let emotesInSetGlobal = ffzGlobal['sets'][emoteSetGlobal]['emoticons'];
for (let k = 0; k < emotesInSetGlobal.length; k++) {
// let ffzEmoteName = JSON.stringify(emotesInSetGlobal[k].name);
$('.chatInput[id$=\'' + channelLC + '\'] .emoteMenu .ffzEmotes')
.append('<img src=\'https:' +
emotesInSetGlobal[k]['urls']['1'] + '\' ' +
'alt=\'' + emotesInSetGlobal[k].name + '\' />');
}
}
// BTTV Channel
let bttvChannels = this.emoteManager_.getBttvChannels();
if (bttvChannels.hasOwnProperty(channelLC)) {
for (let j = 0; j < bttvChannels[channelLC].length; j++) {
/* let bttvChannelEmote =
JSON.stringify(bttvChannels[channelLC][j].code);*/
let emoteId = JSON.stringify(bttvChannels[channelLC][j].id)
.substring(1,
JSON.stringify(bttvChannels[channelLC][j].id).length - 1);
$('.chatInput[id$=\'' + channelLC
+ '\'] .emoteMenu .bttvChannelEmotes')
.append('<img src=\'https://cdn.betterttv.net/emote/' +
emoteId +
'/1x\' alt=\'' + bttvChannels[channelLC][j].code + '\' />');
}
}
// FFZ Channel
let ffzChannels = this.emoteManager_.getFfzChannels();
if (ffzChannels.hasOwnProperty(channelLC)) {
let ffzChannelId = ffzChannels[channelLC]['room']['_id'];
if (ffzChannels[channelLC]['sets'][ffzChannelId] != null) {
let ffzChannelEmoteSet =
ffzChannels[channelLC]['sets'][ffzChannelId]['emoticons'];
for (let j = 0; j < ffzChannelEmoteSet.length; j++) {
/* let ffzChannelEmote =
JSON.stringify(ffzChannelEmoteSet[j].name);*/
$('.chatInput[id$=\'' + channelLC
+ '\'] .emoteMenu .ffzChannelEmotes')
.append('<img src=\'https:' +
ffzChannelEmoteSet[j]['urls']['1'] + '\' ' +
'alt=\'' + ffzChannelEmoteSet[j].name + '\' />');
}
}
}
}
/**
* @private
*/
addEmoteMenuImgClickAbility_() {
let channelLC = this.channelName_.toLowerCase();
$('.chatInput[id$=\'' + channelLC + '\'] .emoteMenu img').click(function() {
let emoteName = $(this).attr('alt');
let inputField = $('.chatInputField[id$=\'' + channelLC + '\']');
let curValue = inputField.val();
let newValue;
if (!curValue.endsWith(' ') && curValue.length > 0) {
newValue = curValue + ' ' + emoteName + ' ';
} else {
newValue = curValue + emoteName + ' ';
}
inputField.val(newValue);
});
}
/**
* @private
*/
addEmoteMenuGroupClickAbility_() {
let channelLC = this.channelName_.toLowerCase();
$('.chatInput[id$=\'' + channelLC + '\'] .emoteMenu .emotes h3')
.click(/* @this HTMLElement */function() {
if ($(this).parent().css('height') === '18px') {
$(this).parent().css({'height': ''});
} else {
$(this).parent().css({'height': '18px'});
}
});
}
/**
* @private
*/
addEmoteMenuToggleAbility_() {
let channelLC = this.channelName_.toLowerCase();
let $emoteMenu = $('.chatInput[id$=\'' + channelLC + '\'] .emoteMenu');
$('.chatInput[id$=\'' + channelLC + '\'] .kappa').click(function() {
if ($emoteMenu.is(':hidden')) {
$('.chatInput[id$=\'' + channelLC + '\'] .emoteMenu').show();
} else {
$emoteMenu.hide();
$emoteMenu.css({
'top': '',
'left': '',
'right': '',
'bottom': '',
});
}
});
}
/**
* @private
*/
addEmoteMenuDraggableAbility_() {
let channelLC = this.channelName_.toLowerCase();
let $emoteMenu = $('.chatInput[id$=\'' + channelLC + '\'] .emoteMenu');
let chatArea = $('#main-chat-area');
$emoteMenu.draggable({
containment: chatArea,
});
}
/**
* @private
*/
addEmoteMenuResizableAbility_() {
let channelLC = this.channelName_.toLowerCase();
let $emoteMenu = $('.chatInput[id$=\'' + channelLC + '\'] .emoteMenu');
$emoteMenu.resizable({
handles: 'n, ne, e',
minHeight: 200,
minWidth: 200,
});
}
/**
* @private
*/
addStreamIframeAbility_() {
let channelLC = this.channelName_.toLowerCase();
$(document).on('click', '.toggleStream[id$=\'' + channelLC + '\']',
/* @this HTMLElement */function() {
if ($(this).parent().parent().find('.chatStream').length) {
$(this).parent().parent().find('.chatStream').remove();
$(this).parent().parent().find('.chatContent')
.css({'height': 'calc(100% - 105px)'});
$(this).parent().parent().find('.chatViewerList')
.css({'height': 'calc(100% - 35px)'});
} else {
$(this).parent().parent().prepend(
'<div class="chatStream" id="' + channelLC + '">' +
'<div class="chatStreamInner">' +
'<iframe src="https://player.twitch.tv/?channel=' + channelLC
+ '" frameborder="0" allowfullscreen="true"' +
' scrolling="no" height="100%" width="100%"></iframe>' +
'</div></div>');
$(this).parent().parent().find('.chatContent')
.css({
'height': 'calc(100% - 105px - ' +
$(this).parent().parent()
.find('.chatStream').outerHeight() + 'px )',
});
$(this).parent().parent().find('.chatViewerList')
.css({
'height': 'calc(100% - 35px - ' +
$(this).parent().parent()
.find('.chatStream').outerHeight() + 'px )',
});
}
});
}
/**
* @private
*/
addResizeAbility_() {
let channelLC = this.channelName_.toLowerCase();
$(document).on('resize', '.chat[id$=\'' + channelLC + '\']', function() {
$(this).find('.chatContent')
.css({
'height': 'calc(100% - 105px - ' + $(this)
.find('.chatStream').outerHeight() + 'px )',
});
$(this).find('.chatViewerList')
.css({
'height': 'calc(100% - 35px - ' + $(this)
.find('.chatStream').outerHeight() + 'px )',
});
});
$('.chat[id$=\'' + channelLC + '\']').resizable({
handles: 'e',
start: function() {
$('iframe').css('pointer-events', 'none');
},
stop: function() {
$('iframe').css('pointer-events', 'auto');
},
});
let contentHeightOld =
$('.chatContent[id$=\'' + channelLC + 'scrollArea\'] .chatMessageList').height();
$('.chat[id$=\'' + channelLC).resize(function() {
let $newMessagesInfo = $('.chatNewMessagesInfo[id$=\'' + channelLC + '\']');
let $chatContent = $('#' + channelLC + ' .chatContent');
let $chatContentArea = $('.chatContent[id$=\'' + channelLC + 'contentArea\']');
if ($newMessagesInfo.is(':hidden') && contentHeightOld <= $chatContentArea.height()) {
$chatContent.scrollTop($chatContent[0].scrollHeight + 50);
contentHeightOld = $chatContentArea.height();
}
if ($newMessagesInfo.is(':hidden')) {
$chatContent.scrollTop($chatContent[0].scrollHeight + 50);
}
let scroller = $('.chatContent[id$=\'' + channelLC + 'scrollArea\']').baron();
scroller.update();
});
}
/**
* @private
*/
addChatterListAbility_() {
let channelLC = this.channelName_.toLowerCase();
let toggleVL = 0;
$(document).on('click', '.toggleViewerList[id$=\'' + channelLC + '\']', function() {
// if ($(this).parent().parent().find("div.chatViewerList")
// .css("display").toLowerCase() != "none") {
if (toggleVL % 2 !== 0) {
$(this).parent().parent().find('div.chatViewerList').hide();
$(this).parent().parent().find('div.chatContent').show();
$(this).parent().parent().find('div.chatInput').show();
} else {
$(this).parent().parent().find('div.chatContent').hide();
$(this).parent().parent().find('div.chatInput').hide();
$(this).parent().parent().find('div.chatViewerList').show();
let viewerList =
$(this).parent().parent().find('div.chatViewerList');
TwitchApi.getChatterList(channelLC, this, function(data) {
viewerList.empty();
data = data.data;
viewerList.append('Chatter Count: ' + data.chatter_count +
'<br /><br />');
let chatters = data.chatters;
if (chatters.moderators.length > 0) {
viewerList.append('<h3>Moderators</h3>');
let modList = '<ul>';
for (let i = 0; i < chatters.moderators.length; i++) {
modList += '<li>' + chatters.moderators[i] + '</li>';
}
modList += '</ul><br />';
viewerList.append(modList);
}
if (chatters.staff.length > 0) {
viewerList.append('<h3>Staff</h3>');
let staffList = '<ul>';
for (let i = 0; i < chatters.staff.length; i++) {
staffList += '<li>' + chatters.staff[i] + '</li>';
}
staffList += '</ul><br />';
viewerList.append(staffList);
}
if (chatters.admins.length > 0) {
viewerList.append('<h3>Admins</h3>');
let adminsList = '<ul>';
for (let i = 0; i < chatters.admins.length; i++) {
adminsList += '<li>' + chatters.admins[i] + '</li>';
}
adminsList += '</ul><br />';
viewerList.append(adminsList);
}
if (chatters.global_mods.length > 0) {
viewerList.append('<h3>Global Mods</h3>');
let globalModsList = '<ul>';
for (let i = 0; i < chatters.global_mods.length; i++) {
globalModsList +=
'<li>' + chatters.global_mods[i] + '</li>';
}
globalModsList += '</ul><br />';
viewerList.append(globalModsList);
}
if (chatters.viewers.length > 0) {
viewerList.append('<h3>Viewers</h3>');
let viewersList = '<ul>';
for (let i = 0; i < chatters.viewers.length; i++) {
viewersList += '<li>' + chatters.viewers[i] + '</li>';
}
viewersList += '</ul><br />';
viewerList.append(viewersList);
}
});
}
toggleVL++;
});
}
/**
* @private
*/
addSendMessagesAbility_() {
let channelLC = this.channelName_.toLowerCase();
$('.chatInputField[id$=\'' + channelLC + '\']').keydown(this, function(event) {
if (event.keyCode === 13) {
event.preventDefault();
if ($(this).val().startsWith('.')
|| $(this).val().startsWith('/')) {
event.data.receiveIrcConnection_.send('PRIVMSG #' + channelLC + ' :'
+ $(this).val());
} else {
event.data.sendIrcConnection_.send('PRIVMSG #' + channelLC
+ ' :' + $(this).val());
}
$(this).val('');
} else if (event.keyCode === 9) {
event.preventDefault();
if ($(this).val().length !== 0 && !$(this).val().endsWith(' ')) {
console.log('WUB');
}
}
});
}
/**
* @private
*/
addNewMessageInfoAbility_() {
let channelLC = this.channelName_.toLowerCase();
$('.chatNewMessagesInfo[id$=\'' + channelLC + '\']').click(function() {
$(this).hide();
let $chatContent = $('#' + channelLC + ' .chatContent');
$chatContent.scrollTop($chatContent[0].scrollHeight);
});
$('.chatContent[id$=\'' + channelLC + 'scrollArea\']').scroll(
/* @this HTMLElement */function() {
// Bug workaround: unexpected horizontal scrolling
// despite overflow-x: hidden
if ($(this).scrollLeft() !== 0) {
$(this).scrollLeft(0);
}
// New messages info scroll behavior
if ($(this)[0].scrollHeight - $(this).scrollTop()
< $(this).outerHeight() + 50) {
$('.chatNewMessagesInfo[id$=\'' + channelLC + '\']').hide();
} else {
$('.chatNewMessagesInfo[id$=\'' + channelLC + '\']').show();
}
if ($(this).scrollTop() < 200) {
$('.chatContent[id$=\'' + channelLC
+ 'scrollArea\'] .chatMessageList')
.children('div:hidden:last').show();
}
});
}
} |
JavaScript | class ChatManager {
/**
* Creates the ChatManager
* @param {EmoteManager} emoteManager
* @param {MessageParser} messageParser
*/
constructor(emoteManager, messageParser) {
/**
* @private
* @type {Object.<string, Chat>}
*/
this.chatList_ = {};
this.emoteManager_ = emoteManager;
this.messageParser_ = messageParser;
// Bug workaround: unexpected vertical scrolling
// despite overflow-y: hidden
$('#main-chat-area').scroll(function() {
if ($(this).scrollTop() !== 0) {
$(this).scrollTop(0);
}
});
}
/**
* Setting the IRC Connection for receiving messages.
* @param {ReceiveIRCConnection} receiveIrcConnection
*/
setReceiveIrcConnection(receiveIrcConnection) {
this.receiveIrcConnection_= receiveIrcConnection;
}
/**
* Setting the IRC Connection for sending messages.
* @param {SendIRCConnection} sendIrcConnection
*/
setSendIrcConnection(sendIrcConnection) {
this.sendIrcConnection_ = sendIrcConnection;
}
/**
* Adds the chat messages to the correct chat
* @param {Array.<ChatMessage>} chatMessages
*/
addMessages(chatMessages) {
for (let i = 0; i < chatMessages.length; i++) {
let chatName = chatMessages[i].getChatName().toLowerCase();
this.chatList_[chatName].addMessage(chatMessages[i]);
}
}
/**
* @param {string} channelName
* @return {boolean} true if chat already in the chatList
*/
isChatAlreadyAdded(channelName) {
return this.chatList_.hasOwnProperty(channelName);
}
/**
* Removes the Chat from the chatList_ and the DOM
*
* @param {Object} event
* @private
*/
removeChat_(event) {
let channelName = event.data[1].toLowerCase();
let chatManager = event.data[0];
delete chatManager.chatList_[channelName];
$(document).off('click', '.toggleStream[id$=\'' + channelName + '\']');
$(this).parent().parent().remove();
chatManager.receiveIrcConnection_.leaveChat(channelName);
chatManager.sendIrcConnection_.leaveChat(channelName);
}
/**
* Creates new Chat and adds it to the chatList_ if there is not already
* a chat with this channelName
* @param {string} channelName Name of the channel that will be added
* @param {string} channelId
*/
addChat(channelName, channelId) {
let channelLC = channelName.toLowerCase();
if (!this.isChatAlreadyAdded(channelLC) && this.receiveIrcConnection_.isLoaded() &&
this.sendIrcConnection_.isLoaded()) {
this.chatList_[channelLC] = new Chat(channelName, channelId, this.emoteManager_,
this.receiveIrcConnection_, this.sendIrcConnection_, this.messageParser_);
let chatArea = $('#main-chat-area');
chatArea.append(this.chatList_[channelLC].getHtml());
this.chatList_[channelLC].addAbilities();
this.receiveIrcConnection_.joinChat(channelLC);
this.sendIrcConnection_.joinChat(channelLC);
$(document).on('click', '.removeChat[id$=\'' + channelLC + '\']',
[this, channelName], this.removeChat_);
baron('#' + channelLC + 'scrollArea');
// ToDO: Check if .sortable is needed every time
chatArea.sortable({
handle: '.chatHeader',
start(event, ui) {
ui.placeholder.width(ui.item.width());
ui.placeholder.height(ui.item.height());
},
animation: 300,
cursor: 'move',
revert: 200,
scroll: true,
containment: 'parent',
});
}
}
} |
JavaScript | class UserMessage extends ChatMessage {
/**
* @param {string} chatName Name of the chat the message is for
* @param {string} content The actual content of the message
* @param {array} badges List of badges shown in front of the name
* @param {Array.<string>} emotePositions
* @param {string} chatterName Name of the chatter the message is from
* @param {string} chatterColor The color of the chatters name in hex #xxxxxx
* @param {boolean} action
* @param {EmoteManager} emoteManager
* @param {BadgeManager} badgeManager
* @constructor
*/
constructor(chatName, content, badges, emotePositions, chatterName, chatterColor, action,
emoteManager, badgeManager) {
super(chatName, content);
/** @private */
this.badges_ = badges;
/** @private */
this.emotes_ = emotePositions;
/** @private */
this.chatterName_ = chatterName;
/** @private */
this.chatterColor_ = chatterColor;
/** @private */
this.action_ = action;
/** @private */
this.emoteManager_ = emoteManager;
/** @private */
this.badgeManager_ = badgeManager;
}
/**
* @return {string} HTML code
*/
getHtml() {
let html = this.replaceTwitchEmotesAndEscapeHtml(this.getContent());
html = UserMessage.matchURL_(html);
html = this.replaceBttvEmotes(html);
html = this.replaceFfzEmotes(html);
html = this.replaceBadges(html);
return html;
}
/**
* Replace Twitch emote texts with img html tag
* and simultaneously escape the HTML chars in the msg
* @param {string} userMessage
* @return {string}
*/
replaceTwitchEmotesAndEscapeHtml(userMessage) {
// Replace emote texts with images
if (this.emotes_[0] !== '' && this.emotes_[0] != null) {
let sortEmotes = [];
for (let j = 0; j < this.emotes_.length; j++) {
let emote = this.emotes_[j].split(':');
let emoteId = emote[0];
let positions = emote[1].split(',');
for (let k = 0; k < positions.length; k++) {
sortEmotes.push(
[positions[k].split('-')[0],
positions[k].split('-')[1], emoteId]);
}
}
for (let k = 0; k < sortEmotes.length - 1; k++) {
for (let l = k + 1; l < sortEmotes.length; l++) {
if (parseInt(sortEmotes[k][0])
> parseInt(sortEmotes[l][0])) {
let zs = sortEmotes[k];
sortEmotes[k] = sortEmotes[l];
sortEmotes[l] = zs;
}
}
}
let diff = 0;
let oldAfterEmotePos = 0;
for (let k = 0; k < sortEmotes.length; k++) {
let oldMessage = userMessage;
let imgString = userMessage.substring(0, oldAfterEmotePos)
+ UserMessage.escapeString_(userMessage.substring(oldAfterEmotePos,
parseInt(sortEmotes[k][0]) + diff)) +
'<span style=" display: inline-block;" >​' +
'<img src="https://static-cdn.jtvnw.net/emoticons/v1/'
+ sortEmotes[k][2] + '/1.0" alt="{Emote}" /></span>';
userMessage = imgString +
userMessage.substring(parseInt(sortEmotes[k][1])
+ 1 + diff, userMessage.length);
oldAfterEmotePos = imgString.length;
// alert(oldAfterEmotePos);
// alert(userMessage);
diff += userMessage.length - oldMessage.length;
}
} else {
userMessage = UserMessage.escapeString_(userMessage);
}
return userMessage;
}
/**
* Replaces Bttv emote texts with img html tag
* @param {string} userMessage
* @return {string}
*/
replaceBttvEmotes(userMessage) {
// Replace BTTV Global Emotes with img
let bttvGlobal = this.emoteManager_.getBttvGlobal();
for (let j = 0; j < bttvGlobal.length; j++) {
if (bttvGlobal[j].channel == null) {
let find = JSON.stringify(bttvGlobal[j].code);
find = find.substring(1, find.length - 1);
find = '(^|\\b|\\s)' +
find.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&') + '(?=\\s|$)';
let re = new RegExp(find, 'g');
let emoteId = JSON.stringify(bttvGlobal[j].id)
.substring(1, JSON.stringify(bttvGlobal[j].id).length - 1);
userMessage = userMessage.replace(re,
' <span style=" display: inline-block;" >​' +
'<img src=\'https://cdn.betterttv.net/emote/' + emoteId +
'/1x\' alt=\'' + bttvGlobal[j].code + '\' /></span> ');
}
}
// Replace BTTV Channel Emotes with img
let bttvChannels = this.emoteManager_.getBttvChannels();
if (bttvChannels.hasOwnProperty(this.chatName_)) {
for (let j = 0; j < bttvChannels[this.chatName_].length; j++) {
let find = JSON.stringify(bttvChannels[this.chatName_][j].code);
find = find.substring(1, find.length - 1);
find = '(^|\\b|\\s)' + find.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&') + '(?=\\s|$)';
let re = new RegExp(find, 'g');
let emoteId =
JSON.stringify(bttvChannels[this.chatName_][j].id)
.substring(1,
JSON.stringify(
bttvChannels[this.chatName_][j].id).length - 1);
userMessage = userMessage.replace(re,
' <span style=" display: inline-block;" >​' +
'<img src=\'https://cdn.betterttv.net/emote/' +
emoteId +
'/1x\' alt=\'' +
bttvChannels[this.chatName_][j].code + '\' />' +
'</span> ');
}
}
return userMessage;
}
/**
* Replaces Ffz emote texts with img html tag
* @param {string} userMessage
* @return {string}
*/
replaceFfzEmotes(userMessage) {
// Replace FFZ Global Emotes with img
let ffzGlobal = this.emoteManager_.getFfzGlobal();
for (let j = 0; j < ffzGlobal.default_sets.length; j++) {
let emoteSetGlobal = ffzGlobal.default_sets[j];
let emotesInSetGlobal =
ffzGlobal['sets'][emoteSetGlobal]['emoticons'];
for (let k = 0; k < emotesInSetGlobal.length; k++) {
let find = JSON.stringify(emotesInSetGlobal[k].name);
find = find.substring(1, find.length - 1);
find = '(^|\\b|\\s)'
+ find.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
+ '(?=\\s|$)';
let re = new RegExp(find, 'g');
userMessage = userMessage.replace(re,
' <span style=" display: inline-block;" >​' +
'<img src=\'https:' + emotesInSetGlobal[k]['urls']['1']
+ '\' alt=\'' + emotesInSetGlobal[k].name + '\' />' +
'</span> ');
}
}
// Replace FFZ Channel Emotes with img
let ffzChannels = this.emoteManager_.getFfzChannels();
if (ffzChannels.hasOwnProperty(this.chatName_)) {
let ffzChannelId = ffzChannels[this.chatName_]['room']['_id'];
if (ffzChannels[this.chatName_]['sets'][ffzChannelId] != null) {
let ffzChannelEmoteSet =
ffzChannels[this.chatName_]['sets'][ffzChannelId]['emoticons'];
for (let j = 0; j < ffzChannelEmoteSet.length; j++) {
let find = JSON.stringify(ffzChannelEmoteSet[j].name);
find = find.substring(1, find.length - 1);
find = '(^|\\b|\\s)'
+ find.replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
+ '(?=\\s|$)';
let re = new RegExp(find, 'g');
userMessage = userMessage.replace(re,
' <span style=" display: inline-block;" >​' +
'<img src=\'https:' + ffzChannelEmoteSet[j]['urls']['1']
+ '\' alt=\'' + ffzChannelEmoteSet[j].name + '\' />' +
'</span> ');
}
}
}
return userMessage;
}
/**
* Puts badges img tags in the message
* @param {string} userMessage
* @return {string}
*/
replaceBadges(userMessage) {
let newElement;
if (this.action_) {
newElement = $('<li><span style="color: gray;font-size: 11px;">'
+ this.getTimestamp() + '</span><span style="color: ' + this.chatterColor_
+ ';font-weight: bold;"> ' + this.chatterName_ + '</span>' +
' <span style="color: ' + this.chatterColor_ + ';">'
+ userMessage + '</span></li>');
} else {
newElement = $('<li><span style="color: gray;font-size: 11px;">'
+ this.getTimestamp() + '</span><span style="color: ' + this.chatterColor_
+ ';font-weight: bold;"> ' + this.chatterName_ + '</span>: '
+ userMessage + '</li>');
}
// Put badges in message
for (let j = 0; j < this.badges_.length; j++) {
let badge = this.badges_[j].split('/');
let badgeGroup = this.badgeManager_.getBadgesChannels()[this.chatName_][badge[0]];
if (badge[0].localeCompare('subscriber') === 0) {
newElement.find('span:nth-of-type(2):first').before(
'<div style=" display: inline-block;' +
'vertical-align: -32%;border-radius: 2px;' +
'background-image: url(' +
badgeGroup['versions'][badge[1]]['image_url_1x']
+ ');" ></div>');
} else {
newElement.find('span:nth-of-type(2):first').before(
'<div style=" display: inline-block;' +
'vertical-align: -32%;border-radius: 2px;' +
'background-image: url(' +
this.badgeManager_
.getBadgesGlobal()[badge[0]]['versions'][badge[1]]['image_url_1x']
+ ');"></div>');
}
}
return newElement;
}
/**
* Searches for URLs in the given String and replaces them with the
* proper <a href=""> HTML Tag
* @param {string} txt - Text in which the links get searched
* @return {string} Text with <a href=""> HTML Tags
* @private
*/
static matchURL_(txt) {
let pattern =
/((^|\s| )(http(s)?:\/\/.)?(www\.)?([-a-zA-Z0-9@:%_+~#=]|\.(?!\.)){2,256}\.[a-z]{2,8}\b([-a-zA-Z0-9@:%_+.~#?&/=]*))(?=(\s|$| ))/g;
txt = txt.replace(pattern, function(str, p1) {
let addScheme = p1.indexOf('http://') === -1
&& p1.indexOf('https://') === -1;
let link = ' <a href="'
+ (addScheme ? 'http://' : '')
+ p1 + '" target="_blank">' + p1 + '</a>';
if (p1.startsWith(' ')) {
link = ' <a href="'
+ (addScheme ? 'http://' : '') +
p1.substring(1, p1.length) + '" target="_blank">' + p1 + '</a>';
} else if (p1.startsWith(' ')) {
link = ' <a href="'
+ (addScheme ? 'http://' : '') +
p1.substring(5, p1.length) + '" target="_blank">' + p1 + '</a>';
}
return link;
});
return txt;
}
/**
* Escape HTML characters in the message before adding to the chat
* @param {string} txt message to escape
* @return {string} escaped message
* @private
*/
static escapeString_(txt) {
return txt.replace(/&/g, '&').replace(/</g, '<')
.replace(/>/g, '>').replace(/"/g, '"')
.replace(/`/g, '`').replace(/!/g, '!')
.replace(/@/g, '@').replace(/\$/g, '$')
.replace(/%/g, '%').replace(/=/g, '=')
.replace(/\+/g, '+').replace(/{/g, '{')
.replace(/}/g, '}').replace(/\[/g, '[')
.replace(/]/g, ']');
}
} |
JavaScript | class MessageParser {
/**
* @param {EmoteManager} emoteManager
* @param {BadgeManager} badgeManager
* @constructor
*/
constructor(emoteManager, badgeManager) {
/** @private */
this.emoteManager_ = emoteManager;
/** @private */
this.badgeManager_ = badgeManager;
}
/**
* Parses an IRC message from Twitch and appends it to the corresponding chat.
*
* @param {string} msg Single raw chat message sent by Twitch
* @return {Array.<ChatMessage>} Array of ChatMessage and UserMessage
*/
parseMessage(msg) {
let msgParts = msg.split(' ');
//console.log(msg);
let chatName = MessageParser.parseChatName_(msgParts);
if (msgParts[2].localeCompare('WHISPER') === 0) {
// ToDo: Implement whisper
return [];
} else if (msgParts[2].startsWith('GLOBALUSERSTATE')) {
return [];
} else if (chatName.length < 1) {
// console.log('Message with no Chat specified: ' + msg);
return [];
}
/** @type {Array.<ChatMessage>} */
let chatMessages = [];
if (msgParts[1].localeCompare('JOIN') === 0) ; else if (msgParts[1].localeCompare('PART') === 0) ; else if (msgParts[1].localeCompare('353') === 0) ; else if (msgParts[1].localeCompare('366') === 0) ; else if (msgParts[1].localeCompare('MODE') === 0) ; else if (msgParts[2].localeCompare('ROOMSTATE') === 0) {
chatMessages = MessageParser.parseRoomState_(msg, chatName);
} else if (msgParts[2].localeCompare('USERSTATE') === 0) ; else if (msgParts[2].localeCompare('USERNOTICE') === 0) {
chatMessages = this.parseUserNotice_(msg, chatName);
} else if (msgParts[2].localeCompare('CLEARCHAT') === 0) ; else if (msgParts[1].localeCompare('HOSTTARGET') === 0) ; else if (msgParts[2].localeCompare('NOTICE') === 0
|| msgParts[1].localeCompare('PRIVMSG') === 0) {
chatMessages = MessageParser.parseNotice_(msgParts, chatName);
} else if (msgParts[2].localeCompare('PRIVMSG') === 0) {
chatMessages = this.parsePrivmsg_(msgParts, chatName);
} else if (chatName.length >= 1) {
chatMessages = [new ChatMessage(chatName, msg)];
} else {
alert('Error');
}
return chatMessages;
}
/**
* @param {Array} msgParts
* @param {string} chatName channel the ROOMSTATE belongs to
* @return {Array.<ChatMessage>} newMessages
*/
parsePrivmsg_(msgParts, chatName) {
let username = msgParts[1].split('!', 1);
username = username[0].substring(1, username[0].length);
let metaInfoRaw = msgParts[0].substring(1, msgParts[0].length);
let metaInfo = MessageParser.getMetaInfoWithColor_(metaInfoRaw.split(';'), username);
if (metaInfo.username != null) {
username = metaInfo.username;
}
let userMessage = msgParts.slice(4).join(' ');
userMessage = userMessage.substring(1, userMessage.length);
let action = false;
if (userMessage.startsWith('\x01ACTION')) {
action = true;
userMessage = userMessage.substring(8, userMessage.length - 2);
}
let messageContent = userMessage;
let emotePositions = metaInfo.emotes;
let badges = metaInfo.badges;
let color = metaInfo.color;
return [
new UserMessage(chatName, messageContent, badges,
emotePositions, username, color, action, this.emoteManager_, this.badgeManager_),
];
}
/**
* @param {string} msg ROOMSTATE message
* @param {string} chatName channel the ROOMSTATE belongs to
* @return {Array.<ChatMessage>} newMessages
* @private
*/
static parseRoomState_(msg, chatName) {
let roomStateMsg = msg.split(' ')[0];
roomStateMsg = roomStateMsg.substring(1, roomStateMsg.length);
let roomStates = roomStateMsg.split(';');
let infoMessage = '';
let chatInput = $('#' + chatName + ' .chatInput');
chatInput.find('p').remove();
for (let j = 0; j < roomStates.length; j++) {
let info = roomStates[j].split('=');
let infoKeyword = info[0];
switch (infoKeyword) {
case 'broadcaster-lang':
infoMessage += info[1] + ' ';
break;
case 'emote-only':
if (info[1].localeCompare('1') === 0) {
infoMessage += 'EMOTE-ONLY ';
}
break;
case 'followers-only':
if (info[1].localeCompare('-1') !== 0) {
infoMessage += 'FOLLOW ' + info[1] + 'm ';
}
break;
case 'r9k':
if (info[1].localeCompare('1') === 0) {
infoMessage += 'R9K ';
}
break;
case 'slow':
if (info[1].localeCompare('0') !== 0) {
infoMessage += 'SLOW ' + info[1] + 's ';
}
break;
case 'subs-only':
if (info[1].localeCompare('1') === 0) {
infoMessage += 'SUB ';
}
break;
}
}
return [new RoomStateMessage(chatName, infoMessage)];
}
/**
* @param {string} msg USERNOTICE message
* @param {string} chatName channel the ROOMSTATE belongs to
* @return {Array.<ChatMessage>} newMessages
* @private
*/
parseUserNotice_(msg, chatName) {
let userNoticeMessageParts = msg.split(' ');
let userNoticeMessage = userNoticeMessageParts.slice(4).join(' ');
let metaInfoRaw = msg.substring(1, msg.length).split(' ')[0].split(';');
let metaInfo = MessageParser.getMetaInfo_(metaInfoRaw);
let chatMessages = [];
chatMessages.push(new ChatMessage(chatName,
((metaInfo.systemMsg != null) ? (metaInfo.systemMsg + ' ') : '')));
if (userNoticeMessage.length > 0) {
chatMessages.push(this.parseMessage(msg.split(' ')[0] + ' :' +
metaInfo.username.toLowerCase() + '!' +
metaInfo.username.toLowerCase() + '@' +
metaInfo.username.toLowerCase() + '.tmi.twitch.tv PRIVMSG #'
+ chatName + ' ' + userNoticeMessage)[0]);
}
return chatMessages;
}
/**
* @param {Array.<string>} msgParts
* @param {string} chatName channel the ROOMSTATE belongs to
* @return {Array.<ChatMessage>} newMessages
* @private
*/
static parseNotice_(msgParts, chatName) {
let slicePoint = msgParts[2].localeCompare('NOTICE') === 0 ? 4 : 3;
let noticeMessage = msgParts.slice(slicePoint).join(' ');
return [new ChatMessage(chatName, noticeMessage.substring(1, noticeMessage.length))];
}
/**
* @param {Array.<string>} msgParts
* @return {string} chatName the message belongs to
* @private
*/
static parseChatName_(msgParts) {
let chatName = '';
// Parse chat channel name the message is for
for (let j = 0; j < msgParts.length; j++) {
if (msgParts[j].startsWith('#')) {
chatName = msgParts[j].slice(1, msgParts[j].length);
chatName = chatName.trim();
break;
}
}
return chatName;
}
/**
* Parses the meta information part of a chat message.
*
* @param {string[]} metaMsg [{@badges=<badges>},{color=<color>},...]
* @param {string} username user from whom the message was sent
* @return {Object} Object with one property for every meta information
* @private
*/
static getMetaInfoWithColor_(metaMsg, username) {
let metaInfo = {};
metaInfo.color = '#acacbf';
metaInfo.emotes = '';
metaInfo.badges = '';
let gotColor = false;
for (let j = 0; j < metaMsg.length; j++) {
let info = metaMsg[j].split('=');
if (info.length <= 1 || info[1].localeCompare('') === 0) {
continue;
}
if (info[0].localeCompare('color') === 0) {
metaInfo.color = info[1];
if (metaInfo.color.localeCompare('') === 0
&& !(NameColorManager.getUserColors().hasOwnProperty(username))) {
metaInfo.color = NameColorManager.randomColor();
NameColorManager.addUserColor(username, metaInfo.color);
} else if (metaInfo.color.localeCompare('') === 0
&& NameColorManager.getUserColors().hasOwnProperty(username)) {
metaInfo.color = NameColorManager.getUserColors()[username];
}
gotColor = true;
} else if (info[0].localeCompare('display-name') === 0) {
metaInfo.username = info[1];
} else if (info[0].localeCompare('emotes') === 0) {
metaInfo.emotes = info[1].split('/');
} else if (info[0].localeCompare('badges') === 0) {
metaInfo.badges = info[1].split(',');
} else if (info[0].localeCompare('system-msg') === 0) {
metaInfo.systemMsg = info[1].replace(/\\s/g, ' ');
} else if (info[0].localeCompare('emote-sets') === 0) {
metaInfo.emoteSets = info[1].split(',');
}
}
if (!gotColor) {
if (NameColorManager.getUserColors().hasOwnProperty(username)) {
metaInfo.color = NameColorManager.getUserColors()[username];
} else {
metaInfo.color = NameColorManager.randomColor();
NameColorManager.addUserColor(username, metaInfo.color);
}
}
// Color contrast correction
metaInfo.color = NameColorManager.colorCorrection(metaInfo.color);
return metaInfo;
}
/**
* Parses the meta information part of a chat message.
*
* @param {string[]} metaMsg [{@badges=<badges>},{color=<color>},...]
* @return {Object} Object with one property for every meta information
* @private
*/
static getMetaInfo_(metaMsg) {
let metaInfo = {};
metaInfo.emotes = '';
metaInfo.badges = '';
for (let j = 0; j < metaMsg.length; j++) {
let info = metaMsg[j].split('=');
if (info.length <= 1 || info[1].localeCompare('') === 0) {
continue;
}
if (info[0].localeCompare('display-name') === 0) {
metaInfo.username = info[1];
} else if (info[0].localeCompare('emotes') === 0) {
metaInfo.emotes = info[1].split('/');
} else if (info[0].localeCompare('badges') === 0) {
metaInfo.badges = info[1].split(',');
} else if (info[0].localeCompare('system-msg') === 0) {
metaInfo.systemMsg = info[1].replace(/\\s/g, ' ');
} else if (info[0].localeCompare('emote-sets') === 0) {
metaInfo.emoteSets = info[1].split(',');
}
}
return metaInfo;
}
} |
JavaScript | class App {
/**
* Created the whole application
* @constructor
*/
constructor() {
// noinspection JSIgnoredPromiseFromCall
this.createApp();
}
/**
* Create the app
*/
async createApp() {
document.title += ` ${version}`;
/** @private */
this.appUser_ = new AppUser();
await this.appUser_.requestAppUserData();
/** @private */
this.badgeManager_ = new BadgeManager();
/** @private */
this.emoteManager_ = new EmoteManager(this.appUser_);
/** @private */
this.messageParser_ =
new MessageParser(this.emoteManager_, this.badgeManager_);
/** @private */
this.chatManager_ = new ChatManager(this.emoteManager_, this.messageParser_);
/** @private */
new FavoritesList(this.badgeManager_, this.emoteManager_, this.chatManager_);
/** @private */
this.sendIrcConnection_ = new SendIRCConnection(this.appUser_);
/** @private */
this.receiveIrcConnection_ = new ReceiveIRCConnection(this.appUser_,
this.messageParser_, this.chatManager_);
this.chatManager_.setReceiveIrcConnection(this.receiveIrcConnection_);
this.chatManager_.setSendIrcConnection(this.sendIrcConnection_);
}
} |
JavaScript | class Router {
constructor() {
this.routes = []
}
handle(conditions, handler) {
this.routes.push({
conditions,
handler,
})
return this
}
get(url, handler) {
return this.handle([Get, Path(url)], handler)
}
post(url, handler) {
return this.handle([Post, Path(url)], handler)
}
all(handler) {
return this.handle([], handler)
}
route(req) {
const route = this.resolve(req)
if (route) {
return route.handler(req)
}
// checks whether or not the specified endpoint is reachable or even exists
return new Response("resource not found", {
status: 404,
statusText: 'not found',
headers: {
'content-type': 'text/plain',
},
})
}
resolve(req) {
return this.routes.find(r => {
if (!r.conditions || (Array.isArray(r) && !r.conditions.length)) {
return true
}
if (typeof r.conditions === 'function') {
return r.conditions(req)
}
return r.conditions.every(c => c(req))
})
}
} |
JavaScript | class AttributeRewriter {
constructor(attributeName, attributeValue) {
this.attributeName = attributeName;
this.attributeValue = attributeValue;
}
element(element) {
element.setAttribute(this.attributeName, this.attributeValue);
}
} |
JavaScript | class TextRewriter {
constructor(newText) {
this.newText = newText;
}
element(element) {
element.setInnerContent(this.newText);
}
} |
JavaScript | class addTag {
constructor(tag) {
this.tags = tag
}
element(element) {
// prepend function adds the tag in the element that is specified ('links' in this case)
element.prepend(this.tags, {html:true})
}
} |
JavaScript | class FakeOSEK {
constructor() {
this.scheduler = {
numberOfTasks: 0,
schedulerTime: 0 // active time of scheduler
}
this.promises = [] // Will always be empty
}
// Runs the function immediately
_addAndRunTask(task) {
this.currentTask = task
this.scheduler.numberOfTasks++
task.rtjs = this
task.enqueuedTime = this.getTime()
let ret = task.run()
task.retval = ret
task.endTime = this.getTime()
task.elapsedTime = task.endTime - task.enqueuedTime
// Account for the this time in the global scheduler
this.scheduler.schedulerTime += task.elapsedTime
task.onTerminated()
return ret
}
addTask(task) {
return this._addAndRunTask(task)
}
addTaskFromFn(fn) {
return this._addAndRunTask(this.taskFromFn(fn, name || fn.name, priority || 0))
}
taskFromFn(fn, args, { name, priority, deadline }) {
return {
run: fn.bind(this, args),
name,
priority,
deadline
}
}
spawnTask(task) {
return this._addAndRunTask(task)
}
spawnTaskFromFn(fn, args, config) {
return this._addAndRunTask(this.taskFromFn(fn, args, config))
}
start() { /* This is intentionally left blank */ }
/**
* returns the current relative time, since the start of the webpage / script, in ms
* @returns the current relative time in ms
*/
getTime() {
return Number(typeof window === 'undefined' ? performance.now() : window.performance.now())
}
// Return the execution time of the current task in Miliseconds
getExecutionTime() {
let task = this.currentTask
return Number((this.getTime() - task.enqueuedTime))
}
// Return the execution time of the current task in Miliseconds
getAbsoluteDeadline() {
let task = this.currentTask
return Number(task.creationTime + task.deadline)
}
addAlarm(fn, delay) {
setTimeout(fn, delay)
}
} |
JavaScript | class VuexBrowserStorage {
constructor (config, store) {
this.config = config
this.store = store
this.populateApplicationState()
this.listenForMutations()
}
populateApplicationState () {
const savedState = {}
logDebug('Populate initial state with browser saved data...')
this.state.replaceState(merge(this.store.state, savedState))
}
listenForMutations () {
this.store.subscribe((mutation, state) => {
console.log(mutation)
})
}
} |
JavaScript | class CreateLink extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}
state = {
title: "",
url: "",
category: "",
rate: 0,
isValidated: false
};
validate = () => {
const formLength = this.formEl.length;
if (this.formEl.checkValidity() === false) {
for (let i = 0; i < formLength; i++) {
const elem = this.formEl[i];
const errorLabel = elem.parentNode.querySelector(".invalid-feedback");
if (errorLabel && elem.nodeName.toLowerCase() !== "button") {
if (!elem.validity.valid) {
errorLabel.textContent = elem.validationMessage;
} else {
errorLabel.textContent = "";
}
}
}
return false;
} else {
for (let i = 0; i < formLength; i++) {
const elem = this.formEl[i];
const errorLabel = elem.parentNode.querySelector(".invalid-feedback");
if (errorLabel && elem.nodeName.toLowerCase() !== "button") {
errorLabel.textContent = "";
}
}
return true;
}
};
onSubmit = event => {
event.preventDefault();
if (this.validate()) {
// let titleInput = ReactDOM.findDOMNode(this.refs.title);
// let urlInput = ReactDOM.findDOMNode(this.refs.url);
// let categoryInput = ReactDOM.findDOMNode(this.refs.category);
// let rateInput = ReactDOM.findDOMNode(this.refs.rate);
let newLink = {
title: this.state.title,
url: this.state.url,
category: this.state.category,
rate: this.state.rate
};
if (this.props.item) {
newLink._id = this.props.item._id;
}
this.setState({
title: "",
url: "",
category: "",
rate: 0
});
this.props.addLink(newLink);
}
this.setState({ isValidated: true });
};
componentWillReceiveProps() {
// Fill in the form with the appropriate data
// console.log(this.props.item);
if (this.props.item) {
// TODO: get item detail from server
this.setState({
title: this.props.item.title,
url: this.props.item.url,
category: this.props.item.category,
rate: this.props.item.rate
});
}
}
handleInputChange(e) {
const target = e.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
this.setState({ [name]: value });
}
render() {
const props = [...this.props];
// let title = this.props.item ? this.props.item.title : "";
// let url = this.props.item ? this.props.item.url : "";
// let category = this.props.item ? this.props.item.category : "";
// let rate = this.props.item ? this.props.item.rate : 0;
let classNames = "form-inline";
// if (props.className) {
// classNames = [...props.className];
// delete props.className;
// }
if (this.state.isValidated) {
classNames = classNames + " was-validated";
}
return (
<form
ref={form => (this.formEl = form)}
onSubmit={this.onSubmit}
{...props}
className={classNames}
noValidate
>
<div className="form-group">
<label htmlFor="title" className="control-label">
Title
</label>
<input
type="text"
ref="title"
name="title"
className="form-control"
placeholder="title"
value={this.state.title}
onChange={this.handleInputChange}
required={true}
/>
<div className="invalid-feedback" />
</div>
<div className="form-group">
<label htmlFor="url" className="control-label">
URL
</label>
<input
type="text"
ref="url"
name="url"
className="form-control"
placeholder="url"
value={this.state.url}
onChange={this.handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="category" className="control-label">
Category
</label>
<input
type="text"
ref="category"
name="category"
className="form-control"
placeholder="category"
value={this.state.category}
onChange={this.handleInputChange}
/>
</div>
<div className="form-group">
<label htmlFor="rate" className="control-label">
Rate
</label>
<input
type="number"
ref="rate"
name="rate"
className="form-control"
placeholder="rate"
value={this.state.rate}
onChange={this.handleInputChange}
/>
</div>
<button type="submit" className="btn btn-default">
Submit
</button>
</form>
);
}
} |
JavaScript | class Nav extends Component {
/**
* Upgrades all Nav AUI components.
* @returns {Array} Returns an array of all newly upgraded components.
*/
static upgradeElements() {
let components = [];
Array.from(document.querySelectorAll(SELECTOR_COMPONENT)).forEach(element => {
if (!Component.isElementUpgraded(element)) {
components.push(new Nav(element));
}
});
return components;
};
/**
* Returns modifier `list`
*/
static get MODIFIER_LIST() {
return CLASS_LIST;
}
/**
* Returns modifier `bar`
*/
static get MODIFIER_BAR() {
return CLASS_BAR;
}
/**
* Returns modifier `tab`
*/
static get MODIFIER_TAB() {
return CLASS_TAB;
}
/**
* Returns modifier `dropdown`
*/
static get MODIFIER_DROPDOWN() {
return CLASS_DROPDOWN;
}
/**
* Constructor
* @constructor
* @param {HTMLElement} element The element of the AUI component.
*/
constructor(element) {
super(element);
}
/**
* Initialize component.
*/
init() {
super.init();
// Initialize with appropriate decorator depending on modifier,
// represented by according CSS class:
if (this._element.classList.contains(CLASS_BAR)) {
this._originModifier = Nav.MODIFIER_BAR;
} else if (this._element.classList.contains(CLASS_TAB)) {
this._originModifier = Nav.MODIFIER_TAB;
} else if (this._element.classList.contains(CLASS_DROPDOWN)) {
this._originModifier = Nav.MODIFIER_DROPDOWN;
} else if (this._element.classList.contains(CLASS_LIST)) {
this._originModifier = Nav.MODIFIER_LIST;
}
this._layoutBreakpoint = parseInt(window.getComputedStyle(this._element, ':after').getPropertyValue('content').replace(/['"]+/g, ''));
if (this._layoutBreakpoint > 0 && (this._originModifier === Nav.MODIFIER_BAR || this._originModifier === Nav.MODIFIER_TAB)) {
this._resizeObserver = new ResizeObserver();
this._resizeObserver.resized.add(this._boundResize = () => this._resized());
this._resized();
} else {
this.setModifier(this._originModifier);
}
}
/**
* Dispose component.
*/
dispose() {
super.dispose();
if (this._decorator) {
this._decorator.dispose();
}
}
/**
* Updates inidcator position and visibility of paddles.
*/
update() {
if (this._decorator) {
this._decorator.update();
}
}
/**
* Set modifier to switch style of Nav Component.
* @param {string} modifier name.
* @throws Will throw an error, if the given modifier is not supported.
*/
setModifier(modifier) {
if (this._modifier === modifier) {
return;
}
if (this._decorator) {
this._decorator.dispose();
}
this._element.classList.remove(CLASS_LIST, CLASS_BAR, CLASS_TAB, CLASS_DROPDOWN);
switch (modifier) {
case Nav.MODIFIER_BAR:
this._element.classList.add(CLASS_BAR);
this._decorator = new NavBar(this._element);
break;
case Nav.MODIFIER_TAB:
this._element.classList.add(CLASS_TAB);
this._decorator = new NavBar(this._element);
break;
case Nav.MODIFIER_DROPDOWN:
this._element.classList.add(CLASS_DROPDOWN);
this._decorator = new NavDropdown(this._element);
break;
case Nav.MODIFIER_LIST:
this._element.classList.add(CLASS_LIST);
this._decorator = new NavList(this._element);
break;
default:
throw new Error(`Modifier '${modifier}' for Nav component not supported.`);
}
this._modifier = modifier;
}
/**
* Handle resize signal.
*/
_resized() {
const viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
if (this._originModifier === Nav.MODIFIER_BAR || this._originModifier === Nav.MODIFIER_TAB) {
if (viewportWidth >= this._layoutBreakpoint) {
this.setModifier(this._originModifier);
} else {
this.setModifier(Nav.MODIFIER_DROPDOWN);
}
}
}
/**
* Returns index.
* @returns {number} the index of current active action element.
*/
get index() {
return this._decorator
? this._decorator.index
: undefined;
}
/**
* Returns length.
* @returns {number} the number of action elements.
*/
get length() {
return this._decorator
? this._decorator.length
: undefined;
}
} |
JavaScript | class RJSFReferencedAcqOrder extends Component {
responseSerializer = (record) => {
return {
key: record.metadata.pid,
value: record.metadata.pid,
text: `#${record.metadata.pid} - Provider: ${record.metadata.provider.name}`,
};
};
render() {
const { options } = this.props;
return (
<RJSFESSelector
{...this.props}
options={{
apiGetByValue: async (value) => (await orderApi.get(value)).data,
apiGetByValueResponseSerializer: this.responseSerializer,
apiQuery: async (searchQuery) => await orderApi.list(searchQuery),
apiQueryResponseSerializer: this.responseSerializer,
...options,
}}
/>
);
}
} |
JavaScript | class ListItem extends Component {
render() {
const listClass = `isoSingleCard card ${this.props.view}`;
const style = { zIndex: 1000 - this.props.index };
return (
<SingleCardWrapper id={this.props._id} className={listClass} style={style}>
<div className="isoCardImage">
<img alt="#" />
</div>
<div className="isoCardContent">
<h3 className="isoCardTitle">{this.props.name}</h3>
<span className="isoCardDate">
{moment(this.props.lastUpdated).format('MMM Do, YYYY')}
</span>
</div>
<button className="isoDeleteBtn" onClick={this.props.clickHandler}>
<Icon type="close" />
</button>
</SingleCardWrapper>
);
}
} |
JavaScript | class Line {
// Returns true if the argument occupies the same space as the line
eql(line) {
return (this.isParallelTo(line) && this.contains(line.anchor));
}
// Returns a copy of the line
dup() {
return Line.create(this.anchor, this.direction);
}
// Returns the result of translating the line by the given vector/array
translate(vector) {
const V = vector.elements || vector;
return Line.create([
this.anchor.elements[0] + V[0],
this.anchor.elements[1] + V[1],
this.anchor.elements[2] + (V[2] || 0)
], this.direction);
}
// Returns true if the line is parallel to the argument. Here, 'parallel to'
// means that the argument's direction is either parallel or antiparallel to
// the line's own direction. A line is parallel to a plane if the two do not
// have a unique intersection.
isParallelTo(obj) {
if (obj.normal || (obj.start && obj.end)) {
return obj.isParallelTo(this);
}
const theta = this.direction.angleFrom(obj.direction);
return (Math.abs(theta) <= Sylvester.precision || Math.abs(theta - Math.PI) <= Sylvester.precision);
}
// Returns the line's perpendicular distance from the argument,
// which can be a point, a line or a plane
distanceFrom(obj) {
if (obj.normal || (obj.start && obj.end)) {
return obj.distanceFrom(this);
}
if (obj.direction) {
// obj is a line
if (this.isParallelTo(obj)) {
return this.distanceFrom(obj.anchor);
}
const N = this.direction.cross(obj.direction).toUnitVector().elements;
const A = this.anchor.elements;
const B = obj.anchor.elements;
return Math.abs(
((A[0] - B[0]) * N[0]) +
((A[1] - B[1]) * N[1]) +
((A[2] - B[2]) * N[2])
);
}
// obj is a point
const P = obj.elements || obj;
const A = this.anchor.elements;
const D = this.direction.elements;
const PA1 = P[0] - A[0];
const PA2 = P[1] - A[1];
const PA3 = (P[2] || 0) - A[2];
const modPA = Math.sqrt((PA1 * PA1) + (PA2 * PA2) + (PA3 * PA3));
if (modPA === 0) {
return 0;
}
// Assumes direction vector is normalized
const cosTheta = ((PA1 * D[0]) + (PA2 * D[1]) + (PA3 * D[2])) / modPA;
const sin2 = 1 - (cosTheta * cosTheta);
return Math.abs(modPA * Math.sqrt(sin2 < 0 ? 0 : sin2));
}
// Returns true iff the argument is a point on the line, or if the argument
// is a line segment lying within the receiver
contains(obj) {
if (obj.start && obj.end) {
return this.contains(obj.start) && this.contains(obj.end);
}
const dist = this.distanceFrom(obj);
return (dist !== null && dist <= Sylvester.precision);
}
// Returns the distance from the anchor of the given point. Negative values are
// returned for points that are in the opposite direction to the line's direction from
// the line's anchor point.
positionOf(point) {
if (!this.contains(point)) {
return null;
}
const P = point.elements || point;
const A = this.anchor.elements;
const D = this.direction.elements;
return ((P[0] - A[0]) * D[0]) +
((P[1] - A[1]) * D[1]) +
(((P[2] || 0) - A[2]) * D[2]);
}
// Returns true iff the line lies in the given plane
liesIn(plane) {
return plane.contains(this);
}
// Returns true iff the line has a unique point of intersection with the argument
intersects(obj) {
if (obj.normal) {
return obj.intersects(this);
}
return (!this.isParallelTo(obj) && this.distanceFrom(obj) <= Sylvester.precision);
}
// Returns the unique intersection point with the argument, if one exists
intersectionWith(obj) {
if (obj.normal || (obj.start && obj.end)) {
return obj.intersectionWith(this);
}
if (!this.intersects(obj)) {
return null;
}
const P = this.anchor.elements;
const X = this.direction.elements;
const Q = obj.anchor.elements;
const Y = obj.direction.elements;
const X1 = X[0];
const X2 = X[1];
const X3 = X[2];
const Y1 = Y[0];
const Y2 = Y[1];
const Y3 = Y[2];
const PsubQ1 = P[0] - Q[0];
const PsubQ2 = P[1] - Q[1];
const PsubQ3 = P[2] - Q[2];
const XdotQsubP = (-X1 * PsubQ1) - (X2 * PsubQ2) - (X3 * PsubQ3);
const YdotPsubQ = (Y1 * PsubQ1) + (Y2 * PsubQ2) + (Y3 * PsubQ3);
const XdotX = (X1 * X1) + (X2 * X2) + (X3 * X3);
const YdotY = (Y1 * Y1) + (Y2 * Y2) + (Y3 * Y3);
const XdotY = (X1 * Y1) + (X2 * Y2) + (X3 * Y3);
const k = ((XdotQsubP * YdotY / XdotX) + (XdotY * YdotPsubQ)) / (YdotY - (XdotY * XdotY));
return Vector.create([P[0] + (k * X1), P[1] + (k * X2), P[2] + (k * X3)]);
}
// Returns the point on the line that is closest to the given point or line/line segment
pointClosestTo(obj) {
if (obj.start && obj.end) {
// obj is a line segment
const P = obj.pointClosestTo(this);
return (P === null) ? null : this.pointClosestTo(P);
}
if (obj.direction) {
// obj is a line
if (this.intersects(obj)) {
return this.intersectionWith(obj);
}
if (this.isParallelTo(obj)) {
return null;
}
const D = this.direction.elements;
const E = obj.direction.elements;
const D1 = D[0];
const D2 = D[1];
const D3 = D[2];
const E1 = E[0];
const E2 = E[1];
const E3 = E[2];
// Create plane containing obj and the shared normal and intersect this with it
// Thank you: http://www.cgafaq.info/wiki/Line-line_distance
const x = (D3 * E1) - (D1 * E3);
const y = (D1 * E2) - (D2 * E1);
const z = (D2 * E3) - (D3 * E2);
const N = [(x * E3) - (y * E2), (y * E1) - (z * E3), (z * E2) - (x * E1)];
const P = Plane.create(obj.anchor, N);
return P.intersectionWith(this);
}
// obj is a point
const P = obj.elements || obj;
if (this.contains(P)) {
return Vector.create(P);
}
const A = this.anchor.elements;
const D = this.direction.elements;
const D1 = D[0];
const D2 = D[1];
const D3 = D[2];
const A1 = A[0];
const A2 = A[1];
const A3 = A[2];
const x = (D1 * (P[1] - A2)) - (D2 * (P[0] - A1));
const y = (D2 * ((P[2] || 0) - A3)) - (D3 * (P[1] - A2));
const z = (D3 * (P[0] - A1)) - (D1 * ((P[2] || 0) - A3));
const V = Vector.create([(D2 * x) - (D3 * z), (D3 * y) - (D1 * x), (D1 * z) - (D2 * y)]);
const k = this.distanceFrom(P) / V.modulus();
return Vector.create([
P[0] + (V.elements[0] * k),
P[1] + (V.elements[1] * k),
(P[2] || 0) + (V.elements[2] * k)
]);
}
// Returns a copy of the line rotated by t radians about the given line. Works by
// finding the argument's closest point to this line's anchor point (call this C) and
// rotating the anchor about C. Also rotates the line's direction about the argument's.
// Be careful with this - the rotation axis' direction affects the outcome!
rotate(t, line) {
// If we're working in 2D
if (typeof (line.direction) === 'undefined') {
line = Line.create(line.to3D(), Vector.k);
}
const R = Matrix.Rotation(t, line.direction).elements;
const C = line.pointClosestTo(this.anchor).elements;
const A = this.anchor.elements;
const D = this.direction.elements;
const C1 = C[0];
const C2 = C[1];
const C3 = C[2];
const A1 = A[0];
const A2 = A[1];
const A3 = A[2];
const x = A1 - C1;
const y = A2 - C2;
const z = A3 - C3;
return Line.create([
C1 + (R[0][0] * x) + (R[0][1] * y) + (R[0][2] * z),
C2 + (R[1][0] * x) + (R[1][1] * y) + (R[1][2] * z),
C3 + (R[2][0] * x) + (R[2][1] * y) + (R[2][2] * z)
], [
(R[0][0] * D[0]) + (R[0][1] * D[1]) + (R[0][2] * D[2]),
(R[1][0] * D[0]) + (R[1][1] * D[1]) + (R[1][2] * D[2]),
(R[2][0] * D[0]) + (R[2][1] * D[1]) + (R[2][2] * D[2])
]);
}
// Returns a copy of the line with its direction vector reversed.
// Useful when using lines for rotations.
reverse() {
return Line.create(this.anchor, this.direction.x(-1));
}
// Returns the line's reflection in the given point or line
reflectionIn(obj) {
if (obj.normal) {
// obj is a plane
const A = this.anchor.elements;
const D = this.direction.elements;
const A1 = A[0];
const A2 = A[1];
const A3 = A[2];
const D1 = D[0];
const D2 = D[1];
const D3 = D[2];
const newA = this.anchor.reflectionIn(obj).elements;
// Add the line's direction vector to its anchor, then mirror that in the plane
const AD1 = A1 + D1;
const AD2 = A2 + D2;
const AD3 = A3 + D3;
const Q = obj.pointClosestTo([AD1, AD2, AD3]).elements;
const newD = [
Q[0] + (Q[0] - AD1) - newA[0],
Q[1] + (Q[1] - AD2) - newA[1],
Q[2] + (Q[2] - AD3) - newA[2]
];
return Line.create(newA, newD);
}
if (obj.direction) {
// obj is a line - reflection obtained by rotating PI radians about obj
return this.rotate(Math.PI, obj);
}
// obj is a point - just reflect the line's anchor in it
const P = obj.elements || obj;
return Line.create(this.anchor.reflectionIn([P[0], P[1], (P[2] || 0)]), this.direction);
}
// Set the line's anchor point and direction.
setVectors(anchor, direction) {
// Need to do this so that line's properties are not
// references to the arguments passed in
anchor = Vector.create(anchor);
direction = Vector.create(direction);
if (anchor.elements.length === 2) {
anchor.elements.push(0);
}
if (direction.elements.length === 2) {
direction.elements.push(0);
}
if (anchor.elements.length > 3 || direction.elements.length > 3) {
return null;
}
const mod = direction.modulus();
if (mod === 0) {
return null;
}
this.anchor = anchor;
this.direction = Vector.create([
direction.elements[0] / mod,
direction.elements[1] / mod,
direction.elements[2] / mod
]);
return this;
}
// Constructor function
static create(anchor, direction) {
const L = new Line();
return L.setVectors(anchor, direction);
}
} |
JavaScript | class ADC extends Instruction {
constructor(opCode, bytes, cycles, addressing, allowExtraCycles) {
super(opCode, bytes, cycles, addressing, allowExtraCycles);
}
run(CPU) {
let value = CPU.get8Bit(this.address);
let result = CPU.REG_A + value + (CPU.FLAG_C ? 1 : 0);
CPU.FLAG_V = Byte.isBitSetAtPosition(((CPU.REG_A ^ result) & (value ^ result)), 7);
CPU.REG_A = result;
CPU.FLAG_C = CPU.REG_A > 0xFF;
CPU.REG_A &= 0xFF;
CPU.FLAG_N = Byte.isBitSetAtPosition(CPU.REG_A, 7);
CPU.FLAG_Z = CPU.REG_A === 0;
}
} |
JavaScript | class AND extends Instruction {
constructor(opCode, bytes, cycles, addressing, allowExtraCycles) {
super(opCode, bytes, cycles, addressing, allowExtraCycles);
}
run(CPU) {
CPU.REG_A = CPU.REG_A & CPU.get8Bit(this.address);
CPU.FLAG_N = Byte.isBitSetAtPosition(CPU.REG_A, 7);
CPU.FLAG_Z = CPU.REG_A === 0x00;
}
} |
JavaScript | class BCC extends Instruction {
constructor(opCode, bytes, cycles, addressing) {
super(opCode, bytes, cycles, addressing);
}
run(CPU) {
if (!CPU.FLAG_C) {
this.extraCycles += CPU.isMemoryPageDifferent(CPU.PROGRAM_COUNTER + 3, this.address) ? 2 : 1;
CPU.PROGRAM_COUNTER = this.address;
}
}
} |
JavaScript | class BMI extends Instruction {
constructor(opCode, bytes, cycles, addressing) {
super(opCode, bytes, cycles, addressing);
}
run(CPU) {
if (CPU.FLAG_N) {
this.extraCycles += CPU.isMemoryPageDifferent(CPU.PROGRAM_COUNTER + 3, this.address) ? 2 : 1;
CPU.PROGRAM_COUNTER = this.address;
}
}
} |
JavaScript | class BPL extends Instruction {
constructor(opCode, bytes, cycles, addressing) {
super(opCode, bytes, cycles, addressing);
}
run(CPU) {
if (!CPU.FLAG_N) {
this.extraCycles += CPU.isMemoryPageDifferent(CPU.PROGRAM_COUNTER + 3, this.address) ? 2 : 1;
CPU.PROGRAM_COUNTER = this.address;
}
}
} |
JavaScript | class BRK extends Instruction {
constructor(opCode, bytes, cycles, addressing) {
super(opCode, bytes, cycles, addressing);
}
run(CPU) {
CPU.PROGRAM_COUNTER++;
CPU.pushValueOnStack(CPU.PROGRAM_COUNTER >> 8);
CPU.pushValueOnStack(CPU.PROGRAM_COUNTER & 0xFF);
CPU.FLAG_B = true;
CPU.pushValueOnStack(CPU.getStatusRegisterByte());
CPU.FLAG_I = true;
CPU.PROGRAM_COUNTER = CPU.get16Bit(0xFFFE) - 1;
}
} |
JavaScript | class BVC extends Instruction {
constructor(opCode, bytes, cycles, addressing) {
super(opCode, bytes, cycles, addressing);
}
run(CPU) {
if (!CPU.FLAG_V) {
this.extraCycles += CPU.isMemoryPageDifferent(CPU.PROGRAM_COUNTER + 3, this.address) ? 2 : 1;
CPU.PROGRAM_COUNTER = this.address;
}
}
} |
JavaScript | class BVS extends Instruction {
constructor(opCode, bytes, cycles, addressing) {
super(opCode, bytes, cycles, addressing);
}
run(CPU) {
if (CPU.FLAG_V) {
this.extraCycles += CPU.isMemoryPageDifferent(CPU.PROGRAM_COUNTER + 3, this.address) ? 2 : 1;
CPU.PROGRAM_COUNTER = this.address;
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.