language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class PutCachesRequest {
/**
* Constructs a new <code>PutCachesRequest</code>.
* PutCachesRequest
* @alias module:model/PutCachesRequest
*/
constructor() {
PutCachesRequest.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>PutCachesRequest</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/PutCachesRequest} obj Optional instance to populate.
* @return {module:model/PutCachesRequest} The populated <code>PutCachesRequest</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new PutCachesRequest();
if (data.hasOwnProperty('cacheType')) {
obj['cacheType'] = ApiClient.convertToType(data['cacheType'], 'Number');
}
}
return obj;
}
} |
JavaScript | class CtrProcessor {
/**
* Init processor
* @param {Uint32Array} iv
* @param {Uint32Array} key
*/
init(key, iv) {
this.name = "AES-CTR"
this.by = 0
this.counter = iv
this.length = 16
this.leftover = new Uint8Array(0)
return windowObject.crypto.subtle.importKey("raw", key, "AES-CTR", false, ["encrypt"])
.then(key => {
this.key = key;
return this
})
}
/**
* Encrypt data
* @param {ArrayBufferView} data Data to encrypt
* @returns {ArrayBuffer}
*/
process(data) {
// Turn block cipher into stream cypher by padding + reusing the last partial block
let lengthOrig = data.byteLength
let lengthCombined = lengthOrig
let offset = 0
//console.log(data)
if (offset = this.leftover.byteLength) {
lengthCombined += offset
let newData = new Uint8Array(lengthCombined + posMod(-lengthCombined, 16))
newData.set(this.leftover)
newData.set(new Uint8Array(data.buffer), offset)
data = newData.buffer
} else {
data = pad(data, 16)
}
//console.log(new Uint8Array(data))
incCounter(this.counter, this.by)
this.by = Math.floor(lengthCombined / 16)
this.leftover = new Uint8Array(data.slice(this.by * 16, lengthCombined))
//console.log(this.by, this.leftover)
return windowObject.crypto.subtle.encrypt(this, this.key, data).then(res => res.slice(offset, offset + lengthOrig))
}
close() {}
} |
JavaScript | class cuentaController {
//mostrar vista de inicio de sesion
verlogin(req, res) {
res.render('index', {
title: 'Hola otra vez!',
fragmentos: "comple/login",
error: req.flash("err_cred"),
info:req.flash("crear")
});
}
//mostar vistas de registro de persona
verRegister(req, res) {
res.render('index', {
title: 'Bienvenido :)',
fragmentos: "comple/register",
error: req.flash("error_correo"),
});
}
//metodo para guardar token
guardarToken(req, res) {
var token = req.params.token;
Cuenta.update({
token: token
}, { where: { external_id: req.user.id_cuenta } }).then(function (updatedToken, created) {
if (updatedToken) {
console.log(updatedToken);
}
});
}
//metodo para obtener token de todas las cuentas
obtenerToken(req, res) {
Cuenta.findAll({}).then(function (cuenta) {
res.status(200).json(cuenta);
});
}
//metodo para cerrar session
cerrar(req, res) {
req.session.destroy();
res.redirect("/");
}
} |
JavaScript | class Channel extends Base {
constructor(data, client) {
super(data.id);
this.type = data.type;
this.client = client;
}
get mention() {
return `<#${this.id}>`;
}
static from(data, client) {
switch(data.type) {
case ChannelTypes.CLUB_TEXT: {
return new TextChannel(data, client);
}
case ChannelTypes.DM: {
return new PrivateChannel(data, client);
}
case ChannelTypes.CLUB_VOICE: {
return new VoiceChannel(data, client);
}
case ChannelTypes.GROUP_DM: {
return new GroupChannel(data, client);
}
case ChannelTypes.CLUB_CATEGORY: {
return new CategoryChannel(data, client);
}
case ChannelTypes.CLUB_NEWS: {
return new NewsChannel(data, client);
}
case ChannelTypes.CLUB_STORE: {
return new StoreChannel(data, client);
}
}
if(data.club_id) {
if(data.last_message_id !== undefined) {
client.emit("warn", new Error(`Unknown club text channel type: ${data.type}\n${JSON.stringify(data)}`));
return new TextChannel(data, client);
}
client.emit("warn", new Error(`Unknown club channel type: ${data.type}\n${JSON.stringify(data)}`));
return new ClubChannel(data, client);
}
client.emit("warn", new Error(`Unknown channel type: ${data.type}\n${JSON.stringify(data)}`));
return new Channel(data, client);
}
toJSON(props = []) {
return super.toJSON([
"type",
...props
]);
}
} |
JavaScript | class Main extends Component{
constructor(props){
super(props);
this.state = {
projetos : null,
}
}
componentDidMount(){
this._carregarProjetos();
}
_carregarProjetos = async() =>{
try {
let token = await AsyncStorage.getItem("@roman:token");
console.warn(token)
if (token !== null){
fetch("http://192.168.4.221:5000/api/projetos",
{
headers: {
"Authorization" : "Bearer " + token,
}
})
.then(resposta => resposta.json())
.then(data => {
this.setState({projetos : data});
})
.catch(error => console.warn(error))
}
} catch (error) {
console.warn("catch " + error)
}
}
_irParaCadastro = async() =>{
await this.props.navigation.navigate("Jefferson");
}
render() {
return (
<View style={styles.FundoTela}>
<Text style={styles.Titulos}>Projetos</Text>
<TouchableOpacity onPress={this._irParaCadastro}>
<Text>Cadastrar novo projeto</Text>
</TouchableOpacity>
<FlatList
data={this.state.projetos}
keyExtractor={item => item.idProjeto.toString()}
renderItem={({ item }) => (
<View>
<Text style={styles.IdTabela}>{item.idProjeto}</Text>
<Text style={styles.InfoTabela}>{item.nome}</Text>
<Text style={styles.InfoTabela}>{item.idTemaNavigation.nome}</Text>
</View>
)}
/>
</View>
)
}
} |
JavaScript | class IterativeParseTreeWalker extends ParseTreeWalker {
walk(listener, t) {
/**
* @type {Array<org.antlr.v4.runtime.tree.ParseTree>}
*/
var nodeStack = [];
/**
* @type {Array<number>}
*/
var indexStack = [];
var currentNode = t;
var currentIndex = 0;
while (currentNode != null) {
// pre-order visit
if (currentNode instanceof ErrorNodeImpl) {
listener.visitErrorNode(/** @type {!ErrorNode} */ (currentNode));
}
else if (currentNode instanceof TerminalNodeImpl) {
listener.visitTerminal(/** @type {!TerminalNode} */ (currentNode));
}
else {
this.enterRule(listener, /** @type {!RuleNode} */ (currentNode));
}
// Move down to first child, if exists
if (currentNode.getChildCount() > 0) {
nodeStack.push(currentNode);
indexStack.push(currentIndex);
currentIndex = 0;
currentNode = currentNode.getChild(0);
continue;
}
// No child nodes, so walk tree
do {
// post-order visit
if (currentNode instanceof RuleContext) {
this.exitRule(listener, /** @type {!RuleNode} */ (currentNode));
}
// No parent, so no siblings
if (nodeStack.length === 0) {
currentNode = null;
currentIndex = 0;
break;
}
// Move to next sibling if possible
currentNode = nodeStack[nodeStack.length - 1].getChild(++currentIndex);
if (currentNode != null) {
break;
}
// No next, sibling, so move up
currentNode = nodeStack.pop();
currentIndex = indexStack.pop();
} while (currentNode != null);
}
}
} |
JavaScript | class FileDescriptor {
constructor (number, path, stream) {
this.path = path;
this.number = number;
this.stream = stream;
}
} |
JavaScript | class Avatar extends React.PureComponent {
constructor(props) {
super(props);
let image = props.image ? props.image : props.defaultImage;
this.state = { "image": image ? image : null };
}
componentWillReceiveProps = nextProps => {
if (nextProps.image !== this.props.image) {
this.setState({ "image": nextProps.image });
}
};
_handleBadImage = () => {
/* If the default Image is equal to the bad image URL or the default image is undefined
set this.state.image as null so avatar will fallback on a different prop. */
if (
this.props.defaultImage &&
this.props.defaultImage !== this.state.image
) {
this.setState({ "image": this.props.defaultImage });
return;
}
this.setState({ "image": null });
};
render() {
let { children, icon, title, className, ...others } = this.props;
const filteredProps = Object.keys(others)
.filter(prop => !Avatar.propTypes[prop])
.reduce((obj, key) => {
obj[key] = others[key];
return obj;
}, {});
let avatar = null;
if (this.state.image) {
avatar =
<img
src={this.state.image}
title={title}
onError={this._handleBadImage}
styleName={"image"}
/>
;
} else if (icon) {
avatar = <i className={icon} />;
} else if (title) {
avatar = <span styleName={"letter"}>{title[0]}</span>;
}
return (
<div
{...filteredProps}
title={title}
className={cx(className)}
styleName={"avatar"}
>
{children}
{avatar}
</div>
);
}
} |
JavaScript | class BidParams extends BasicParams_1.default {
constructor(protocol, type, values) {
if (!values) {
super(protocol, type);
}
else {
if (!values.price) {
throw new Error('price is a required field');
}
if (!values.vehicleId) {
throw new Error('vehicleId is a required field');
}
super(protocol, type, values);
this.id = values.id;
this.vehicleId = values.vehicleId;
this.neederDavId = values.neederDavId;
this.isCommitted = values.isCommitted === false ? false : true;
const priceObject = values.price instanceof Array ? values.price : [values.price];
priceObject.map((price) => {
return typeof price === 'string'
? new Price_1.default(price, common_enums_1.PriceType.flat)
: new Price_1.default(price.value, price.type, price.description);
});
this.price = priceObject;
}
}
serialize() {
const formattedParams = super.serialize();
Object.assign(formattedParams, {
id: this.id,
price: this.price,
vehicleId: this.vehicleId,
neederDavId: this.neederDavId,
isCommitted: this.isCommitted,
});
return formattedParams;
}
deserialize(json) {
super.deserialize(json);
this.id = json.id;
this.price = json.price;
this.vehicleId = json.vehicleId;
this.neederDavId = json.neederDavId;
this.isCommitted = json.isCommitted;
}
equals(other) {
const isPriceEqual = this.price
.map((price, index) => other.price[index] && price.equals(other.price[index]))
.find((x) => !x) === undefined;
return (this.ttl === other.ttl &&
isPriceEqual &&
this.vehicleId === other.vehicleId &&
this.neederDavId === other.neederDavId);
}
} |
JavaScript | class CustomButton extends Component {
/**
* Render this component.
*/
render() {
const {
text, onPress, buttonStyle, textStyle, width, disabled
} = this.props;
return (
<TouchableOpacity
style={ [
{ padding : 10, height : 60, borderRadius : 8, margin : 10,
width : width,
backgroundColor :
disabled != null && disabled === "true" ? "#e0e0e0" : "#303656",
},
buttonStyle
] }
onPress={
() => { if (disabled == null || disabled === "false") { onPress() } }
}
>
<Text style={ [
{ fontSize : 20, fontWeight : "bold", color : "#ffffff",
textAlign : "center", paddingTop : 8
},
textStyle
] } >
{text}
</Text>
</TouchableOpacity>
);
}
} /* End customButton component. */ |
JavaScript | class NgbConfig {
constructor() {
this.animation = environment.animation;
}
} |
JavaScript | class Metadata {
constructor(entity) {
if (isPlainObject(entity) === false) {
throw new KinveyError('entity argument must be an object');
}
/**
* The entity.
*
* @private
* @type {Object}
*/
entity._kmd = entity._kmd || {};
this.entity = entity;
}
get createdAt() {
if (isDefined(this.entity._kmd.ect)) {
return new Date(this.entity._kmd.ect);
}
return undefined;
}
get ect() {
return this.createdAt;
}
get emailVerification() {
if (isDefined(this.entity._kmd.emailVerification)) {
return this.entity._kmd.emailVerification.status;
}
return undefined;
}
get lastModified() {
if (isDefined(this.entity._kmd.lmt)) {
return new Date(this.entity._kmd.lmt);
}
return undefined;
}
get lmt() {
return this.lastModified;
}
get authtoken() {
return this.entity._kmd.authtoken;
}
isLocal() {
return this.entity._kmd.local === true;
}
toPlainObject() {
return this.entity._kmd;
}
} |
JavaScript | class Payload {
constructor (path, value) {
this.path = path
this.value = value
}
/**
* Set sub-property on target
* @param target
*/
update (target) {
setValue(target, this.path, this.value)
}
} |
JavaScript | class IdentifiableMongoDbPersistence extends MongoDbPersistence_1.MongoDbPersistence {
/**
* Creates a new instance of the persistence component.
*
* @param collection (optional) a collection name.
*/
constructor(collection) {
super(collection);
/**
* Flag to turn on automated string ID generation
*/
this._autoGenerateId = true;
}
/**
* Converts the given object from the public partial format.
*
* @param value the object to convert from the public partial format.
* @returns the initial object.
*/
convertFromPublicPartial(value) {
return this.convertFromPublic(value);
}
/**
* Gets a list of data items retrieved by given unique ids.
*
* @param correlationId (optional) transaction id to trace execution through call chain.
* @param ids ids of data items to be retrieved
* @returns a data list.
*/
getListByIds(correlationId, ids) {
let filter = {
_id: { $in: ids }
};
return this.getListByFilter(correlationId, filter, null, null);
}
/**
* Gets a data item by its unique id.
*
* @param correlationId (optional) transaction id to trace execution through call chain.
* @param id an id of data item to be retrieved.
* @returns the found data item.
*/
getOneById(correlationId, id) {
return __awaiter(this, void 0, void 0, function* () {
let filter = { _id: id };
let item = yield new Promise((resolve, reject) => {
this._collection.findOne(filter, (err, item) => {
if (err == null)
resolve(item);
else
reject(err);
});
});
if (item == null) {
this._logger.trace(correlationId, "Nothing found from %s with id = %s", this._collectionName, id);
}
else {
this._logger.trace(correlationId, "Retrieved from %s with id = %s", this._collectionName, id);
}
item = this.convertToPublic(item);
return item;
});
}
/**
* Creates a data item.
*
* @param correlation_id (optional) transaction id to trace execution through call chain.
* @param item an item to be created.
* @returns theß created item.
*/
create(correlationId, item) {
if (item == null) {
return;
}
// Assign unique id
let newItem = Object.assign({}, item);
delete newItem.id;
newItem._id = item.id;
// Auto generate id
if (newItem._id == null && this._autoGenerateId) {
newItem._id = pip_services3_commons_nodex_1.IdGenerator.nextLong();
}
return super.create(correlationId, newItem);
}
/**
* Sets a data item. If the data item exists it updates it,
* otherwise it create a new data item.
*
* @param correlation_id (optional) transaction id to trace execution through call chain.
* @param item a item to be set.
* @returns the updated item.
*/
set(correlationId, item) {
return __awaiter(this, void 0, void 0, function* () {
if (item == null) {
return null;
}
// Assign unique id
let newItem = Object.assign({}, item);
delete newItem.id;
newItem._id = item.id;
// Auto generate id
if (newItem._id == null && this._autoGenerateId) {
newItem._id = pip_services3_commons_nodex_1.IdGenerator.nextLong();
}
newItem = this.convertFromPublic(newItem);
let filter = {
_id: newItem._id
};
let options = {
returnOriginal: false,
upsert: true
};
let result = yield new Promise((resolve, reject) => {
this._collection.findOneAndReplace(filter, newItem, options, (err, result) => {
if (err == null)
resolve(result);
else
reject(err);
});
});
if (item != null) {
this._logger.trace(correlationId, "Set in %s with id = %s", this._collectionName, item.id);
}
newItem = result ? this.convertToPublic(result.value) : null;
return newItem;
});
}
/**
* Updates a data item.
*
* @param correlation_id (optional) transaction id to trace execution through call chain.
* @param item an item to be updated.
* @returns the updated item.
*/
update(correlationId, item) {
return __awaiter(this, void 0, void 0, function* () {
if (item == null || item.id == null) {
return null;
}
let newItem = Object.assign({}, item);
delete newItem.id;
newItem = this.convertFromPublic(newItem);
let filter = { _id: item.id };
let update = { $set: newItem };
let options = {
returnOriginal: false
};
let result = yield new Promise((resolve, reject) => {
this._collection.findOneAndUpdate(filter, update, options, (err, result) => {
if (err == null)
resolve(result);
else
reject(err);
});
});
this._logger.trace(correlationId, "Updated in %s with id = %s", this._collectionName, item.id);
newItem = result ? this.convertToPublic(result.value) : null;
return newItem;
});
}
/**
* Updates only few selected fields in a data item.
*
* @param correlation_id (optional) transaction id to trace execution through call chain.
* @param id an id of data item to be updated.
* @param data a map with fields to be updated.
* @returns the updated item.
*/
updatePartially(correlationId, id, data) {
return __awaiter(this, void 0, void 0, function* () {
if (data == null || id == null) {
return null;
}
let newItem = data.getAsObject();
newItem = this.convertFromPublicPartial(newItem);
let filter = { _id: id };
let update = { $set: newItem };
let options = {
returnOriginal: false
};
let result = yield new Promise((resolve, reject) => {
this._collection.findOneAndUpdate(filter, update, options, (err, result) => {
if (err == null)
resolve(result);
else
reject(err);
});
});
this._logger.trace(correlationId, "Updated partially in %s with id = %s", this._collectionName, id);
newItem = result ? this.convertToPublic(result.value) : null;
return newItem;
});
}
/**
* Deleted a data item by it's unique id.
*
* @param correlation_id (optional) transaction id to trace execution through call chain.
* @param id an id of the item to be deleted
* @returns the deleted item.
*/
deleteById(correlationId, id) {
return __awaiter(this, void 0, void 0, function* () {
let filter = { _id: id };
let result = yield new Promise((resolve, reject) => {
this._collection.findOneAndDelete(filter, (err, result) => {
if (err == null)
resolve(result);
else
reject(err);
});
});
this._logger.trace(correlationId, "Deleted from %s with id = %s", this._collectionName, id);
let oldItem = result ? this.convertToPublic(result.value) : null;
return oldItem;
});
}
/**
* Deletes multiple data items by their unique ids.
*
* @param correlationId (optional) transaction id to trace execution through call chain.
* @param ids ids of data items to be deleted.
*/
deleteByIds(correlationId, ids) {
let filter = { _id: { $in: ids } };
return this.deleteByFilter(correlationId, filter);
}
} |
JavaScript | class TradierAPI {
constructor(address) {
this.endpoint = address;
}
getReferral = (symbol) => {
return {
url: `https://developer.tradier.com/documentation`,
sourceName: 'Tradier API',
interestUrl: 'https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Pages/TextView.aspx?data=yield',
};
};
// Transforms fetched chain data into something usable by this application.
// May be imported from another file a la factory pattern, and return
// whatever version works for the data source.
makeDataTransform = (chain) => {
let cleanedChain = {puts: {}, calls: {}};
let bound = chain.length;
let color;
for (let i = 0; i < bound; i++) {
color = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
cleanedChain[chain[i].option_type === 'put' ? 'puts' : 'calls'][chain[i].strike] = {
ask: chain[i].ask,
bid: chain[i].bid,
color: color,
IV: 0,
last: chain[i].last,
premium: chain[i].last || chain[i].ask || chain[i].bid,
raw: chain[i],
strike: chain[i].strike,
volume: 0,
};
}
return cleanedChain;
};
fetchData = (symbol, date) => {
// call resolve after all the necessary data are returned
// call reject if any step fails
return new Promise((resolve, reject) => {
// fetch expDates if init
let quote = fetch(`${this.endpoint}/quote?symbol=${symbol}`)
.then(response => response.json())
.then(json => {
// process quote data in here
return Promise.resolve({
change: json.quotes.quote.change,
changePercent: json.quotes.quote.change_percentage,
symbol: json.quotes.quote.symbol,
price: json.quotes.quote.last,
time: json.quotes.quote.trade_date,
raw: json.quotes.quote,
});
})
.catch(error => reject('Failed to fetch data for underlying.'));
let chain;
if (!date) {
chain = fetch(`${this.endpoint}/exp/?symbol=${symbol}`)
.then(response => response.json())
.then(json => {
return Promise.resolve(json.expirations.date);
})
.then(expDates => {
return Promise.all([
fetch(`${this.endpoint}/chain/?symbol=${symbol}&expiration=${expDates[0]}`),
Promise.resolve(expDates)
])
})
.then(vals => Promise.all([vals[0].json(), Promise.resolve(vals[1])]))
.then(vals => Promise.all([this.makeDataTransform(vals[0].options.option), Promise.resolve(vals[1])]))
.catch(error => reject('Failed to fetch option data.'));
} else {
chain = fetch(`${this.endpoint}/chain/?symbol=${symbol}&expiration=${date}`)
.then(response => response.json())
.then(chain => Promise.resolve([this.makeDataTransform(chain.options.option)]))
.catch(error => reject('Failed to fetch option data.'));
}
resolve(Promise.all([quote, chain]));
})
};
fetchRate = () => {
let rate = fetch(`${this.endpoint}/interest-rate`)
.then(response => response.json())
.then(json => json['rate']);
return rate;
};
} |
JavaScript | class Cube extends HoistBase {
static RECORD_ID_DELIMITER = '>>';
/** @member {Store} */
@managed store;
/** @member {LockFn} */
lockFn;
/** @member {BucketSpecFn} */
bucketSpecFn;
/** @member {Object} */
@observable.ref
info = null;
/** @member {Set<View>} */
_connectedViews = new Set();
/**
* @param {Object} c - Cube configuration.
* @param {(CubeField[]|CubeFieldConfig[])} c.fields - CubeField instances or configs.
* @param {{}} [fieldDefaults] - default configs applied to `CubeField` instances constructed
* internally by this Cube for its Store. {@see CubeFieldConfig} for options.
* @param {Object[]} [c.data] - array of initial raw data.
* @param {(function|string)} [c.idSpec] - {@see Store.idSpec} - default 'id'.
* @param {function} [c.processRawData] - {@see Store.processRawData}
* @param {Object} [c.info] - app-specific metadata to be associated with this data.
* @param {LockFn} [c.lockFn] - optional function to be called for each aggregate node to
* determine if it should be "locked", preventing drilldown into its children.
* @param {BucketSpecFn} [c.bucketSpecFn] - optional function to be called for each dimension
* during row generation to determine if the children of that dimension should be bucketed
* into additional dynamic dimensions.
* @param {OmitFn} [c.omitFn] - optional function to be called on all single child rows during
* view processing. Return true to omit the row.
*/
constructor({
fields,
fieldDefaults = {},
data = [],
idSpec = 'id',
processRawData,
info = {},
lockFn,
bucketSpecFn,
omitFn
}) {
super();
makeObservable(this);
this.store = new Store({
fields: this.parseFields(fields, fieldDefaults),
idSpec,
processRawData,
freezeData: false,
idEncodesTreePath: true
});
this.store.loadData(data);
this.info = info;
this.lockFn = lockFn;
this.bucketSpecFn = bucketSpecFn;
this.omitFn = omitFn;
}
/** @returns {CubeField[]} - Fields configured for this Cube. */
get fields() {return this.store.fields}
/** @returns {CubeField[]} - Dimension Fields configured for this Cube. */
get dimensions() {return this.fields.filter(it => it.isDimension)}
/** @returns {Record[]} - records loaded in to this Cube. */
get records() {return this.store.records}
/** @returns {number} - count of currently connected, auto-updating Views. */
get connectedViewCount() {return this._connectedViews.size}
//------------------
// Querying API
//-----------------
/**
* Query the cube.
*
* This method will return a snapshot of javascript objects representing the filtered
* and aggregated data in the query. In addition to the fields specified in Query, nodes will
* each contain a 'cubeLabel' and a 'cubeDimension' property.
*
* @param {Object} query - Config for query defining the shape of the view.
* @returns {Object[]} - data containing the results of the query as a hierarchical set of rows.
*/
executeQuery(query) {
query = new Query({...query, cube: this});
const view = new View({query}),
rows = view.result.rows;
view.destroy();
return rows;
}
/**
* Create a View on this data.
*
* Creates a dynamic View of the cube data, based on a query. Useful for binding to grids a
* and efficiently displaying changing results in the cube.
*
* Note: Applications should call the disconnect() or destroy() method on the View
* returned when appropriate to avoid unnecessary processing.
*
* @param {Object} c - config object.
* @param {Query} c.query - query to be used to construct this view.
* @param {(Store[]|Store)} [c.stores] - Stores to be loaded/reloaded with data from this view.
* To receive data only, use the 'results' property of the returned View instead.
* @param {boolean} [c.connect] - true to update View automatically when data in
* the underlying cube is changed. Default false.
* @returns {View}
*/
createView({query, stores, connect = false}) {
query = new Query({...query, cube: this});
return new View({query, stores, connect});
}
/**
* @param {View} view
* @return {boolean} - true if the provided view is connected to this Cube for live updates.
*/
viewIsConnected(view) {
this._connectedViews.has(view);
}
/** @param {View} view - view to disconnect from live updates. */
disconnectView(view) {
this._connectedViews.delete(view);
}
//-------------------
// Data Loading API
//-------------------
/**
* Populate this cube with a new dataset.
*
* This method largely delegates to Store.loadData(). See that method for more
* information.
*
* Note that this method will update its views asynchronously, in order to avoid locking
* up the browser when attached to multiple expensive views.
*
* @param {Object[]} rawData - flat array of lowest/leaf level data rows.
* @param {Object} info - optional metadata to associate with this cube/dataset.
*/
async loadDataAsync(rawData, info = {}) {
this.store.loadData(rawData);
this.setInfo(info);
await forEachAsync(
this._connectedViews,
(v) => v.noteCubeLoaded()
);
}
/**
* Update this cube with incremental data set changes and/or info.
* This method largely delegates to {@see Store.updateData()} - see that method for more info.
*
* Note that this method will update its views asynchronously in order to avoid locking
* up the browser when attached to multiple expensive views.
*
* @param {(Object[]|StoreTransaction)} rawData
* @param {Object} infoUpdates - new key-value pairs to be applied to existing info on this cube.
*/
async updateDataAsync(rawData, infoUpdates) {
// 1) Process data
const changeLog = this.store.updateData(rawData);
// 2) Process info
const hasInfoUpdates = !isEmpty(infoUpdates);
if (hasInfoUpdates) this.setInfo({...this.info, ...infoUpdates});
// 3) Notify connected views
if (changeLog || hasInfoUpdates) {
await forEachAsync(
this._connectedViews,
(v) => v.noteCubeUpdated(changeLog)
);
}
}
/** Clear any/all data and info from this Cube. */
async clearAsync() {
await this.loadDataAsync([]);
}
/**
* Populate the metadata associated with this cube.
* @param {Object} infoUpdates - new key-value pairs to be applied to existing info on this cube.
*/
updateInfo(infoUpdates = {}) {
this.setInfo({...this.info, ...infoUpdates});
this._connectedViews.forEach((v) => v.noteCubeUpdated(null));
}
//---------------------
// Implementation
//---------------------
@action
setInfo(info) {
this.info = Object.freeze(info);
}
parseFields(fields = [], defaults) {
return fields.map(f => {
if (f instanceof CubeField) return f;
if (!isEmpty(defaults)) {
f = defaultsDeep({}, f, defaults);
}
return new CubeField(f);
});
}
destroy() {
this._connectedViews.forEach(v => v.disconnect());
}
} |
JavaScript | class Linky extends React.Component {
render() {
const { text } = this.props
const { link } = this.props
return(
<a href={link} className="link link--iocaste">
<span>{text}</span>
<svg className="link__graphic link__graphic--slide" width="300%" height="100%" viewBox="0 0 1200 60" preserveAspectRatio="none">
<path d="M0,56.5c0,0,298.666,0,399.333,0C448.336,56.5,513.994,46,597,46c77.327,0,135,10.5,200.999,10.5c95.996,0,402.001,0,402.001,0"></path>
</svg>
</a>
)
}
} |
JavaScript | class Utils {
/**
* Return true if variable is string
* @param {*} v
* @returns {boolean}
*/
isString(v) {
return typeof v === 'string';
};
/**
* Return true if variable is a boolean
* @param {*} b
* @returns {boolean}
*/
isBool(b) {
return typeof b === 'boolean';
};
/**
* Return true if variable is a number
* @param {*} n
* @returns {boolean}
*/
isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
/**
* Return true if selector is an id selector
* @param {string} s
* @returns {boolean}
*/
isSelectorID(s) {
return (s + "").trim().indexOf("#") === 0;
};
/**
* Returns true if object is a "plain" object (not an array)
* @param o
* @returns {boolean}
*/
isPlainObject(o) {
return o.constructor.name === "Object";
};
/**
* Returns true if variable is an object (any kind, e.g. Array)
* @param {*} oa
* @returns {boolean}
*/
isObject(oa) {
return typeof oa === 'object';
};
/**
* Returns true if object is an array
* @param {object} a
* @returns {boolean}
*/
isArray(a) {
return Array.isArray(a);
};
/**
* Returns true if object is a function
* @param {object} f
* @returns {boolean}
*/
isFunction(f) {
return typeof f === 'function';
};
/**
* Returns true if object is an HTMLElement
* @param {object} n
* @returns {boolean}
*/
isElement(n) {
return n instanceof HTMLElement;
};
/**
* Return true if object is a Node or DocumentFragment
* @param {object} n
* @returns {boolean}
*/
isNode(n) {
return (n instanceof Node || n instanceof DocumentFragment);
}
/**
* Return true if string seems to be an HTML code
* @param {string} s
* @returns {boolean}
*/
isHtml(s) {
return (s + "").trim().indexOf("<") !== -1;
};
/**
* Checks if an object is empty
* @param {object} obj
* @returns {boolean}
*/
isEmpty(obj) {
return obj === undefined || (this.isObject(obj) && Object.keys(obj).length === 0) || obj === "";
};
/**
* Checks if an element is visible
* @param {HtmlElement}
* @returns {boolean}
*/
isVisible(elem) {
if(! this.isElement(elem)) {
console.log("(isVisible) Not an element: ");
console.log(elem);
return false;
}
const display = elem.style.display !== "none";
const notHidden = elem.style.visibility !== "hidden";
return display && notHidden;
};
/**
* Checks if element is in view
* @param {HtmlElement}
* @returns {boolean}
*/
inView(elem) {
const rect = elem.getBoundingClientRect();
return rect.top >= 0 && rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth) &&
rect.width > 0 && rect.height > 0
}
/**
* Remove null, empty or undefined values from an array
* @param {Array} a
* @returns {Array}
*/
cleanArray(a) {
return a.filter(function(e){ return e === 0 || e });
};
/**
* Checks if a tag name is a valid HTML element
* @param {string} tagName
* @returns {boolean}
*/
isValidElement(tagName) {
const $node = this.newElement(tagName);
return tagName !== "template" && $node.constructor.name !== "HTMLUnknownElement";
}
/**
* Returns true if element exists in DOM based on selector
*/
exists(selector) {
return document.querySelector(selector) !== null;
}
/**
* Get attribute or property
* @param {HTMLElement} $node
* @param {string} key
* @returns {*}
*/
getAttrOrProp ($node, key) {
let value = "";
if(this.hasAttrOrProp($node, key)) {
value = this.hasAttr($node, key) ? $node.getAttribute(key): $node[key];
}
return value
}
/**
* If a node contains either a property or an attribute
* @private
* @param {HTMLElement} $node
* @param {String} key
* @return {boolean}
*/
hasAttrOrProp ($node, key) {
return this.hasAttr($node, key) || this.hasProp($node, key);
}
/**
* If a node has an attribute
* @private
* @param {HTMLElement} $node
* @param {string} attr
* @return {boolean}
*/
hasAttr ($node, attr) {
let hasAttr = false;
if($node && !this.isNumeric(attr)) {
switch(attr) {
case "checked":
hasAttr = ($node.type !== undefined && ($node.type === "radio" || $node.type === "checkbox"));
break;
default:
hasAttr = $node.hasAttribute !== undefined ? $node.hasAttribute(attr) : false;
}
}
return hasAttr;
}
/**
* If a node has a property which is not an attribute
* @private
* @param {HTMLElement} $node
* @param {string} prop
* @returns {boolean}
*/
hasProp ($node, prop) {
let hasProp = false;
if($node && !this.isNumeric(prop)) {
let has = $node[prop] !== undefined;
if(has && $node[prop] === null && prop === "value") {
has = false;
}
hasProp = (has &&! ($node[prop] instanceof Node)) &&! $node.hasAttribute(prop);
}
return hasProp;
}
/**
* Set the value of a property which is true/false
* @private
* @param {HTMLElement} $node
* @param {string} key
* @param {*} value
*/
setPropOrAttr ($node, key, value) {
if(this.hasProp($node, key)) {
try {
$node[key] = value;
} catch(ignore) { //If fails, set it as attribute: (e.g. input.list)
this.setAttr($node, key, value);
}
} else {
this.setAttr($node, key, value);
}
}
/**
* Set attribute to node. If value is false, will remove it.
* @private
* @param {HTMLElement} $node
* @param {string} key
* @param {*} value
*/
setAttr ($node, key, value) {
if(value) {
$node.setAttribute(key, value);
} else {
$node.removeAttribute(key);
}
}
/**
* Define a property to an object
* @private
* @param {Object} obj
* @param {string} prop
* @param {string} def
*/
defineProp (obj, prop, def) {
if(this.isObject(obj)) {
if(obj[prop] === undefined) {
Object.defineProperty(obj, prop, {
enumerable: false,
writable: true
});
obj[prop] = def;
}
}
}
/**
* Creates a Node using HTML code
* @param {string} html
* @returns {HTMLElement}
*/
htmlElement(html) {
//return document.createRange().createContextualFragment(html); FIXME
const template = this.newElement("template");
template.innerHTML = html.trim();
return template.content.firstChild;
};
/**
* Creates a Node with a tag name
* @param {string} tagName
* @returns {HTMLElement}
*/
newElement(tagName) {
if(!tagName || this.isNumeric(tagName)) {
tagName = "invalid";
}
return document.createElement(tagName);
};
/**
* Creates an empty node (DocumentFragment)
* @returns {DocumentFragment}
*/
newEmptyNode() {
return new DocumentFragment()
}
/**
* Get all methods of class object
* https://stackoverflow.com/a/67260131/196507
* @param {object} obj
* @returns {Array}
*/
getMethods(obj) {
const o = Reflect.getPrototypeOf(obj);
const x = Reflect.getPrototypeOf(o);
return Reflect.ownKeys(o).filter(it => Reflect.ownKeys(x).indexOf(it) < 0);
};
/**
* Append all child from one node to another
* @param {HTMLElement} $srcNode
* @param {HTMLElement} $tgtNode
*/
appendAllChild($srcNode, $tgtNode) {
//Update all at once
//$node.append(...$outElem.childNodes); //<-- works but it is slower
while ($srcNode.firstChild) {
$tgtNode.append($srcNode.firstChild);
}
}
/**
* Prepend all child from one node to another
* @param {HTMLElement} $srcNode
* @param {HTMLElement} $tgtNode
*/
prependAllChild($srcNode, $tgtNode) {
//Update all at once
//$node.append(...$outElem.childNodes); //<-- works but it is slower
while ($srcNode.firstChild) {
$tgtNode.prepend($srcNode.firstChild);
}
}
} |
JavaScript | class m2d2 {
'use strict';
_stored = {
events : [],
datasetNodes : [],
datasets : [],
styleNodes : [],
styles : []
}
static storedEventsTimeout = 50; //ms to group same events
static short = true; //Enable short assignation (false = better performance) TODO: document (use Proxy like: obj.a = "text")
static updates = true; //Enable "onupdate" (false = better performance) TODO: document (use MutationObserver)
static utils = new Utils();
constructor() {
// Override some methods to prevent strange behaviour (issue #53):
["after","before","append","prepend","insertAdjacentElement","replaceWith"].forEach(p => {
Element.prototype["_"+p] = Element.prototype[p];
Element.prototype[p] = function(...args) {
const arrArgs = Array.from(args);
arrArgs.forEach((arg, index) => {
if(arg !== undefined && arg.domNode !== undefined && arg.domNode instanceof Element) { arrArgs[index] = arg.domNode; }
})
this["_"+p].apply(this, arrArgs);
}
});
}
//------------------------- STATIC -----------------------------
static instance = new m2d2();
static extensions = {}; // Additional properties for DOM
static main = (() => {
const f = (selector, object) => {
const node = this.instance.getProxyNode(selector, object);
// TEST: 13
if(node && node.onready && m2d2.utils.isFunction(node.onready)) {
node.addEventListener("ready", node.onready, { once : true });
// This will be called just after the object has been returned (to be sure it was created)
// Without setTimeout "onready" would be the same as "onload".
setTimeout(() => {
node.dispatchEvent(new CustomEvent('ready'));
}, 10); //TODO: Document
}
// Store references to datasets (used later in onpudate dataset, style):
["dataset","style"].forEach(i => {
if(node && node[i]) {
this.instance._stored[i + "s"].push(node[i]);
this.instance._stored[i + "Nodes"].push(node);
}
})
return node;
}
// Extends Utils:
m2d2.utils.getMethods(m2d2.utils).forEach(k => { f[k] = m2d2.utils[k] });
return f;
})();
/**
* Initialization. Use: m2d2.ready()
* @param { function } callback
*/
static ready(callback) {
document.addEventListener("DOMContentLoaded", () => {
callback(m2d2.main);
});
}
/**
* Execute something on load. It will search for extensions.
* @param {function} callback
* TEST: 00
*/
static load(callback) {
if(callback !== undefined) {
const ext = callback(m2d2.main); //main can be extended here
if(m2d2.utils.isObject(ext) && !m2d2.utils.isEmpty(ext)) {
Object.keys(ext).forEach(k => {
if(m2d2.utils.isValidElement(k)) {
if(m2d2.extensions[k] === undefined) {
m2d2.extensions[k] = {};
}
// Check that we are not replacing any existing property:
const $node = m2d2.utils.newElement(k);
Object.keys(ext[k]).forEach(it => {
if(m2d2.utils.hasProp($node, it)) {
console.log("Warning: property [" + it + "] already exists " +
"in node: [" + k + "] while trying to extend it. " +
"Unexpected behaviour may happen.");
}
});
Object.assign(m2d2.extensions[k], ext[k]);
} else {
if(m2d2.extensions["*"] === undefined) {
m2d2.extensions["*"] = {};
}
const $node = m2d2.utils.newElement("div");
Object.keys(ext[k]).forEach(it => {
if(m2d2.utils.hasProp($node, it)) {
console.log("Warning: property [" + it + "] already exists " +
"in Node while trying to extend it. " +
"Unexpected behaviour may happen.");
}
});
Object.assign(m2d2.extensions["*"], ext[k]);
}
});
}
}
return m2d2.main; //TODO: documentation : const $ = m2d2.load();
}
/**
* M2D2 Will set all extensions to DOM objects //TODO: documentation
* @param {string, HTMLElement} selector
* @param {HTMLElement, Node} [$root]
* @returns {HTMLElement}
* TEST: 01
*/
extDom(selector, $root) {
if(! selector) { // Do not proceed if selector is null, empty or undefined
console.error("Selector was empty");
return null;
}
if($root === undefined) { $root = document }
const $node = m2d2.utils.isNode(selector) ? selector : $root.querySelector(selector);
if(! $node) {
if(m2d2.utils.isString(selector)) {
console.error("Selector: " + selector + " didn't match any element in node:");
console.log($root);
} else {
console.error("Node was null");
}
return null;
}
if($node._m2d2 === undefined) {
$node._m2d2 = true; //flag to prevent it from re-assign methods
["parent","sibling","posterior","anterior","find","findAll","onupdate","onready","show","onshow","inView","css","text","html","getData","index"].forEach(f => {
if($node.hasOwnProperty(f)) {
console.log("Node already had ["+f+"] property. It might cause unexpected behaviour.")
console.log("You may need to update the M2D2 version or report it to: github.com/intellisrc/m2d2/")
}
});
// Properties:
// TEST: 01, ...
Object.defineProperty($node, "text", {
get() { return this.childNodes.length ? this.innerText : this.textContent; },
set(value) {
// text should only change Text nodes and not children: //TODO: documentation
if(this.childNodes.length) {
let found = false;
this.childNodes.forEach(n => {
if(n.constructor.name === "Text") {
n.nodeValue = value;
found = true;
}
});
if(! found) {
this.prepend(document.createTextNode(value));
}
} else {
this.textContent = value
}
}
});
// TEST: 43,13,27,...
Object.defineProperty($node, "html", {
get() { return this.innerHTML; },
set(value) { this.innerHTML = value; }
});
// TEST: 02
Object.defineProperty($node, "css", { //TODO: document new behaviour
get() {
return this.classList;
},
set(value) {
if(m2d2.utils.isArray(value)) {
this.className = value.join(" ");
} else if(m2d2.utils.isString(value)) {
this.className = value;
} else if(m2d2.utils.isPlainObject(value)) {
Object.keys(value).forEach(c => {
if(value[c]) {
this.classList.add(c);
} else {
this.classList.remove(c);
}
});
} else {
console.error("Trying to assign a wrong value to css : " + value);
}
}
});
// TEST: 16
Object.defineProperty($node, "show", {
get() { //TODO: document
return m2d2.utils.isVisible(this);
},
set(show) {
const cssDisplay = () => {
return getComputedStyle(this, null).display;
};
const defaultDisplay = () => {
const b = document.getElementsByTagName("body")[0];
const t = document.createElement("template");
const n = document.createElement(this.tagName);
t.append(n);
b.append(t);
const display = getComputedStyle(n, null).display;
t.remove();
return display;
};
if(show) {
if(cssDisplay() === "none") {
if(this._m2d2_display) {
this.style.display = this._m2d2_display;
} else {
this.style.removeProperty("display");
if(cssDisplay() === "none") {
const defaultShow = defaultDisplay();
this.style.display = this.dataset.display || (defaultShow !== "none" ? defaultShow : "block");
}
}
// TEST: 16
if(this.onshow !== undefined && m2d2.utils.isFunction(this.onshow)) { //TODO: document onshow
this.onshow(this);
}
}
} else {
const stored = this.style.display !== "none" ? this.style.display : cssDisplay();
if(stored !== "none") {
this._m2d2_display = stored;
}
this.style.display = "none"
}
}
});
//TODO: document how to extend
//TODO: test
let extend = {};
if(m2d2.extensions["*"] !== undefined) {
Object.assign(extend, m2d2.extensions["*"]);
}
if(m2d2.extensions[$node.tagName] !== undefined) {
Object.assign(extend, m2d2.extensions[$node.tagName]);
}
// Functions:
Object.assign($node, {
inView: () => { //TODO: document
return m2d2.utils.inView($node);
},
posterior: () => { //TEST: 07
return $node.nextElementSibling; },
anterior: () => { //TEST: 07
return $node.previousElementSibling;
},
parent: () => { //TODO: test
return this.extDom($node.parentElement);
},
sibling: (sel) => { //TODO: test
return $node.parentElement.find(sel);
},
find: (it) => { // Test: 04
const node = $node.querySelector(it)
return node ? this.extDom(node) : null;
},
findAll: (it) => { //TEST: 05
const nodeList = it === undefined ? Array.from($node.children) : $node.querySelectorAll(it);
nodeList.forEach(n => { this.extDom(n) });
return nodeList;
},
}, extend);
// Only if the object doesn't have index already (like OPTION)
if($node.index === undefined) {
$node.index = () => { //TEST: 07
return Array.from($node.parentNode.children).indexOf($node);
}
}
// Let attributes know about changes in values //TODO: test
if(["INPUT", "TEXTAREA", "SELECT"].indexOf($node.tagName) >= 0 && m2d2.utils.hasAttrOrProp($node, "value")) {
$node.oninput = function() { this.setAttribute("value", this.value )}
}
// Add getData() to form: //TODO: document
if($node.tagName === "FORM") {
$node.getData = function (includeNotVisible) { //TODO document: includeNotVisible
const data = {};
const fd = new FormData(this);
const include = includeNotVisible || false;
for (let pair of fd.entries()) {
const elem = $node.find("[name='"+pair[0]+"']");
if(include || elem.type === "hidden" || elem.show) {
const name = pair[0];
const val = elem.type === "file" ? elem.files : pair[1];
if(data[name] !== undefined) {
if(m2d2.utils.isArray(data[name])) {
data[name].push(val);
} else {
data[name] = [data[name], val];
}
} else {
data[name] = val;
}
}
}
return data;
}
}
return $node;
} else {
return $node;
}
}
/**
* M2D2 will create custom links and properties
* @param {string, HTMLElement, Node} selector
* @param {Object} object
* @returns {HTMLElement, Proxy}
* TEST: 03,...
*/
doDom(selector, object) {
// When no selector is specified, set "body"
if(m2d2.utils.isObject(selector) && object === undefined) {
object = selector;
selector = m2d2.utils.newEmptyNode(); //TODO: document
if(object.warn === undefined) {
object.warn = false;
}
}
if(!(m2d2.utils.isString(selector) || m2d2.utils.isElement(selector) || m2d2.utils.isNode(selector))) {
console.error("Selector is not a string or a Node:")
console.log(selector);
return null;
}
if(m2d2.utils.isString(selector) &&! document.querySelector(selector)) {
console.log("Selected element doesn't exists: " + selector)
return null;
}
const $node = this.extDom(selector); // Be sure that $node is an extended DOM object
// If there is no object return only extension
if(object === undefined) { //TODO: documentation: extending nodes
return $node;
}
object = this.plainToObject($node, object); // Be sure it's an object
// TEST: 03
// We filter-out some known keys:
Object.keys(object).filter(it => ! ["tagName"].includes(it)).forEach(key => {
let origValue = object[key];
if(origValue === undefined || origValue === null) {
console.log("Value was not set for key: " + key + ", 'empty' was used in object: ");
console.log(object);
console.log("In node:");
console.log($node);
origValue = "";
}
//Look for onupdate inline ([ Node, string ])
let value = this.updateValue($node, key, origValue);
//Look for property first:
let isProp = m2d2.utils.hasProp($node, key);
let isAttr = m2d2.utils.hasAttr($node, key);
//Identify if value matches property type:
let foundMatch = false;
if(isAttr || isProp) {
// noinspection FallThroughInSwitchStatementJS
switch(true) {
// Math found:
case key === "value" && m2d2.utils.hasProp($node, "valueAsDate") && value instanceof Date: // Dates
key = "valueAsDate"; //renamed value to valueAsDate
case key === "css": // css is a Proxy so it fails to verify:
case typeof value === typeof $node[key]: //Same Time
case m2d2.utils.isString($node[key]) && m2d2.utils.isNumeric(value): //Numeric properties
case (m2d2.utils.isFunction(value) && m2d2.utils.isObject($node[key])): //Functions
case m2d2.utils.isBool(value) && m2d2.utils.isString($node[key]): //Boolean
case typeof $node[key] === "object" && $node.tagName === "INPUT": //Cases like "list" in input
foundMatch = true;
break;
}
}
// Properties and Attributes:
if(foundMatch) {
let error = false;
switch(key) {
case "classList": //TODO: test
if(m2d2.utils.isArray(value)) {
value.forEach(v => {
$node[key].add(v);
});
} else if(m2d2.utils.isString(value)) {
$node[key].add(value);
} else {
error = true;
}
break
case "style": //TODO: test
case "dataset": //TODO: as it is already a DOM, we don't need it maybe?
if(m2d2.utils.isPlainObject(value)) {
Object.keys(value).forEach(k => {
$node[key][k] = this.updateValue($node[key], k, value[k]);
});
} else {
error = true;
}
break
default:
switch(true) {
case m2d2.utils.isBool(value): // boolean properties
case m2d2.utils.hasAttrOrProp($node, key):
m2d2.utils.setPropOrAttr($node, key, value);
break
default:
$node[key] = value;
}
}
if(error) {
console.error("Invalid value passed to '" + key + "': ")
console.log(value);
console.log("Into Node:");
console.log($node);
}
// Look for elements:
} else {
const options = [];
try {
// TEST: 03
// Functions can not be placed directly into elements, so we skip
if(key !== "template" &&! m2d2.utils.isFunction(value)) {
//Look for ID:
if(key && key.match(/^\w/)) {
let elem = $node.find("#" + key);
if(elem && options.indexOf(elem) === -1) { options.push(elem); }
//Look for name:
elem = $node.find("[name='"+key+"']");
if(elem && options.indexOf(elem) === -1) { options.push(elem); }
//Look for class:
const elems = Array.from($node.findAll("." + key)).filter(i => options.indexOf(i) < 0)
if(elems.length > 0) { elems.forEach(e => options.push(e)) }
}
//Look for element or free selector (e.g: "div > span"):
const elems = Array.from($node.findAll(key)).filter(i => options.indexOf(i) < 0)
if(elems.length > 0) { elems.forEach(e => options.push(e)) }
}
} catch(e) {
console.error("Invalid selector: " + key);
console.log(e);
return;
}
if(options.length > 1) {
const items = [];
options.forEach(item => {
items.push(this.render(item, key, value));
});
this.linkNode($node, key, items);
if(value.warn === undefined || value.warn !== false) { //TODO: document
console.log("Multiple elements were assigned with key: [" + key + "] under node: ")
console.log($node);
console.log("It might be what we expect, but if it is not expected it could result " +
"on some elements mistakenly rendered. You can specify " +
"'warn : false' under that element to hide this message.") //TODO: add link to reference
}
} else if(options.length === 1) { // Found single option: place values
const opt = options[0];
if(m2d2.utils.isElement(opt)) { //TODO: test (no template or no items)
const obj = this.plainToObject(opt, value);
const opt_key = m2d2.utils.isPlainObject(obj) && Object.keys(obj).length >= 1 ? Object.keys(obj)[0] : null;
if(opt_key) {
value = this.updateValue(opt, opt_key, origValue);
}
if(m2d2.utils.isArray(value)) { // Process Array
const template = object["template"];
this.doItems(opt, value, template);
this.linkNode($node, key, opt);
} else { // Normal Objects:
this.renderAndLink($node, opt, key, value);
}
} else {
console.error("BUG: It should have been a node but got: ");
console.log(opt);
console.log("Parent node:")
console.log($node);
}
} else if(options.length === 0) { //No options found: create nodes
// Make "items" optional: //TODO: document
if(key === "template" && object["items"] === undefined) {
key = "items";
value = [];
}
const isFunc = m2d2.utils.isFunction(value);
if(value.tagName !== undefined) {
const $newNode = this.appendElement($node, value.tagName);
this.renderAndLink($node, $newNode, key, value);
} else if(m2d2.utils.isValidElement(key) &&! isFunc) {
const $newNode = this.appendElement($node, key);
this.renderAndLink($node, $newNode, key, value);
} else if(key === "items") { //Items creation
const template = object["template"];
// Allow use of plain object to specify value -> text //TODO: documentation
if(m2d2.utils.isPlainObject(value)) {
const valTmp = [];
Object.keys(value).forEach(o => {
let obj;
if($node.tagName === "DL") { //TODO: document DL
obj = { dt : o, dd : value[o] }
} else {
obj = { text: value[o] };
if (m2d2.utils.hasAttrOrProp($node, "value")) {
obj.value = o;
} else {
obj.dataset = {id: o};
}
}
valTmp.push(obj);
});
value = valTmp;
}
// Process Array:
if(m2d2.utils.isArray(value)) {
this.doItems($node, value, template);
} else {
console.log("Warning: 'items' specified but value is not and array, in element: ");
console.log($node);
console.log("Passed values are: ");
console.log(value);
}
} else if(isFunc) {
if(m2d2.updates) {
// By using addEventListener we can assign multiple listeners to a single node //TODO: document
if (key === "onupdate") {
$node.addEventListener("update", value, true); //TODO: document
}
}
$node[key] = value;
} else if(key !== "template" && (key !== "warn" && value !== false)) { //We handle templates inside items
if(object.warn === undefined || object.warn !== false) { //TODO: document
console.error("Not sure what you want to do with key: " + key + " under element: ");
console.log($node);
console.log("And object:");
console.log(object);
console.log("Most likely the element's property or child no longer exists or the value" +
" passed to it is incorrect.");
console.log("You can set 'warn : false' property to the element to dismiss this message.");
}
$node[key] = value;
}
}
}
});
// Dispatch onload event (if its not native): //TODO: Document
if($node.onload) {
const native = ["BODY","FRAME","IFRAME","IMG","LINK","SCRIPT","STYLE"].indexOf($node.tagName) >= 0;
const inputImage = $node.tagName === "INPUT" && $node.type === "image";
if(! (native || inputImage)) {
// We don't need to add the event as it exists natively and it was assigned during: $node.onload = ...;
$node.dispatchEvent(new CustomEvent('load'));
}
}
return $node;
}
/**
* Identify if value is an update link (inline onupdate)
* @param {*} value
* @returns {boolean}
*/
isUpdateLink(value) {
let isLink = false
if(m2d2.utils.isArray(value) && (value.length === 2 || value.length === 3)) {
const twoArgs = value.length === 2;
// First element in array must be Node || DomStringMap (dataset) || CSSStyleDeclaration (style)
const acceptedType = m2d2.utils.isNode(value[0]) ||
value[0] instanceof DOMStringMap ||
value[0] instanceof CSSStyleDeclaration
// Second must be 'string' and Third can be a 'function'
const otherTypes = twoArgs ? m2d2.utils.isString(value[1]) :
m2d2.utils.isString(value[1]) && m2d2.utils.isFunction(value[2]);
// If only two args are in array, add an empty function:
isLink = acceptedType && otherTypes;
if(isLink && twoArgs) { value.push(v => { return v; }) } //TODO: Document function
}
return isLink
}
/**
* Convert plain value into object if needed
* @param {HTMLElement, Node} $node
* @param {*} value
*/
plainToObject($node, value) {
if(!m2d2.utils.isPlainObject(value) &&! m2d2.utils.isFunction(value) &&! m2d2.utils.isElement(value)) {
// When setting values to the node (simplified version):
if(m2d2.utils.isHtml(value)) {
value = { html : value };
} else if(this.isUpdateLink(value)) {
const obj = value[0];
const prop = value[1];
const callback = value[2];
let tmpVal = this.plainToObject($node, callback(obj[prop]));
if(m2d2.utils.isPlainObject(tmpVal)) {
const newValue = {};
Object.keys(tmpVal).forEach(k => {
newValue[k] = value;
});
value = newValue;
}
} else if(m2d2.utils.isArray(value)) {
value = { items : value };
} else if(m2d2.utils.hasAttrOrProp($node, "value")) {
// If the parent is <select> set also as text to item:
if($node.tagName === "SELECT") {
value = {
value : value,
text : value
};
} else if($node.tagName === "BUTTON") {
value = { text : value };
} else {
value = { value : value };
}
} else if(m2d2.utils.isString(value) && $node.tagName === "IMG") {
value = { src : value };
} else if(m2d2.utils.isString(value) || m2d2.utils.isNumeric(value)) {
value = { text : value };
}
}
return value;
}
/**
* Render and Link a node
* @private
* @param {HTMLElement} $root
* @param {HTMLElement} $node
* @param {string} key
* @param {*} value
*/
renderAndLink($root, $node, key, value) {
const $child = this.render($node, key, value);
this.linkNode($root, key, $child);
}
/**
* Render some value in a node
* @private
* @param {HTMLElement} $node
* @param {string} key
* @param {*} value
* @returns {Proxy, HTMLElement}
*/
render($node, key, value) {
value = this.plainToObject($node, value);
return this.doDom($node, value); // Recursive for each element
}
/**
* Links a property to a child node
* @private
* @param {HTMLElement} $node
* @param {String} key
* @param {HTMLElement} $child
*/
linkNode($node, key, $child) {
if($node[key] === $child) {
const $proxy = this.proxy($child);
try {
$node[key] = $proxy;
} catch(ignore) {
//NOTE: although it fails when using forms, form is a proxy so it still works.
}
$node["$" + key] = $proxy;
} else if(m2d2.utils.hasAttrOrProp($node, key)) { // Only if its not an attribute or property, we "link" it.
$node["$" + key] = $child; //Replace name with "$" + name
console.log("Property : " + key + " existed in node: " + $node.tagName +
". Using $" + key + " instead for node: " + $child.tagName + ".")
} else {
$node[key] = this.proxy($child);
}
}
/**
* Creates a dom element inside $node
* @private
* @param {HTMLElement} $node
* @param {string} tagName
* @returns {HTMLElement}
*/
appendElement ($node, tagName) {
const $newElem = m2d2.utils.newElement(tagName);
$node.append($newElem);
return $newElem;
}
/**
* Get an item to be added
* @param {HTMLElement|null} $node
* @param {number|string} index
* @param {*} obj
* @param {HTMLElement} $template
*/
getItem($node, index, obj, $template) {
if(!$template) {
$template = this.getTemplate($node);
}
const $newItem = $template.cloneNode(true);
// Copy templates to new item:
this.addTemplatesToItem($template, $newItem);
$newItem.dataset.id = index;
// Add "selected" property
this.setUniqueAttrib($newItem, "selected"); //TODO: Document
// Add template to object //TODO: it might not work with events
this.addTemplatesToObjectDeep($template, obj);
// Set values and links
let $newNode = this.doDom($newItem, obj);
// Place Events:
return this.getItemWithEvents($node, $newNode);
}
/**
* Try to set template to objects deep in tree
*/
addTemplatesToObjectDeep($template, obj) {
if(m2d2.utils.isPlainObject(obj)) {
Object.keys(obj).forEach(key => {
if($template[key] && $template[key].__template &&! obj.template) {
obj[key].template = $template[key].__template;
}
if($template[key] && obj[key]) {
this.addTemplatesToObjectDeep($template[key], obj[key]);
}
});
}
}
/**
* Reassign templates
* @param {HTMLElement, Node} $template
* @param {HTMLElement, Node} $newNode
* @returns {HTMLElement|Proxy}
// TODO: this does not support deep location of templates
*/
addTemplatesToItem($template, $newNode) {
["_template","__template"].forEach(key => {
if($template[key] !== undefined) {
$newNode[key] = $template[key];
}
});
}
/**
* Returns a Node with events
* @param {HTMLElement, Node} $node
* @param {HTMLElement, Node} $newNode
* @returns {HTMLElement|Proxy}
//FIXME: I think `this.doDom` could be removed from here and only "link" events
*/
getItemWithEvents($node, $newNode) {
if($node.__template !== undefined) {
const scan = (object, result) => {
result = result || {};
Object.keys(object).forEach(key=> {
if (m2d2.utils.isPlainObject(object[key])) {
result[key] = scan(object[key]);
} else if(m2d2.utils.isFunction(object[key])) {
result[key] = object[key];
}
});
return result;
}
let tree = scan($node.__template);
if(!m2d2.utils.isEmpty(tree)) {
tree = tree[Object.keys(tree)[0]];
$newNode = this.doDom($newNode, tree);
}
}
return $newNode;
}
/**
* Process items
* @private
* @param {HTMLElement} $node
* @param {Array} values
* @param {Object} template
*/
doItems ($node, values, template) {
// Create the structure for the item:
const $template = this.getTemplate($node, template);
if($template === undefined) {
console.error("Template not found. Probably an array is being used where it is not expected. Node:");
console.log($node);
console.log("Value (mistaken?):")
console.log(values);
return;
}
// Fill the template with data:
let i = 0;
values.forEach(val => {
val = this.plainToObject($node, val);
const $newItem = this.getItem($node, i++, val, $template);
if($newItem) {
$node.append($newItem);
}
});
// Cleanup
const $temp = $node.find("template");
if($temp) { $node.removeChild($temp); }
// Set "items" link:
$node.items = $node.children;
this.extendItems($node);
}
/** Returns an HTMLElement with the structure without events
* @private
* @param {HTMLElement} $node
* @param {Object, string} [template]
* @returns {HTMLElement}
*/
getTemplate ($node, template) {
// If we already have the template, return it:
if($node._template !== undefined && $node._template !== "") {
return $node._template;
} else {
let $template;
const $htmlTemplate = $node.querySelector("template"); // look into HTML under node
if($htmlTemplate) {
$template = m2d2.utils.htmlElement($htmlTemplate.innerHTML.trim());
} else {
switch ($node.tagName) {
case "SELECT":
case "DATALIST":
$template = m2d2.utils.newElement("option");
break;
case "UL":
case "OL":
$template = m2d2.utils.newElement("li");
break;
case "NAV":
$template = m2d2.utils.newElement("a");
break;
case "DL":
$template = m2d2.utils.newElement("dd");
break;
default:
if(template && m2d2.utils.isPlainObject(template)) {
const children = Object.keys(template).length;
if(children) {
if(children > 1) {
if(template.tagName !== undefined) { //TODO: document (optional top child when using tagName)
let wrap = {};
wrap[template.tagName] = template;
template = wrap;
} else {
console.log("Template has more than one top elements. Using the first one. In: ");
console.log(template);
console.log("Node: ");
console.log($node);
}
}
const key = Object.keys(template)[0];
const val = template[key];
if(m2d2.utils.isValidElement(key)) {
$template = m2d2.utils.newElement(key);
} else if(val.tagName !== undefined) {
$template = m2d2.utils.newElement(val.tagName);
template[val.tagName] = val;
delete(template[key]);
} else {
console.error("Template defined an element which can not be identified: [" + key + "], using <span> in:");
console.log(template);
console.log("Node: ");
console.log($node);
$template = m2d2.utils.newElement("span");
}
} else {
console.error("Template has no definition, and it can not be guessed. Using <span>. Template: ");
console.log(template);
console.log("Node: ");
console.log($node);
$template = m2d2.utils.newElement("span");
}
} else {
// If not template is found, use html as of element
if($node.childElementCount > 0) {
$template = m2d2.utils.htmlElement($node.innerHTML.trim());
}
}
break;
}
}
if (template) {
if (m2d2.utils.isPlainObject(template)) {
const $wrap = m2d2.utils.newEmptyNode();
$wrap.append($template);
const $fragment = this.doDom($wrap, template);
$template = $fragment.children[0];
m2d2.utils.defineProp($node, "__template", template); // This is the original template with events
} else if (m2d2.utils.isHtml(template)) {
$template = m2d2.utils.htmlElement(template);
} else if (m2d2.utils.isSelectorID(template)) { //Only IDs are allowed //TODO document
$template = m2d2.utils.htmlElement(document.querySelector(template).innerHTML);
} else { //When its just a tag name
$template = m2d2.utils.newElement(template);
}
}
if ($template) {
if($template.childrenElementCount > 1) {
console.log("Templates only supports a single child. Multiple children were detected, wrapping them with <span>. Template:");
console.log($template);
const $span = m2d2.utils.newElement("span");
$span.append($template);
$template = $span;
} else {
m2d2.utils.defineProp($node, "_template", $template); // This is the DOM
}
} else {
console.log("Template was not found for element, using <span>:");
console.log($node);
const $span = m2d2.utils.newElement("span");
$template = $span;
}
return $template;
}
}
/**
* It will set a unique attribute among a group of nodes (grouped by parent)
* @private
* @param {HTMLElement, Node} $node
* @param {string} key
*/
setUniqueAttrib($node, key) {
if(! $node.hasOwnProperty(key)) {
Object.defineProperty($node, key, {
get : function() {
return this.hasAttribute(key);
},
set : function(val) {
const prevSel = this.parentNode ? this.parentNode.find("["+key+"]") : null;
if(prevSel) {
prevSel.removeAttribute(key);
}
m2d2.utils.setAttr(this, key, val);
}
});
}
}
/**
* Handle [ Node, string ] values (inline onupdate)
* @private
* @param {HTMLElement} $node
* @param {string} key
* @param {*} value
*/
updateValue($node, key, value) {
// TEST: 06
if(this.isUpdateLink(value)) {
const _this = this;
const obj = value[0];
const prop = value[1];
const callback = value[2];
value = obj[prop];
if(obj instanceof CSSStyleDeclaration && this._stored.styles.includes(obj)) {
const parent = this._stored.styleNodes[this._stored.styles.indexOf(obj)];
if(m2d2.updates) {
parent.onupdate = function (ev) {
if (ev.detail && ev.detail.property === "style" && ev.detail.newValue.startsWith(prop + ":")) {
_this.setShortValue($node, key, callback(this.style[prop]));
}
}
}
} else if(obj instanceof DOMStringMap && this._stored.datasets.includes(obj)) {
const parent = this._stored.datasetNodes[this._stored.datasets.indexOf(obj)];
if(m2d2.updates) {
parent.onupdate = (ev) => {
if (ev.detail && ev.detail.property === "data-" + prop) {
_this.setShortValue($node, key, callback(ev.detail.newValue));
}
}
}
} else {
if(m2d2.updates) {
obj.onupdate = (ev) => {
if (ev.detail && ev.detail.property === prop) {
if (!m2d2.utils.isObject($node[key])) {
_this.setShortValue($node, key, callback(ev.detail.newValue));
}
}
}
}
}
}
return value;
}
/**
* Place a value either in a property or in a node (short)
* @param $node {Node}
* @param key {string}
* @param value {*}
*/
setShortValue($node, key, value) {
if(m2d2.utils.isNode($node[key])) {
if(m2d2.short) {
const o = this.plainToObject($node[key], value);
const k = m2d2.utils.isPlainObject(o) && Object.keys(o).length >= 1 ? Object.keys(o)[0] : null;
if (k) {
$node[key][k] = value;
}
} else {
console.log("Short is disabled. Trying to set a value ("+value+") in a node:")
console.log($node[key]);
console.log("Either turn on 'short' functionality, or be sure you specify the property, like: 'node.text'")
}
} else {
$node[key] = value
}
}
/**
* Place a value either in a property or in a node (short)
* @param $node {Node}
* @param key {string}
* @param sample {*} Sample value (to automatically guess property)
* @returns {*} current value
*/
getShortValue($node, key, sample) {
let value = null;
if(m2d2.utils.isNode($node[key])) {
if(m2d2.short) {
const o = this.plainToObject($node[key], sample || "");
const k = m2d2.utils.isPlainObject(o) && Object.keys(o).length >= 1 ? Object.keys(o)[0] : null;
if (k) {
value = $node[key][k];
}
} else {
console.log("Short is disabled. Trying to get a value from node:")
console.log($node[key]);
console.log("Either turn on 'short' functionality, or be sure you specify the property, like: 'node.text'")
}
} else {
value = $node[key];
}
return value;
}
/**
* Basic Proxy to enable assign values to elements
* for example: div.a = "Click me" (instead of using: div.a.text)
* NOTE: for reading, "div.a" will return a Node and not the value.
* @private
* @param {Object} obj
* @param {boolean} [force] Force to update
* @returns {Proxy, Object}
*/
proxy (obj, force) {
if(!m2d2.short || (obj === null || (obj.domNode !== undefined && force === undefined))) {
return obj;
} else {
obj.domNode = obj;
const handler = {
get: (target, property) => {
const t = target[property];
switch (true) {
case t === null || t === undefined: return null;
// Functions should bind target as "this"
case m2d2.utils.isFunction(t): return t.bind(target);
// If there was a failed attempt to set proxy, return it on read:
case t.domNode && target["$" + property] !== undefined: return target["$" + property];
case t.domNode === undefined && m2d2.utils.isElement(t): return this.proxy(t);
default: return t;
}
},
set: (target, property, value) => {
let oldValue = "";
if(m2d2.utils.isElement(target[property])) {
oldValue = this.getShortValue(target, property, value);
this.setShortValue(target, property, value);
} else if(property === "onupdate") {
if(m2d2.updates) {
if (m2d2.utils.isFunction(value)) {
// By using addEventListener we can assign multiple listeners to a single node
target.addEventListener("update", value, true);
oldValue = target[property];
target[property] = value;
} else {
console.error("Value passed to 'onupdate' is incorrect, in node:");
console.log(target);
console.log("Value: (not a function)");
console.log(value);
}
} else {
console.log("Updates are not available when `m2d2.updates == false`:")
console.log(target);
}
} else if(property === "items") { //Reset items
target.items.clear();
this.doItems(target, value);
} else {
oldValue = target[property];
value = this.updateValue(target, property, value);
target[property] = value;
}
// Check for onupdate //TODO: document
// This will observe changes on values
if(m2d2.updates && target.onupdate !== undefined) {
if(value !== oldValue) {
target.dispatchEvent(new CustomEvent("update", {
detail: {
type : typeof value,
property : property,
newValue : value,
oldValue : oldValue
}
}));
}
}
return true;
}
};
return new Proxy(obj, handler);
}
}
/**
* Function passed to MutationObserver
* @private
* @param {MutationRecord} mutationsList
* @param {MutationObserver} observer
*/
onObserve(mutationsList, observer) {
mutationsList.forEach(m => {
const target = m.target;
// We store the events to remove immediately repeated events.
// Forms will link elements which can not be set as proxy so we
// add a link named `"$" + key` but this have the side effect to
// generate two triggers (one for the element and one for the Proxy).
if(this._stored.events.indexOf(m) >= 0) { return } else {
this._stored.events.push(m);
setTimeout(() => {
const i = this._stored.events.indexOf(m);
if(i >= 0) { this._stored.events.splice(i, 1); }
}, m2d2.storedEventsTimeout); //TODO: this will prevent repeated events to be triggered in less than 50ms : document
}
// Check for onupdate //TODO: document
if(target.onupdate !== undefined) {
if(m.type === "attributes") {
const value = m2d2.utils.getAttrOrProp(target, m.attributeName);
if(value !== m.oldValue) {
target.dispatchEvent(new CustomEvent("update", {
detail: {
type : typeof value,
property : m.attributeName,
newValue : value,
oldValue : m.oldValue
}
}));
}
} else if(m.type === "childList") { //TODO: improve for other types
const $child = m.addedNodes[0] || m.removedNodes[0];
if($child.nodeName === "#text") {
const value = m.addedNodes[0].textContent;
const oldValue = m.removedNodes.length ? m.removedNodes[0].textContent : null;
if(value !== oldValue) {
target.dispatchEvent(new CustomEvent("update", {
detail: {
type : typeof value,
property : "text",
newValue : value,
oldValue : oldValue
}
}));
}
} else if(target.items !== undefined) { //Items updated
//TODO: Document: in case of items, "new = added", "old = removed"
const value = m.addedNodes;
const oldValue = m.removedNodes;
if(value !== oldValue) {
target.dispatchEvent(new CustomEvent("update", {
detail: {
type : typeof value,
property : "items",
newValue : value,
oldValue : oldValue
}
}));
}
}
}
}
});
}
/**
* Add MutationObserver to object
* @private
* @param { HTMLElement } $node
*/
observe($node) {
if(m2d2.updates) {
const mutationObserver = new MutationObserver(this.onObserve.bind(this))
const options = {
attributeOldValue: true
}
options.subtree = true;
options.childList = true;
const toObserve = $node.domNode || $node;
mutationObserver.observe(toObserve, options);
}
}
/**
* Get the root node as proxy
* @private
* @param {string|HTMLElement} selector
* @param {Object} obj
*/
getProxyNode(selector, obj) {
const $node = this.doDom(selector, obj);
if($node) {
this.observe($node);
return this.proxy($node);
}
}
/**
* Extends "items"
* @private
* @param {NodeList, HTMLCollection} $node
*/
extendItems($node) {
// We try to add most of the array functions into NodeList and HTMLCollection:
// NOTE: Not all will work as expected.
// NOTE: function() {} is not the same here as () => {} as "this" is not as expected
function reattach(items) {
items.forEach(itm => {
const parent = itm.parentNode;
const detatchedItem = parent.removeChild(itm); //We detach from original parent
$node.append(detatchedItem); //Attach to $node (works with non-existing elements)
});
}
const items = $node.items;
// Non-Standard or non-existent in Array:
const nonStd = ["clear", "get", "remove", "selected", "first", "last", "findAll"];
// Array properties:
Object.getOwnPropertyNames(Array.prototype).concat(nonStd).forEach(method => {
if(items[method] === undefined) {
let func = null;
const _this = this;
switch (method) {
//-------------------- Same as in Array --------------------------
case "copyWithin": // copy element from index to index
case "fill": // replace N elements in array
case "splice": // add or remove elements
func = function() {
console.log("Not available yet: " + method);
}
break;
case "reverse": // reverse the order
func = function(...args) {
if(this.items.length) {
const items = Array.from(this.items); //Keep a copy
const retObj = items[method](...args);
reattach(items);
return retObj;
}
}
break;
//--------------------- Special Implementation --------------------
case "clear": // parentNode.replaceChildren() can also be used
func = function() {
while(this.items[0]) this.items[0].remove()
}
break;
case "get": // will return the item with data-id:
func = function(id) {
let found = null;
if(this.items.length) {
this.items.some(item => {
const sameId = m2d2.utils.isNumeric(id) ? (item.dataset.id * 1) === id * 1 : item.dataset.id === id;
if(item.dataset && sameId) {
found = item;
return true;
}
});
}
return found;
}
break;
case "selected": // will return the selected item in list
func = function() {
return _this.proxy(this.find(":scope > " + "[selected]")); //only direct children
}
break;
case "first": // returns the first item in list
func = function() {
return _this.proxy(this.items[0]);
}
break;
case "last": // returns the last item in list
func = function() {
return _this.proxy(this.items[this.items.length - 1]);
}
break;
case "pop" : //Remove and return last element:
func = function() {
if(this.items.length) {
const parent = this[0].parentNode;
return _this.proxy(parent.removeChild(this.items[this.items.length - 1]));
}
}
break;
case "push": // Add one item at the end:
func = function(obj) {
obj = _this.plainToObject(this, obj);
if(m2d2.utils.isElement(obj)) {
this.append(obj);
} else if (m2d2.utils.isPlainObject(obj)) {
const index = this.items.length;
const $child = _this.getItem(this, index, obj);
this.appendChild($child);
} else {
console.log("Trying to push an unknown value into a list:");
console.log(obj)
}
}
break;
case "remove": // will return the item with data-id:
func = function(id) {
if(this.items.length) {
const elem = this.items.get(id);
if(elem.length === 1) {
elem.remove();
}
}
}
break;
case "shift": // remove and return first item:
func = function() {
if(this.items.length) {
const parent = this.items[0].parentNode;
return _this.proxy(parent.removeChild(this.items[0]));
}
}
break;
case "sort": // You can pass a function to compare items:
func = function(compareFunc) {
if(this.items.length) {
const items = Array.from(this.items); //Keep copy
items.sort(compareFunc || ((a, b) => {
return a.text.localeCompare(b.text);
}));
reattach(items);
}
}
break;
case "unshift": // Add an item to the beginning
func = function(obj) {
obj = _this.plainToObject(this, obj);
if(m2d2.utils.isElement(obj)) {
this.prepend(obj);
} else if (m2d2.utils.isPlainObject(obj)) {
const index = this.items.length;
const $child = _this.getItem(this, index, obj);
this.prepend($child);
} else {
console.log("Trying to unshift an unknown value into a list:");
console.log(obj)
}
}
break;
default: //----------------- Link to Array -------------------
let arrMethod = method;
// noinspection FallThroughInSwitchStatementJS
switch(true) {
case method === "findAll":
arrMethod = "filter"; // Use "filter"
case m2d2.utils.isFunction(Array.prototype[method]):
// Convert nodes to proxy so we can use short assignment
// at, concat, every, filter, find, findIndex, forEach, includes, indexOf, join,
// keys, lastIndexOf, map, reduce, reduceRight, slice, some, values
const arrFunc = function (...args) {
const proxies = [];
Array.from($node.items).forEach(n => {
proxies.push(_this.proxy(n));
});
return Array.from(proxies)[arrMethod](...args);
}
switch(method) {
// Change behaviour of find: //TODO: documentation
case "find":
func = function(...args) {
if(m2d2.utils.isString(args[0])) {
return this.find(args[0]);
} else {
return arrFunc(...args);
}
}
break
case "findAll": //TODO: documentation
func = function(...args) {
if(args.length === 0) {
return this.findAll();
} else if(m2d2.utils.isString(args[0])) {
return this.findAll(args[0]);
} else {
return arrFunc(...args);
}
}
break
case "concat": //TODO: documentation
func = function(...args) {
for(let i = 0; i < args.length; i++) {
if(m2d2.utils.isArray(args[i])) {
for(let j = 0; j < args[i].length; j++) {
let obj = args[i][j];
if(! m2d2.utils.isElement(obj)) {
obj = _this.plainToObject(this, args[i][j]);
if (m2d2.utils.isPlainObject(obj)) {
const index = this.items.length;
obj = _this.getItem(this, index, obj);
}
}
this.items.push(obj);
}
}
}
}
break
default:
func = arrFunc;
break
}
}
}
if(func) {
m2d2.utils.defineProp(items, method, func.bind($node)); //bind: specify the "this" value
}
}
});
}
} |
JavaScript | class ws {
request(msg) {
if (msg) {
try {
this.webSocket.send($.isObject(msg) ? JSON.stringify(msg) : msg);
} catch(e) {
this.webSocket.onerror(e);
}
}
}
/**
* Connect and return the websocket object
*/
getSocket(onMessage, onOpen, onClose) {
const webSocket = new WebSocket(this.url);
webSocket.onopen = onOpen;
webSocket.onclose = onClose;
webSocket.onmessage = (res) => {
if (res.data) {
try {
onMessage(JSON.parse(res.data));
} catch(e) {
webSocket.onerror(e);
}
}
}
webSocket.onerror = (err) => {
console.error('Socket encountered error: ', err ? err.message : 'Unknown', 'Closing socket');
const wsk = webSocket || this;
if(wsk.readyState === 1) {
wsk.close();
}
}
return webSocket;
}
connect(options, onMessage) {
this.initRequest = options.request || null;
this.onConnect = options.connected || (() => {});
this.onDisconnect = options.disconnected || (() => {});
this.reconnect = options.reconnect !== false;
this.host = options.host || window.location.hostname;
this.secure = options.secure === true;
this.port = options.port || (this.secure ? 443 : 80);
this.path = "/" + (options.path.replace(/^\//,"") || "");
this.args = Object.assign({}, options.args);
const protocol = "ws" + (this.secure ? "s" : "") + "://";
const hostPort = this.host + ":" + this.port;
const uriPath = this.path;
const queryStr = (this.args ? "?" + new URLSearchParams(this.args).toString() : "");
this.url = protocol + hostPort + uriPath + queryStr;
this.connected = false;
this.interval = null;
//-------- Connect ----------
const onOpen = (e) => {
this.connected = true;
this.request(this.initRequest);
this.onConnect();
}
const onClose = (e) => {
this.connected = false;
this.onDisconnect();
if(!this.interval && this.reconnect) {
this.interval = setInterval(() => {
if(this.connected) {
console.log("Reconnected...")
clearInterval(this.interval);
} else {
try {
this.webSocket.close();
console.log("Reconnecting...")
this.webSocket = this.getSocket(onMessage, onOpen, onClose);
} catch(ignore) {}
}
}, 2000);
}
}
this.webSocket = this.getSocket(onMessage, onOpen, onClose);
}
disconnect() {
this.reconnect = false;
this.webSocket.close();
}
} |
JavaScript | class Loop extends Adjust {
constructor(props) {
super(props);
this._loopAdjustFunction = ContentCreatorLoop.create();
}
/**
* Function that removes the used props
*
* @param aReturnObject Object The props object that should be adjusted
*/
_removeUsedProps(aReturnObject) {
//METODO: change this to actual source cleanup
aReturnObject = super._removeUsedProps(aReturnObject);
delete aReturnObject["loop"];
delete aReturnObject["loopName"];
return aReturnObject;
}
_addAdjustFunctions(aReturnArray) {
let loop = this.getSourcedPropWithDefault("loop", this._loopAdjustFunction);
aReturnArray.push(loop);
}
_getAdjustFunctions() {
let returnArray = super._getAdjustFunctions();
this._addAdjustFunctions(returnArray);
return returnArray;
}
_getChildrenToClone() {
let children = super._getChildrenToClone();
if(children.length === 0) {
children = [React.createElement(InjectChildren)];
}
return children;
}
_renderMainElement() {
//console.log("Loop::_renderMainElement", this);
let clonedElementes = super._renderMainElement();
let injectData = new Object();
let loopLength = 0;
let input = this.getSourcedProp("input");
if(input) {
loopLength = input.length;
}
let loopName = this.getSourcedPropWithDefault("loopName", "");
if(loopName !== "") {
loopName += "/";
}
injectData["loop/name"] = loopName;
injectData["loop/" + loopName + "allItems"] = input;
injectData["loop/" + loopName + "length"] = loopLength;
if(clonedElementes === undefined || (clonedElementes && clonedElementes.type === undefined)) {
console.error("Loop has undefined children");
clonedElementes = React.createElement("div", {className: "react-error"},
React.createElement("div", {}, "Loop has undefined children")
);
}
return React.createElement(ReferenceInjection, {"injectData": injectData}, clonedElementes);
}
static createMarkupLoop(aArray, aItemMarkup, aSpacingMarkup = null, aChildren = null) {
return React.createElement(Loop, {"loop": Wprr.adjusts.markupLoop(aArray, aItemMarkup, aSpacingMarkup), "sourceUpdates": aArray}, aChildren);
}
} |
JavaScript | class NormalState extends State {
constructor(context, options){
super(context, options);
}
/**
*
*
* @method bindState
*/
bindState() {
this.context_.addClass('ntk-normal-state');
}
/**
* Disposes state properties
*
* @method disposeState
*/
disposeState() {
this.context_.removeClass('ntk-normal-state');
}
} |
JavaScript | class LocalStorageProvider extends StorageProvider {
/**
* Initializes a new client to interact with Minio.
*
* @param options - Dictionary with storage options.
*/
constructor(options) {
if (!options || !Object.keys(options).length) {
throw new Error('Options argument is empty');
}
if (!options.signingFn) {
throw new Error('Signing function (options.signingFn) is empty');
}
super(null);
this._provider = 'localstorage';
this._basePath = options.basePath || __dirname;
this._signingFn = options.signingFn || (() => {});
this._client = module.exports;
}
/**
* ~~Create a container ("bucket") on the server.~~
* Does nothing because localstorage doesn't use containers.
*
* @param container - An unused variable, only here for compatibility
* @param options - An unused variable, only here for compatibility
* @returns An empty resolved promise.
* @async
*/
createContainer(container, options) {
return Promise.resolve();
}
/**
* ~~Check if a container exists.~~
* Does nothing because localstorage doesn't use containers.
*
* @param container - An unused variable, only here for compatibility
* @returns A promise that always resolves to fasle.
* @async
*/
isContainer(container) {
return Promise.resolve(false);
}
/**
* ~~Create a container ("bucket") on the server if it doesn't already exist.~~
* Does nothing because localstorage doesn't use containers.
*
* @param container - An unused variable, only here for compatibility
* @param options - An unused variable, only here for compatibility
* @returns An empty resolved promise.
* @async
*/
ensureContainer(container, options) {
return Promise.resolve();
}
/**
* ~~Lists all containers belonging to the user~~
* Does nothing because localstorage doesn't use containers.
*
* @returns A promise that resolves to an empty array.
* @async
*/
listContainers() {
return Promise.resolve([]);
}
/**
* ~~Removes a container from the server~~
* Does nothing because localstorage doesn't use containers.
*
* @param container - An unused variable, only here for compatibility
* @returns An empty resolved promise.
* @async
*/
deleteContainer(container) {
return Promise.resolve();
}
/**
* Uploads a stream to the object storage server
*
* @param container - An unused variable, only here for compatibility
* @param path - Path where to store the object, relative to the base path
* @param data - Object data or stream. Can be a Stream (Readable Stream), Buffer or string.
* @param options - Key-value pair of options used by providers, including the `metadata` dictionary
* @returns Promise that resolves once the object has been uploaded
* @async
*/
async putObject(container, path, data, options) {
path = pathLib.join(this._basePath, sanitisePath(path));
await mkdir(pathLib.dirname(path));
if (data instanceof Stream || data instanceof Buffer || typeof data === "string") {
return fs.promises.writeFile(path, data);
} else {
return Promise.reject(new Error('Data must be a stream, buffer or string'));
}
}
/**
* Requests an object from the server. The method returns a Promise that resolves to a Readable Stream containing the data.
*
* @param container - An unused variable, only here for compatibility
* @param path - Path of the object, relative to the base path
* @returns A promise resolving to a Readable Stream containing the object's data
* @async
*/
getObject(container, path) {
// Open the file at basePath + path
path = pathLib.join(this._basePath, sanitisePath(path));
try {
let s = fs.createReadStream(path);
return Promise.resolve(s);
} catch (e) {
return Promise.reject(e);
}
}
/**
* Returns a list of objects with a given prefix (folder). The list is not recursive, so prefixes (folders) are returned as such.
*
* @param container - An unused variable, only here for compatibility
* @param path - Path resolving to a folder, relative to the base path
* @returns List of elements returned by the server
* @async
*/
listObjects(container, path) {
path = pathLib.join(this._basePath, sanitisePath(path));
try {
if (fs.statSync(path).isDirectory()) {
let files = fs.readdirSync(path);
let items = [];
for (let file of files) {
let fullPath = pathLib.join(path, file);
let stats = fs.statSync(fullPath);
if (stats.isDirectory()) {
items.push({
prefix: file
});
} else {
items.push({
path: file,
size: stats.size,
lastModified: stats.mtime,
creationTime: stats.ctime,
});
}
}
return Promise.resolve(items);
} else throw new Error(`Path ${path} is not a directory`);
} catch (e) {
return Promise.reject(e);
}
}
/**
* Removes an object from the server
*
* @param container - An unused variable, only here for compatibility
* @param path - Path of the object, relative to the base path
* @returns Promise that resolves once the object has been removed
* @async
*/
deleteObject(container, path) {
path = pathLib.join(this._basePath, sanitisePath(path));
return fs.promises.rm(path);
}
/**
* Returns a URL that clients (e.g. browsers) can use to request an object from the server with a GET request,
* even if the object is private.
*
* This does no checking to ensure that the object exists!
*
* @param container - An unused variable, only here for compatibility
* @param path - Path of the object, relative to the base path
* @param ttl - Expiry time of the URL, in seconds (default: 1 day)
* @returns Promise that resolves with the pre-signed URL for GET requests
* @async
*/
presignedGetUrl(container, path, ttl) {
ttl = !!ttl && ttl > 0 ? ttl : 86400;
return Promise.resolve(this._signingFn("get", path, ttl));
}
/**
* Returns a URL that clients (e.g. browsers) can use for PUT operations on an object in the server, even if
* the object is private.
*
* This does no checking to ensure that the object doesn't exist!
*
* @param container - An unused variable, only here for compatibility
* @param path - Path of the object, relative to the base path
* @param options - An unused variable, only here for compatibility
* @param ttl - Expiry time of the URL, in seconds (default: 1 day)
* @returns Promise that resolves with the pre-signed URL for GET requests
* @async
*/
presignedPutUrl(container, path, options, ttl) {
ttl = !!ttl && ttl > 0 ? ttl : 86400;
return Promise.resolve(this._signingFn("put", path, ttl));
}
} |
JavaScript | class MongoDbQueue {
constructor(mongoDb, name, opts = {}) {
if (!mongoDb) {
throw new Error('mongodb-queue: provide a mongodb.MongoClient.db');
}
if (!name) {
throw new Error('mongodb-queue: provide a queue name');
}
this.name = name;
this.col = mongoDb.collection(name);
this.visibility = opts.visibility || 30;
this.delay = opts.delay || 0;
if (opts.deadQueue) {
this.deadQueue = opts.deadQueue;
this.maxRetries = opts.maxRetries || 5;
}
}
// ----------------------------------------------------------------------
async createIndexes() {
return [
await this.col.createIndex({deleted: 1, visible: 1}),
await this.col.createIndex({ack: 1}, {unique: true, sparse: true}),
];
}
// ----------------------------------------------------------------------
async add(payload, opts = {}) {
const delay = opts.delay || this.delay;
const visible = delay ? nowPlusSecs(delay) : now();
if (payload instanceof Array) {
// Insert many
if (payload.length === 0) {
const errMsg = 'Queue.add(): Array payload length must be greater than 0';
throw new Error(errMsg);
}
const messages = payload.map((payload) => {
return {
visible: visible,
payload: payload,
};
});
const result = await this.col.insertMany(messages);
// These need to be converted because they're in a weird format.
const insertedIds = [];
for (const key of Object.keys(result.insertedIds)) {
const numericKey = +key;
insertedIds[numericKey] = `${result.insertedIds[key]}`;
}
return insertedIds;
} else {
// insert one
const result = await this.col.insertOne({
visible: visible,
payload: payload,
});
return result.insertedId;
}
}
// ----------------------------------------------------------------------
async get(opts = {}) {
const visibility = opts.visibility || this.visibility;
const query = {
deleted: null,
visible: {$lte: now()},
};
const sort = {
_id: 1
};
const update = {
$inc: {tries: 1},
$set: {
ack: id(),
visible: nowPlusSecs(visibility),
}
};
const result = await this.col.findOneAndUpdate(query, update, {sort: sort, returnOriginal: false});
let msg = result.value;
if (!msg) return;
// convert to an external representation
msg = {
// convert '_id' to an 'id' string
id: `${msg._id}`,
ack: msg.ack,
payload: msg.payload,
tries: msg.tries,
};
// if we have a deadQueue, then check the tries, else don't
if (this.deadQueue) {
// check the tries
if (msg.tries > this.maxRetries) {
// So:
// 1) add this message to the deadQueue
// 2) ack this message from the regular queue
// 3) call ourself to return a new message (if exists)
await this.deadQueue.add(msg);
await this.ack(msg.ack);
return await this.get(opts);
}
}
return msg;
}
// ----------------------------------------------------------------------
async ping(ack, opts = {}) {
const visibility = opts.visibility || this.visibility;
const query = {
ack: ack,
visible: {$gt: now()},
deleted: null,
};
const update = {
$set: {
visible: nowPlusSecs(visibility)
}
};
const msg = await this.col.findOneAndUpdate(query, update, {returnOriginal: false});
if (!msg.value) {
throw new Error('Queue.ping(): Unidentified ack : ' + ack);
}
return `${msg.value._id}`;
}
// ----------------------------------------------------------------------
async ack(ack) {
const query = {
ack: ack,
visible: {$gt: now()},
deleted: null,
};
const update = {
$set: {
deleted: now(),
}
};
const msg = await this.col.findOneAndUpdate(query, update, {returnOriginal: false});
if (!msg.value) {
throw new Error('Queue.ack(): Unidentified ack : ' + ack);
}
return `${msg.value._id}`;
}
// ----------------------------------------------------------------------
async nack(ack, opts = {}) {
const delay = opts.delay || this.delay;
const query = {
ack: ack,
visible: {$gt: now()},
deleted: null,
};
const update = {
$set: {
visible: nowPlusSecs(delay),
},
$unset: {
ack: '',
}
};
const msg = await this.col.findOneAndUpdate(query, update, {returnOriginal: false});
if (!msg.value) {
throw new Error('Queue.nack(): Unidentified ack : ' + ack);
}
return `${msg.value._id}`;
}
// ----------------------------------------------------------------------
async clean() {
const query = {
deleted: {$exists: true},
};
return await this.col.deleteMany(query);
}
// ----------------------------------------------------------------------
async total() {
return await this.col.count();
}
// ----------------------------------------------------------------------
async size() {
const query = {
deleted: null,
visible: {$lte: now()},
};
return await this.col.count(query);
}
// ----------------------------------------------------------------------
async inFlight() {
const query = {
ack: {$exists: true},
visible: {$gt: now()},
deleted: null,
};
return await this.col.count(query);
}
// ----------------------------------------------------------------------
async done() {
const query = {
deleted: {$exists: true},
};
return await this.col.count(query);
}
} |
JavaScript | class ManPage extends FBP(LitElement) {
constructor() {
super();
}
/**
* flow is ready lifecycle method
*/
_FBPReady() {
super._FBPReady();
//this._FBPTraceWires()
}
/**
* Themable Styles
* @private
* @return {CSSResult}
*/
static get styles() {
// language=CSS
return Theme.getThemeForComponent(this.name) || css`
:host {
display: block;
background: var(--surface);
padding: 16px 140px 24px 24px;
height: 100%;
overflow: auto;
box-sizing: border-box;
}
:host([hidden]) {
display: none;
}
a.close {
position: absolute;
right: 24px;
top: 16px;
outline: none;
}
h1 {
margin-top: 0;
}
`
}
/**
* @private
* @returns {TemplateResult}
* @private
*/
render() {
// language=HTML
return html`
<h1>man viz.furo.pro </h1>
<p><strong>v 1.6.1</strong></p>
<p>With viz.furo.pro you can inspect fbp flows. You can paste in the template from your source code or paste
live flows from your running apps.</p>
<p>When you start the app, you will see the current flow of viz.furo.pro itself.</p>
<h3>Getting the template from running apps</h3>
<ol>
<li>Select the element in the elements tab of your chrome dev toos</li>
<li>type in <strong>copy($0.shadowRoot.innerHTML)</strong>
in the console.
</li>
<li>Then paste the received content (already in clipboard) in viz.furo.pro to inspect live apps</li>
</ol>
<h2>Reading the flow graph</h2>
<p>If you are familiar with fbp, you should not have any problem to read the graph. Otherwise we recommend to read
<a target="_blank" href="https://furo.pro/guide/md/fbp-wires/">the guide</a> to learn more about</p>
<p>The <strong>boxes</strong> represent the used components.</p>
<p> Boxes with <strong>dashed lines</strong> have a comment in the source. Hover on the box to read the comment
</p>
<p>The <strong>blue lines</strong> are the wires. Hover on them to read the wire name, like --clipboardContent.
</p>
<p>The <strong>small blue boxes</strong> with an <strong>@-</strong> are the catched events. Hover on them to read
the used name and more.</p>
<p>The <strong>small green boxes</strong> with an <strong>ƒ-</strong> are the triggerer for the methods of the
component.</p>
<p>The <strong>small black boxes</strong> are <strong>boolean</strong> flags of the component which are setted.
</p>
<p>The <strong>small orange boxes</strong> are <strong>string</strong> attributes of the component which are
setted. Hover on them to read the setted string.</p>
<p>The <strong>orange dots</strong> are indicating a wire from nowhere or a wire which was triggered from the
source (like <strong>this._FBPTriggerWire("--dataReceived",data)</strong>) or from outside (like <strong>--pageEntered</strong>
from furo-pages).
</p>
<p>The <strong>orange dots</strong> are indicating a wire which goes nowhere or a wire which is cathced in the
source
(like <strong>this._FBPAddWireHook("--wireName",(e)=>{ ... });</strong></p>
<h2>Keyboard shortcuts</h2>
<p><strong>f</strong> on the buttons toggles the fullscreen mode. Press "esc" to get back.</p>
<p><strong>ctrl v</strong> or <strong>cmd v</strong> renders the clipboard content.</p>
<p><strong>enter</strong> on the navigation buttons or arrow-left, arrow-right ◀, ▶ re renders the last pasted content.</p>
<p><strong>enter</strong> on the ✘ button or Backspace removes the current view.</p>
<p><strong>enter</strong> on the parse button renders the clipboard content.</p>
<h2>Mouse controls</h2>
<p><strong>scroll down</strong> zooms the flow in.</p>
<p><strong>scroll up</strong> zooms the out.</p>
<p><strong>moving the mouse with mousedown</strong> pans the flow.</p>
<h2>Touch controls</h2>
<p><strong>pinch in</strong> zooms the flow in.</p>
<p><strong>pinch out</strong> zooms the flow out.</p>
<p><strong>paning</strong> (with 2 fingers) pans the flow.</p>
<a class="close" href="/">
<furo-button outline>close help</furo-button>
</a>
`;
}
} |
JavaScript | class GalacticAge {
constructor() {
this.mercury = .24;
this.venus = .62;
this.mars = 1.88;
this.jupiter = 11.86;
}
// Age on Mercury
mercuryCalc(earthAge) {
return Math.floor(earthAge / this.mercury);
}
// Age on Venus
venusCalc(earthAge) {
return Math.floor(earthAge / this.venus);
}
// Age on Jars
marsCalc(earthAge) {
return Math.floor(earthAge / this.mars);
}
// Age on Jupiter
jupiterCalc(earthAge) {
return Math.floor(earthAge / this.jupiter);
}
// Life expectany on Mercury
leMercury(earthAge) {
return Math.floor(earthAge / this.mercury);
}
// Life expectany on Venus
leVenus(earthAge) {
return Math.floor(earthAge / this.venus);
}
// Life expectany on Mars
leMars(earthAge) {
return Math.floor(earthAge / this.mars);
}
// Life expectancy on Jupiter
leJupiter(earthAge) {
return Math.floor(earthAge / this.jupiter);
}
} |
JavaScript | class LogWatcher extends events.EventEmitter {
/**
* Construct the log watcher.
* @param dirpath {string} The directory to watch.
* @param maxfiles {number} Maximum amount of files to process.
* @param ignoreInitial {boolean} Ignore initial read or not.
*/
constructor(dirpath, maxfiles, ignoreInitial) {
super();
this._dirpath = dirpath || DEFAULT_SAVE_DIR;
this._filter = isCommanderLog;
this._maxfiles = maxfiles || 3;
this._logDetailMap = {};
this._ops = [];
this._op = null;
this._startTime = new Date();
this._timer = null;
this._die = false;
this._ignoreInitial = ignoreInitial || false;
this.stopped = false;
this._loop();
this.emit('Started');
}
/**
* Bury a file
* @param filename {string} File to bury.
*/
bury(filename) {
debug('bury', {filename});
this._logDetailMap[filename].tombstoned = true;
}
/**
* Stop running
*/
stop() {
debug('stop');
if (this._op === null) {
clearTimeout(this._timer);
this.stopped = true;
this.emit('stopped');
} else {
this._ops.splice(this._ops.length);
this.stopped = true;
this._die = true;
}
}
/**
* The main loop
*/
_loop() {
debug('_loop', {opcount: this._ops.length});
this._op = null;
if (this._ops.length === 0) {
this._timer = setTimeout(() => {
this._ops.push(callback => this._poll(callback));
setImmediate(() => this._loop());
}, POLL_INTERVAL);
return;
}
this._op = this._ops.shift();
try {
this._op(err => {
if (err) {
this.emit('error', err);
} else if (this._die) {
this.emit('stopped');
} else {
setImmediate(() => this._loop());
}
});
} catch (err) {
this.emit('error', err);
// Assumption: it crashed BEFORE an async wait
// otherwise, we'll end up with more simultaneous
// activity
setImmediate(() => this._loop());
}
}
/**
* Poll the logs directory for new/updated files.
* @param callback {function}
*/
_poll(callback) {
debug('_poll');
const unseen = {};
Object.keys(this._logDetailMap).forEach(filename => {
if (!this._logDetailMap[filename].tombstoned) {
unseen[filename] = true;
}
});
fs.readdir(this._dirpath, (err, filenames) => {
if (err) {
callback(err);
} else {
let counter = this._maxfiles;
for (let i = filenames.length - 1; i >= 0 && counter; i--) {
let filename = path.join(this._dirpath, filenames[i]);
if (this._filter(filename)) {
counter--;
delete unseen[filename];
this._ops.push(cb => this._statfile(filename, cb));
}
}
Object.keys(unseen).forEach(filename => {
this.bury(filename);
});
callback(null);
}
});
}
/**
* Stat the new/updated files in log directory
* @param filename {string} Path to file to get stats of.
* @param callback
*/
_statfile(filename, callback) {
debug('_statfile', {filename});
fs.stat(filename, (err, stats) => {
if (err && err.code === 'ENOENT') {
if (this._logDetailMap[filename]) {
this.bury(filename);
}
callback(null); // File deleted
} else if (err) {
callback(err);
} else {
this._ops.push(cb => this._process(filename, stats, cb));
callback(null);
}
});
}
/**
* Process the files
* @param filename {string} Filename to check
* @param stats {object} Last modified etc
* @param callback {function}
*/
_process(filename, stats, callback) {
debug('_process', {filename});
let CURRENT_FILE = 0;
setImmediate(callback, null);
const info = this._logDetailMap[filename];
if (this._ignoreInitial && stats.mtime < this._startTime) {
return
}
if (info === undefined && CURRENT_FILE < this._maxfiles) {
this._logDetailMap[filename] = {
ino: stats.ino,
mtime: stats.mtime,
size: stats.size,
watermark: 0,
tombstoned: false
};
CURRENT_FILE++;
this._ops.push(cb => this._read(filename, cb));
return;
}
if (info.tombstoned) {
return;
}
if (info.ino !== stats.ino) {
// File replaced... can't trust it any more
// if the client API supported replay from scratch, we could do that
// but we can't yet, so:
CURRENT_FILE = 0;
this.bury(filename);
} else if (stats.size > info.size) {
// File not replaced; got longer... assume append
this._ops.push(cb => this._read(filename, cb));
} else if (info.ino === stats.ino && info.size === stats.size) {
// Even if mtime is different, treat it as unchanged
// e.g. ^Z when COPY CON to a fake log
// don't queue read
}
info.mtime = stats.mtime;
info.size = stats.size;
}
/**
* Read the files
* @param filename {string} The filename to read.
* @param callback {function}
*/
_read(filename, callback) {
const {watermark, size} = this._logDetailMap[filename];
debug('_read', {filename, watermark, size});
let leftover = Buffer.from('', 'utf8');
const s = fs.createReadStream(filename, {
flags: 'r',
start: watermark,
end: size
});
const finish = err => {
if (err) {
// On any error, emit the error and bury the file.
this.emit('error', err);
this.bury(filename);
}
setImmediate(callback, null);
callback = () => {
}; // No-op
};
s.once('error', finish);
s.once('end', finish);
s.on('data', chunk => {
const idx = chunk.lastIndexOf('\n');
if (idx < 0) {
leftover = Buffer.concat([leftover, chunk]);
} else {
this._logDetailMap[filename].watermark += idx + 1;
try {
const obs = Buffer.concat([leftover, chunk.slice(0, idx + 1)])
.toString('utf8')
.replace(/\u000e/igm, '')
.replace(/\u000f/igm, '')
.split(/[\r\n]+/)
.filter(l => l.length > 0)
.map(l => {
try {
return JSON.parse(l)
} catch (e) {
debug('json.parse error', {line: l});
}
});
leftover = chunk.slice(idx + 1);
if (obs) {
debug('data emit');
setImmediate(() => this.emit('data', obs) && this.emit('finished'));
} else {
debug('data emit');
setImmediate(() => this.emit('data', {}) && this.emit('finished'));
}
} catch (err) {
finish(err);
}
}
});
}
} |
JavaScript | class Version {
constructor(siteId) {
this.siteId = siteId;
this.counter = 0;
this.exceptions = [];
}
// Update a site's version based on the incoming operation that was processed
// If the incomingCounter is less than we had previously processed, we can remove it from the exceptions
// Else if the incomingCounter is the operation immediately after the last one we procesed, we just increment our counter to reflect that
// Else, add an exception for each counter value that we haven't seen yet, and update our counter to match
update(version) {
const incomingCounter = version.counter;
if (incomingCounter <= this.counter) {
const index = this.exceptions.indexOf(incomingCounter);
this.exceptions.splice(index, 1);
} else if (incomingCounter === this.counter + 1) {
this.counter = this.counter + 1;
} else {
for (let i = this.counter + 1; i < incomingCounter; i++) {
this.exceptions.push(i);
}
this.counter = incomingCounter;
}
}
} |
JavaScript | class HXBeaconElement extends HXElement {
static get is () {
return 'hx-beacon';
}
static get template () {
return `<style>${shadowStyles}</style>${shadowMarkup}`;
}
$onCreate () {
this._onDismiss = this._onDismiss.bind(this);
}
$onConnect () {
this._btnDismiss.addEventListener('click', this._onDismiss);
}
$onDisconnect () {
this._btnDismiss.removeEventListener('click', this._onDismiss);
}
/**
* Dismiss the beacon (removes element from the DOM)
*/
dismiss () {
if (this.$emit('dismiss')) {
this.remove();
}
}
/** @private */
_onDismiss () {
this.dismiss();
}
/** @private */
get _btnDismiss () {
return this.shadowRoot.getElementById('hxDismiss');
}
} |
JavaScript | class PlanForm extends Component {
static propTypes = {
isEditForm: PropTypes.bool.isRequired,
plan: PropTypes.shape({
name: PropTypes.string,
title: PropTypes.string,
abbreviation: PropTypes.string,
mobile: PropTypes.string,
email: PropTypes.string,
}).isRequired,
form: PropTypes.shape({ getFieldDecorator: PropTypes.func }).isRequired,
onCancel: PropTypes.func.isRequired,
posting: PropTypes.bool.isRequired,
};
/**
* @function
* @name handleSubmit
* @description Handle submit form action
*
* @param {Object} event onSubmit event object
*
* @version 0.1.0
* @since 0.1.0
*/
handleSubmit = event => {
event.preventDefault();
const {
form: { validateFieldsAndScroll },
plan,
isEditForm,
} = this.props;
validateFieldsAndScroll((error, values) => {
if (!error) {
if (isEditForm) {
const updatedPlan = Object.assign({}, plan, values);
putPlan(
updatedPlan,
() => {
notifySuccess('Plan was updated successfully');
},
() => {
notifyError(
'Something occurred while updating plan, please try again!'
);
}
);
} else {
postPlan(
values,
() => {
notifySuccess('Plan was created successfully');
},
() => {
notifyError(
'Something occurred while saving plan, please try again!'
);
}
);
}
}
});
};
render() {
const {
isEditForm,
plan,
posting,
onCancel,
form: { getFieldDecorator },
} = this.props;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 24 },
md: { span: 24 },
lg: { span: 24 },
xl: { span: 24 },
xxl: { span: 24 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 24 },
md: { span: 24 },
lg: { span: 24 },
xl: { span: 24 },
xxl: { span: 24 },
},
};
return (
<Form onSubmit={this.handleSubmit} autoComplete="off">
{/* plan incident type */}
<Form.Item label="Incident Type" {...formItemLayout}>
{getFieldDecorator('incidentType', {
rules: [
{
required: true,
message: 'Please Select Plan Incident Type',
},
],
initialValue: isEditForm ? plan.incidentType._id : undefined, //eslint-disable-line
})(
<SearchableSelectInput
placeholder="Select Incident Type ..."
onSearch={getIncidentTypes}
optionLabel="name"
optionValue="_id"
initialValue={isEditForm ? plan.incidentType : undefined}
/>
)}
</Form.Item>
{/* end plan incident type */}
{/* plan owner */}
<Form.Item label="Owner" {...formItemLayout}>
{getFieldDecorator('owner', {
rules: [
{
required: true,
message: 'Please Select the Plan Owner',
},
],
initialValue: isEditForm ? plan.owner._id : undefined, //eslint-disable-line
})(
<SearchableSelectInput
placeholder="Select Plan Owner ..."
onSearch={getFocalPeople}
optionLabel="name"
optionValue="_id"
initialValue={isEditForm ? plan.owner : undefined}
/>
)}
</Form.Item>
{/* end plan owner */}
{/* plan boundary input */}
<Form.Item label="Plan Applicable Area" {...formItemLayout}>
{getFieldDecorator('boundary', {
rules: [
{
required: true,
message: 'Please Select the Plan Applicable Area',
},
],
initialValue: isEditForm ? plan.boundary._id : undefined, // eslint-disable-line
})(
<SearchableSelectInput
placeholder="Select Plan Boundary ..."
onSearch={getFeatures}
optionValue="_id"
optionLabel={feature =>
`${feature.name} (${upperFirst(feature.type)})`
}
initialValue={isEditForm ? plan.boundary : undefined}
/>
)}
</Form.Item>
{/* end plan boundary input */}
{/* form actions */}
<Form.Item wrapperCol={{ span: 24 }} style={{ textAlign: 'right' }}>
<Button onClick={onCancel}>Cancel</Button>
<Button
style={{ marginLeft: 8 }}
type="primary"
htmlType="submit"
loading={posting}
>
Save
</Button>
</Form.Item>
{/* end form actions */}
</Form>
);
}
} |
JavaScript | class CommandHandler {
/**
* The command handler class for the client. Saves or updates commands and categories to the command and category collections, as well as running permission/cooldown checks.
* @param {AstronClient} client
* @param {import("discord-astron").CommandHandlerOptions} commandHandlerOptions The options for the command handler
*/
constructor(client, commandHandlerOptions) {
/**
* The Astron client.
* @type {AstronClient}
*/
this.client = client;
/**
* The directory of commands to save to the command collection and execute.
* @type {string}
*/
this.directory = commandHandlerOptions.directory;
/**
* The prefix for triggering commands.
* @type {string | Function}
*/
this.prefix = commandHandlerOptions.prefix;
/**
* Determines whether to block bots from using commands.
* @type {boolean}
*/
this.blockBots = commandHandlerOptions.blockBots || true;
/**
* Determines whether to allow commands run in direct message channels.
* @type {boolean}
*/
this.allowDirectMessages = commandHandlerOptions.allowDirectMessages || true;
/**
* Determines whether the client's user mention can be used as a prefix.
* @type {boolean}
*/
this.allowMention = commandHandlerOptions.allowMention || true;
/**
* The message to send upon a user running commands in direct messages if disabled.
* @type {string | Function}
*/
this.directMessageWarning = commandHandlerOptions.directMessageWarning;
/**
* A message to warn a user when a command only meant to be used in servers is run in a dm.
* @type {string | Function}
*/
this.guildOnlyWarning = commandHandlerOptions.guildOnlyWarning;
/**
* A message to warn a non-owner running a owner only command.
* @type {string | Function}
*/
this.ownerOnlyWarning = commandHandlerOptions.ownerOnlyWarning;
/**
* Sends a warning message to the dm of the user who runs a command but the client is missing the SEND_MESSAGES permission.
* @type {string | Function}
*/
this.missingSendPermissions = commandHandlerOptions.missingSendPermissions;
/**
* Sends a message to the user if the client is missing permissions for a command.
* @type {string | Function}
*/
this.clientPermissionsMissing = commandHandlerOptions.clientPermissionsMissing;
/**
* Sends a message to the user if the user is missing permissions for a command.
* @type {string | Function}
*/
this.userPermissionsMissing = commandHandlerOptions.userPermissionsMissing;
/**
* Warns a user when the person executing the command exceeds the cooldown limit.
* @type {string | Function}
*/
this.cooldownMessage = commandHandlerOptions.cooldownWarning;
/**
* The command collection to store the commands for the client.
* @type {Discord.Collection}
*/
this.commands = new Discord.Collection();
/**
* The command alias collection to store command name aliases for each command.
* @type {Discord.Collection}
*/
this.aliases = new Discord.Collection();
/**
* The collection of command cooldowns.
* @type {Collection}
*/
this.commandCooldowns = new Discord.Collection();
/**
* The collection of command categories.
* @type {Collection}
*/
this.categories = new Discord.Collection();
/**
* Executes the command using the provided parameters.
* @param {any[]} [args] The commnad parameters
* @type {Promise<void>}
*/
this.load = async () => {
try {
// Sets or updates categories and commands to the command and categories collections.
const categories = ["configuration", "information"];
categories.forEach(async category => {
this.categories.set(await this.client.util.capitalize(category), new Category(await this.client.util.capitalize(category), null)); // Creates category classes for each category.
});
for (const category of categories.values()) {
for (const command of readdirSync(`${this.directory}/${category.toLowerCase()}`).filter(fileName => fileName.endsWith(".js"))) { // Creates a constant for each command file.
const commandFile = require(`${this.directory}/${category.toLowerCase()}/${command}`); // The command file.
this.commands.set(new commandFile(this.client).id.toLowerCase(), commandFile); // Creates a new instance of the command class exported from the command file and sets it to the command collection.
if (new commandFile(this.client).aliases) {
for (const alias of new commandFile(this.client).aliases) {
this.aliases.set(alias, commandFile); // Checks if command aliases found, if so, sets command aliases to the alias collection.
};
};
};
this.categories.set(await this.client.util.capitalize(category), new Category(await this.client.util.capitalize(category), this.commands.filter(async cmd => new cmd(this.client).categoryID.toLowerCase() === category.toLowerCase()))); // Sets the commands with matching categories to each category in the category collection.
console.log(`${await this.client.util.time()} | [ ${await this.client.util.capitalize(category)} Module ] Loaded ${readdirSync(`${this.directory}/${category}`).length} command(s)`); // Logs successful message to the console.
};
// Message event
this.client.on("message", async (message) => {
if (message.author.bot && this.blockBots === true) return; // Checks if the author is a bot user.
const escapeRegex = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // Mention regex function.
const prefixRegex = new RegExp(`^(<@!?${this.client.user.id}>|${escapeRegex(typeof this.prefix === "function" ? (await this.prefix(message)) : this.prefix)})\\s*`); // The prefix.
if (!prefixRegex.test(message.content)) return; // Checks if the content of the message includes either the prefix for mention prefix.
const [, matchedPrefix] = message.content.match(prefixRegex); // Also checks if the content of the message includes either the prefix for mention prefix.
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/g); // The arguments in the command input.
const commandName = args.shift().toLowerCase(); // Retrieves the command name from the provided argument input.
const command = this.commands.get(commandName) || this.aliases.get(commandName); // The command object.
if (!command) return; // Checks if the command exists.
const cmd = new command(this.client); // Creates a new instance of the command class.
// Channel and permissions checks
if (message.channel.type === "dm" && !this.allowDirectMessages === false && cmd.channel === "guild") return message.channel.send(typeof this.directMessageWarning === 'function' ? this.directMessageWarning(message) : this.directMessageWarning);
if (message.channel.type === "text" && cmd.channel === "dm") return message.channel.send(typeof this.guildOnlyWarning === 'function' ? this.guildOnlyWarning(message) : this.guildOnlyWarning);
if (cmd.ownerOnly && !this.client.config.owners.includes(message.author.id)) return message.channel.send(typeof this.ownerOnlyWarning === 'function' ? this.ownerOnlyWarning(message) : this.ownerOnlyWarning);
if (message.guild && !message.channel.permissionsFor(message.guild.me).toArray().includes("SEND_MESSAGES")) return message.author.send(typeof this.missingSendPermissions === 'function' ? this.missingSendPermissions(message) : this.missingSendPermissions);
if (message.guild && cmd.clientPermissions && !message.guild.me.permissions.has(cmd.clientPermissions)) return message.channel.send(typeof this.clientPermissionsMissing === 'function' ? this.clientPermissionsMissing(message, message.guild.me.permissions.missing(cmd.clientPermissions).length > 1 ? `${message.guild.me.permissions.missing(cmd.clientPermissions).slice(0, -1).map(perm => `\`${perm}\``).join(', ')} and \`${message.guild.me.permissions.missing(cmd.clientPermissions).slice(-1)[0]}\`` : `\`${message.guild.me.permissions.missing(cmd.clientPermissions)[0]}\``) : this.clientPermissionsMissing);
if (message.guild && cmd.userPermissions && !message.member.permissions.has(cmd.userPermissions) && !cmd.ignorePermissions.includes(message.author.id)) return message.channel.send(typeof this.userPermissionsMissing === 'function' ? this.userPermissionsMissing(message, message.member.permissions.missing(cmd.userPermissions).length > 1 ? `${message.member.permissions.missing(cmd.userPermissions).slice(0, -1).map(perm => `\`${perm}\``).join(', ')} and \`${message.member.permissions.missing(cmd.userPermissions).slice(-1)[0]}\`` : `\`${message.member.permissions.missing(cmd.userPermissions)[0]}\``) : this.userPermissionsMissing);
// Commands run in a server.
if (message.guild) {
// Cooldown checks.
if (!this.commandCooldown.has(cmd.id)) this.commandCooldown.set(cmd.id, new Discord.Collection());
const now = Date.now();
const timestamps = this.commandCooldown.get(cmd.id);
const cooldownAmount = (cmd.cooldown || 3) * 1000;
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
const timeLeft = (expirationTime - now) / 1000;
if (timestamps.has(message.author.id) && !this.client.config.owners.includes(message.author.id) && (now < expirationTime) && !cmd.ignoreCooldown.includes(message.author.id)) return message.channel.send(typeof this.cooldownMessage === "function" ? this.cooldownMessage(message, timeLeft.toFixed(1), cmd) : this.cooldownMessage);
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
};
return cmd.exec(this.client, message, args, Discord); // Executing the command.
});
// Error handling.
this.client.on("error", (err) => console.log(`[ AstronClient ] ${err}`)); // discord.js client error event.
process.on("unhandledRejection", async (err) => console.error('Unhandled Rejection:', err)); // Node process unhandledRejection event. Called when a promise is rejected.
} catch (err) {
return console.log(`[ AstronClient ] ${err.stack}`); // Logging any errors with the command handler to the console.
};
};
/**
* Fetches a command via parameters and reloads it.
* @param {string | import("discord-astron").Command} command The command to search for
* @type {Promise<void>}
*/
this.reloadCommand = async (command) => {
const commandFile = require(`${this.directory}/${command}.js`); // The command file.
this.commands.set(new commandFile(this.client).id, commandFile); // Sets the command to the command collection.
if (new commandFile(this.client).aliases) for (const alias of new commandFile(this.client).aliases) {
this.aliases.set(alias, commandFile); // Checks for aliases, if found, sets them to the aliases collection.
};
};
/**
* Fetches all commands and reloads them.
* @type {Promise<void>}
*/
this.reloadAll = async () => {
for (const command of readdirSync(this.directory).filter(fileName => fileName.endsWith(".js"))) {
const commandFile = require(`${this.directory}/${command}`); // The command files.
this.commands.set(new commandFile(this.client).id, commandFile); // Sets the commands from each command file to the command collection.
if (new commandFile(this.client).aliases) for (const alias of new commandFile(this.client).aliases) {
this.aliases.set(alias, commandFile); // Checks for aliases in each command file, if found, sets them to the aliases collection.
};
};
};
/**
* Fetches a certain command by searching through the command collection
* @param {string | Command} command
* @type {Promise<Command>}
*/
this.fetchCommand = async (searchQuery) => {
const command = this.commands.get(searchQuery.toLowerCase()) || this.aliases.get(searchQuery.toLowerCase()); // Searches for the command in the commands or aliases collection/
return new command();
};
};
} |
JavaScript | class AuthRoute {
constructor() {
this.router = require('express').Router()
this.controllerAuth = require('../controllers/AuthController');
this.setAuth();
}
setAuth() {
const AuthRoute = this;
this.router.use(function (req, res, next) {
AuthRoute.controllerAuth.middleWare(req, res, next);
})
}
} |
JavaScript | class ParameterValueChange extends Change {
/**
* Creates an instance of ParameterValueChange.
*
* @param {Parameter} param - The param value.
* @param {object|string|number|any} newValue - The newValue value.
*/
constructor(param, newValue) {
if (param) {
super(param ? param.getName() + ' Changed' : 'ParameterValueChange')
this.__prevValue = param.getValue()
this.__param = param
if (newValue != undefined) {
this.__nextValue = newValue
this.__param.setValue(this.__nextValue)
}
} else {
super()
}
this.suppressPrimaryChange = false
this.secondaryChanges = []
}
/**
* Rollbacks the value of the parameter to the previous one, passing it to the redo stack in case you wanna recover it later on.
*/
undo() {
if (!this.__param) return
if (!this.suppressPrimaryChange) this.__param.setValue(this.__prevValue)
this.secondaryChanges.forEach((change) => change.undo())
}
/**
* Rollbacks the `undo` action by moving the change from the `redo` stack to the `undo` stack
* and updating the parameter with the new value.
*/
redo() {
if (!this.__param) return
if (!this.suppressPrimaryChange) this.__param.setValue(this.__nextValue)
this.secondaryChanges.forEach((change) => change.redo())
}
/**
* Updates the state of the current parameter change value.
*
* @param {Parameter} updateData - The updateData param.
*/
update(updateData) {
if (!this.__param) return
this.__nextValue = updateData.value
this.__param.setValue(this.__nextValue)
this.emit('updated', updateData)
}
/**
* Serializes `Parameter` instance value as a JSON object, allowing persistence/replication.
*
* @param {object} context - The context param.
* @return {object} The return value.
*/
toJSON(context) {
const j = {
name: this.name,
paramPath: this.__param.getPath(),
}
if (this.__nextValue != undefined) {
if (this.__nextValue.toJSON) {
j.value = this.__nextValue.toJSON()
} else {
j.value = this.__nextValue
}
}
return j
}
/**
* Restores `Parameter` instance's state with the specified JSON object.
*
* @param {object} j - The j param.
* @param {object} context - The context param.
*/
fromJSON(j, context) {
const param = context.appData.scene.getRoot().resolvePath(j.paramPath, 1)
if (!param || !(param instanceof Parameter)) {
console.warn('resolvePath is unable to resolve', j.paramPath)
return
}
this.__param = param
this.__prevValue = this.__param.getValue()
if (this.__prevValue.clone) this.__nextValue = this.__prevValue.clone()
else this.__nextValue = this.__prevValue
this.name = j.name
if (j.value != undefined) this.updateFromJSON(j)
}
/**
* Updates the state of an existing identified `Parameter` through replication.
*
* @param {object} j - The j param.
*/
updateFromJSON(j) {
if (!this.__param) return
if (this.__nextValue.fromJSON) this.__nextValue.fromJSON(j.value)
else this.__nextValue = j.value
this.__param.setValue(this.__nextValue)
}
} |
JavaScript | class App extends Component {
componentDidMount() {
setTimeout(async () => {
store.dispatch({type: UPDATE_LOADING_VIEW, payload: false});
await SplashScreen.hideAsync();
}, 2000);
}
render() {
return (
<Provider store={store}>
<StatusBar backgroundColor="black" barStyle='default'/>
<CustomDrawer/>
</Provider>
);
}
} |
JavaScript | class CreateSubjects extends Component {
state ={
testsCount: 0,
tests: [],
test_title: null,
test_Questions: [],
questionInput: '',
qCount: 1,
options: [],
optionCount: 1,
is_Submitted: false
}
// componentDidMount(){
// if(this.props.token !== null && this.props.token !== undefined){
// this.props.getTeachers(this.props.token)
// }
// }
// componentWillUpdate(newProps){
// if(newProps.token !== this.props.token){
// if(newProps.token !== null && newProps.token !== undefined){
// this.props.getSubjects(newProps.token)
// this.props.getTeachers(newProps.token)
// }
// }
// }
//Creates new option in state
createOptions = optionItem =>{
optionItem.id = this.state.optionCount
optionItem.question = this.state.qCount
optionItem.test = this.state.testsCount
const options = [...this.state.options, optionItem]
this.setState({ options })
}
//Marks an option that corresponds to the answer value as the answer
makeAnswer = answer =>{
const options = []
const oldOptions = this.state.options
oldOptions.forEach(option => {
if(option.option===answer){
option.is_answer = true
}
options.push(option)
});
this.setState({ options })
}
//Trigger actions to add a new option
addOption = option =>{
const optionCount = this.state.optionCount
this.setState({ optionCount: optionCount+1 })
this.createOptions(option)
}
//Removes a given option
removeOption = () =>{
const optionCount = this.state.optionCount
this.setState({ optionCount: optionCount-1 })
const options = this.state.options
options.filter(op => op.id !== optionCount)
this.setState({ options })
}
//Creates new question
createQuestion = questionItem =>{
questionItem.test = this.state.testsCount
questionItem.id = this.state.qCount
this.setState({ question: questionItem })
const test_Questions = [...this.state.test_Questions, questionItem]
this.setState({ test_Questions })
}
//Adds a question trigger
addQuestionField = () =>{
let qCount = this.state.qCount
qCount += 1
if(qCount>1){
const question = {}
question.question = this.state.questionInput
this.createQuestion(question)
}
this.setState({ qCount })
}
//deletes a question
removeQuestionField = () =>{
let qCount = this.state.qCount
this.setState({ qCount: qCount-1 })
const test_Questions = this.state.test_Questions.filter(q => q.id !== qCount);
const options = this.state.options.filter(o => o.question !== qCount);
this.setState({ test_Questions })
this.setState({ options })
}
//Checks the input on the question field
handleQuestionInput = e =>{
this.setState({
[e.target.name] : e.target.value
})
}
//Checks for inputed test title
handleTestTitle = e =>{
this.setState({
[e.target.id] : e.target.value
})
}
//Creates a new test
createTest = testItem =>{
testItem.order = this.state.testsCount
const tests = [...this.state.tests, testItem]
this.setState({ tests })
}
//Triggers actions to add new test
handleAddTest= () =>{
let testsCount = this.state.testsCount + 1
this.setState({ testsCount })
if(this.state.testsCount>=1){
const testItem = {}
testItem.test_title = this.state.test_title
this.createTest(testItem)
}
}
//Deletes a test
handleDeleteTest = () =>{
const testsCount = this.state.testsCount
this.setState({ testsCount: testsCount - 1})
const tests = this.state.tests.filter(t => t.order !== testsCount);
const test_Questions = this.state.test_Questions.filter(tq => tq.test !== testsCount);
const options = this.state.options.filter(op => op.test !== testsCount);
this.setState({ tests })
this.setState({ test_Questions })
this.setState({ options })
}
//Submits inputted values on the form
handleSubmit = e =>{
e.preventDefault();
const tests = []
for(let i=0; i<this.state.tests.length; i++){
const test = {}
const questions = []
const sTests = this.state.tests
test.test_title = sTests[i].test_title
test.order = i+1
const sQ = this.state.test_Questions.filter(q => q.test===i+1)
for(let j=0; j<sQ.length; j++){
const question ={}
const options = []
question.question = sQ[j].question
question.order = j+1
const opt = this.state.options.filter(o => o.question===j+1)
opt.forEach(opt => {
options.push(opt.option)
if(opt.is_answer){
question.answer = opt.option
}
});
question.options = options
questions.push(question)
}
test.questions = questions
tests.push(test)
}
const subject = {
subject_name: e.target.elements.subject_name.value,
teacher: this.props.un,
tests
}
this.props.createSubject(this.props.token, subject)
this.setState({ is_Submitted: true })
}
// {errorMessage}
render() {
const testForms = []
// const testQuestions = this.state.test_Questions
const allTest = this.state.tests
const is_Submitted = this.state.is_Submitted
let testStatus = 'no test added'
if(allTest!==undefined && allTest.length){
if(allTest.length>1){
testStatus = `${allTest.length} tests added`
}else{
testStatus = '1 test added'
}
}
const testLength = this.state.testsCount
let addMessage =<p className='pb-1'>Add a test</p>
if(testLength>0){
addMessage = null
}
for(let i=1; i<=testLength; i++){
testForms.push(i)
}
let alert = null
if(is_Submitted){
if(!this.props.loading){
if(this.props.error){
alert = <Alertbox message={'Invalid entry'} status={'error'} />
}else{
alert = <Alertbox message={'Created new subject'} status={'success'} />
}
}
}
return (
<main className="main-area pt-5 pb-5">
{alert}
<h1 className="text-center">Add a subject</h1>
<section className="form-area container bg-light mt-4 mb-5 pt-2 pb-2">
<form className="p-2 mt-1" onSubmit={this.handleSubmit}>
<div className="row mt-2 pt-2">
<div className="col-md-6">
<div className="form-area-inner pt-5">
<div className="form-group row">
<label htmlFor="subject_name" className="col-sm-3 control-label">Subject Name*</label>
<div className="col-sm-9">
<input type="text" className="form-control" name="subject_name"
placeholder="Enter subject" required/>
</div>
</div>
</div>
<p className='text-muted ml-2'>{testStatus}</p>
{
allTest!==undefined ? allTest.map(test =>
(<div className="list-group mt-2">
<a href="#t" className="list-group-item active">
<h5 className="list-group-item-heading">{test.test_title}</h5>
</a>
</div>)): null
}
</div>
<div className="col-md-6">
<div className="form-area-inner pt-5">
{addMessage}
{testForms.map(i => <TestForm key={i} testOrder={i} handleDelete={this.handleDeleteTest}
enterTitle={this.handleTestTitle} removeQuestion={this.removeQuestionField}
addQuestion={this.addQuestionField} inputQuestion={this.handleQuestionInput}
qCount={this.state.qCount} addOption={this.addOption} removeOption={this.removeOption}
makeAnswer={this.makeAnswer}/>)}
<button type="button" className="btn btn-sm btn-success btn-round" onClick={this.handleAddTest}><i className="icon-plus"></i></button>
</div>
</div>
</div>
<div className="form-group mt-2 p-2">
<div className="col-sm-offset-2 col-sm-10">
<button type="submit" className="btn btn-dark">Save subject <i className="icon-plus"></i></button>
</div>
</div>
</form>
<div><Link to='/1/add'>Go to</Link></div>
</section>
</main>
)
}
} |
JavaScript | class AttachDiskProperties {
/**
* Create a AttachDiskProperties.
* @property {string} [leasedByLabVmId] The resource ID of the Lab virtual
* machine to which the disk is attached.
*/
constructor() {
}
/**
* Defines the metadata of AttachDiskProperties
*
* @returns {object} metadata of AttachDiskProperties
*
*/
mapper() {
return {
required: false,
serializedName: 'AttachDiskProperties',
type: {
name: 'Composite',
className: 'AttachDiskProperties',
modelProperties: {
leasedByLabVmId: {
required: false,
serializedName: 'leasedByLabVmId',
type: {
name: 'String'
}
}
}
}
};
}
} |
JavaScript | class VerifyRequest {
/**
* Constructs a new <code>VerifyRequest</code>.
* The verification call for the Normalized API is a POST method call
* @alias module:model/VerifyRequest
* @param countryCode {String} The country code for which the verification needs to be performed.
* @param dataFields {module:model/DataFields}
*/
constructor(countryCode, dataFields) {
VerifyRequest.initialize(this, countryCode, dataFields);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj, countryCode, dataFields) {
obj['CountryCode'] = countryCode;
obj['DataFields'] = dataFields;
}
/**
* Constructs a <code>VerifyRequest</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/VerifyRequest} obj Optional instance to populate.
* @return {module:model/VerifyRequest} The populated <code>VerifyRequest</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new VerifyRequest();
if (data.hasOwnProperty('AcceptTruliooTermsAndConditions')) {
obj['AcceptTruliooTermsAndConditions'] = ApiClient.convertToType(data['AcceptTruliooTermsAndConditions'], 'Boolean');
}
if (data.hasOwnProperty('Demo')) {
obj['Demo'] = ApiClient.convertToType(data['Demo'], 'Boolean');
}
if (data.hasOwnProperty('CallBackUrl')) {
obj['CallBackUrl'] = ApiClient.convertToType(data['CallBackUrl'], 'String');
}
if (data.hasOwnProperty('Timeout')) {
obj['Timeout'] = ApiClient.convertToType(data['Timeout'], 'Number');
}
if (data.hasOwnProperty('CleansedAddress')) {
obj['CleansedAddress'] = ApiClient.convertToType(data['CleansedAddress'], 'Boolean');
}
if (data.hasOwnProperty('ConfigurationName')) {
obj['ConfigurationName'] = ApiClient.convertToType(data['ConfigurationName'], 'String');
}
if (data.hasOwnProperty('ConsentForDataSources')) {
obj['ConsentForDataSources'] = ApiClient.convertToType(data['ConsentForDataSources'], ['String']);
}
if (data.hasOwnProperty('CountryCode')) {
obj['CountryCode'] = ApiClient.convertToType(data['CountryCode'], 'String');
}
if (data.hasOwnProperty('CustomerReferenceID')) {
obj['CustomerReferenceID'] = ApiClient.convertToType(data['CustomerReferenceID'], 'String');
}
if (data.hasOwnProperty('DataFields')) {
obj['DataFields'] = DataFields.constructFromObject(data['DataFields']);
}
if (data.hasOwnProperty('VerboseMode')) {
obj['VerboseMode'] = ApiClient.convertToType(data['VerboseMode'], 'Boolean');
}
}
return obj;
}
} |
JavaScript | class Thread extends EventTarget {
/**
* Constructor.
* @param {IThreadJob} job The job to run
*/
constructor(job) {
super();
/**
* @type {IThreadJob}
* @private
*/
this.job_ = job;
/**
* @type {Delay}
* @private
*/
this.delay_ = new Delay(this.onDelay_, 5, this);
}
/**
* @inheritDoc
*/
disposeInternal() {
super.disposeInternal();
this.job_ = null;
this.delay_.dispose();
this.delay_ = null;
}
/**
* Starts the thread
*/
start() {
this.delay_.start();
this.dispatchEvent(new ThreadEvent(EventType.START, this.job_));
}
/**
* Stops or pauses the thread. Processing may resume by calling <code>start()</code>.
*/
stop() {
this.delay_.stop();
this.dispatchEvent(new ThreadEvent(EventType.STOP, this.job_));
}
/**
* Terminates the thread and cleans up resources. Processing cannot resume.
*/
terminate() {
this.delay_.stop();
this.dispatchEvent(new ThreadEvent(EventType.COMPLETE, this.job_));
}
/**
* @return {boolean} Whether or not the thread is determinate.
*/
isDeterminate() {
return this.job_.getLoaded() > -1 && this.job_.getTotal() > -1;
}
/**
* Handles timer tick
*
* @private
*/
onDelay_() {
this.delay_.stop();
try {
var done = this.job_.executeNext();
this.dispatchEvent(new ThreadProgressEvent(this.job_.getLoaded(), this.job_.getTotal()));
if (done) {
this.terminate();
} else {
this.delay_.start();
}
} catch (err) {
if (!this.isDisposed()) {
this.stop();
}
log.error(logger, 'Thread execution error!', err);
this.dispatchEvent(new ThreadEvent(EventType.ERROR, this.job_));
}
}
} |
JavaScript | class App extends React.Component {
render () {
return (<footer classname='mainFooter'>
<Logo classname="logo" href="./here.html" title="this title"
src="https://media.sailthru.com/5cj/1k1/6/k/59493e8978575.jpg" width="222" height="30"
alt="logo-leftfield-222x30"/>
<Copyright name="nbcnews"/>
<ul>
<li>
<FeaturedLinks href="./here.html" title="this title"
src="https://media.sailthru.com/5cj/1k1/6/7/59381576227a9.jpg" width="222" height="30"
alt="logo-leftfield"/></li>
<li><FeaturedLinks href="./here.html" title="this title"
src="https://media.sailthru.com/5cj/1k1/6/7/59381591c7249.jpg" width="222" height="30" alt="logo-leftfield"/>
</li>
<li><FeaturedLinks href="./here.html" title="this title"
src="https://media.sailthru.com/5cj/1k1/6/7/593815a78a443.jpg" width="222" height="30" alt="logo-leftfield"/>
</li>
</ul>
</footer>
) } } |
JavaScript | class ApiPath {
/**
*
* @param paths JSONObject of paths in key-value format { login: "/auth/login", logout: "/auth/logout" }
* @param serviceUrl Optional a fully formed url e.g. https://example.com:8080.
* If serviceUrl is not passed, we attempt to read the environment variable SVC_URL.
* If neither serviceUrl and SVC_URL are not specified, we throw a URI error
* @throws URI error if you forgot to pass in a serviceUrl and didn't specify the
* SVC_URL environment variable. You can also get this error if the URL is not formed
* correctly.
*/
constructor (paths, serviceUrl) {
let svcUrl = process.env.SVC_URL
if (serviceUrl) {
svcUrl = serviceUrl
}
if (!svcUrl.endsWith("/")) {
svcUrl += "/"
}
svcUrl = encodeURI(svcUrl)
let svcHostAndPortUrl = svcUrl
let svcHostAndPort = svcUrl.match(hostAndPortRegExp)
if (svcHostAndPort.length > 0) {
svcHostAndPortUrl = encodeURI(svcHostAndPort[0])
}
this.svcHostAndPortUrl = svcHostAndPortUrl
this.svcUrl = svcUrl
const localizedStrings = Object.assign({}, paths);
for (let key in localizedStrings) {
if (key === 'fetch' || key === 'params' || key === 'addPath' || key === 'getApiHost' || key === 'getApiBase') {
throw Error(`'${key} is a reserved word.`)
}
if (localizedStrings.hasOwnProperty(key)) {
const path = localizedStrings[key]
this.addPath(key, path)
}
}
}
addPath (key, path) {
if (path.startsWith('/')) {
// Path starts with '/' means that it has to be attached to the base domain
// Meaning, if my serviceUrl is http://localhost:8080/my/api
// appending `/login` to it would result in http://localhost:8080/login
this[key] = this.svcHostAndPortUrl + path;
} else if (!path.startsWith('http')) {
// Paths that don't start with with '/' are relative to the service URL
// Meaning, if my serviceUrl is http://localhost:8080/my/api
// appending `/login` to it would result in http://localhost:8080/my/api/login
this[key] = this.svcUrl + path;
} else {
//We assume this is a full URL
this[key] = path;
}
}
getApiHost () {
return this.svcHostAndPortUrl
}
getApiBase () {
return this.svcUrl
}
//Format the passed string replacing the numbered placeholders
//i.e. I'd like some {0} and {1}, or just {0}
//Use example:
// svcPath.setParams(svcPath.question, svcPath.bread, svcPath.butter)
static params (path, ...params) {
return _setParams(path, params)
}
} |
JavaScript | class ApigatewayClient extends AbstractClient {
constructor(credential, region, profile) {
super("apigateway.tencentcloudapi.com", "2018-08-08", credential, region, profile);
}
/**
* This API is used to create a service.
The maximum unit in API Gateway is service. Multiple APIs can be created in one service, and each service has a default domain name for users to call. You can also bind your own custom domain name to a service.
* @param {CreateServiceRequest} req
* @param {function(string, CreateServiceResponse):void} cb
* @public
*/
CreateService(req, cb) {
let resp = new CreateServiceResponse();
this.request("CreateService", req, resp, cb);
}
/**
* This API is used to build an API document.
* @param {BuildAPIDocRequest} req
* @param {function(string, BuildAPIDocResponse):void} cb
* @public
*/
BuildAPIDoc(req, cb) {
let resp = new BuildAPIDocResponse();
this.request("BuildAPIDoc", req, resp, cb);
}
/**
* This API is used to bind a plugin to an API.
* @param {AttachPluginRequest} req
* @param {function(string, AttachPluginResponse):void} cb
* @public
*/
AttachPlugin(req, cb) {
let resp = new AttachPluginResponse();
this.request("AttachPlugin", req, resp, cb);
}
/**
* This API is used to delete a usage plan.
* @param {DeleteUsagePlanRequest} req
* @param {function(string, DeleteUsagePlanResponse):void} cb
* @public
*/
DeleteUsagePlan(req, cb) {
let resp = new DeleteUsagePlanResponse();
this.request("DeleteUsagePlan", req, resp, cb);
}
/**
* This API is used to bind an application to an API.
* @param {BindApiAppRequest} req
* @param {function(string, BindApiAppResponse):void} cb
* @public
*/
BindApiApp(req, cb) {
let resp = new BindApiAppResponse();
this.request("BindApiApp", req, resp, cb);
}
/**
* This API is used to modify an API. You can call this API to edit/modify a configured API. The modified API takes effect only after its service is published to the corresponding environment again.
* @param {ModifyApiRequest} req
* @param {function(string, ModifyApiResponse):void} cb
* @public
*/
ModifyApi(req, cb) {
let resp = new ModifyApiResponse();
this.request("ModifyApi", req, resp, cb);
}
/**
* This API is used to create an application.
* @param {CreateApiAppRequest} req
* @param {function(string, CreateApiAppResponse):void} cb
* @public
*/
CreateApiApp(req, cb) {
let resp = new CreateApiAppResponse();
this.request("CreateApiApp", req, resp, cb);
}
/**
* This API is used to query the list of keys.
If you have created multiple API key pairs, you can use this API to query the information of one or more keys. This API does not display the `secretKey`.
* @param {DescribeApiKeysStatusRequest} req
* @param {function(string, DescribeApiKeysStatusResponse):void} cb
* @public
*/
DescribeApiKeysStatus(req, cb) {
let resp = new DescribeApiKeysStatusResponse();
this.request("DescribeApiKeysStatus", req, resp, cb);
}
/**
* This API is used to modify the path mapping in the custom domain name settings of a service. The path mapping rule can be modified before it is bound to the custom domain name.
* @param {ModifySubDomainRequest} req
* @param {function(string, ModifySubDomainResponse):void} cb
* @public
*/
ModifySubDomain(req, cb) {
let resp = new ModifySubDomainResponse();
this.request("ModifySubDomain", req, resp, cb);
}
/**
* This API is used to query the list of custom domain names.
In API Gateway, you can bind custom domain names to a service for service call. This API is used to query the list of custom domain names bound to a service.
* @param {DescribeServiceSubDomainsRequest} req
* @param {function(string, DescribeServiceSubDomainsResponse):void} cb
* @public
*/
DescribeServiceSubDomains(req, cb) {
let resp = new DescribeServiceSubDomainsResponse();
this.request("DescribeServiceSubDomains", req, resp, cb);
}
/**
* This API is used to query the list of usage plans.
* @param {DescribeUsagePlansStatusRequest} req
* @param {function(string, DescribeUsagePlansStatusResponse):void} cb
* @public
*/
DescribeUsagePlansStatus(req, cb) {
let resp = new DescribeUsagePlansStatusResponse();
this.request("DescribeUsagePlansStatus", req, resp, cb);
}
/**
* This API is used to query the list of APIs bound to an application.
* @param {DescribeApiAppBindApisStatusRequest} req
* @param {function(string, DescribeApiAppBindApisStatusResponse):void} cb
* @public
*/
DescribeApiAppBindApisStatus(req, cb) {
let resp = new DescribeApiAppBindApisStatusResponse();
this.request("DescribeApiAppBindApisStatus", req, resp, cb);
}
/**
* This API is used to modify the name, description, and QPS of a usage plan.
* @param {ModifyUsagePlanRequest} req
* @param {function(string, ModifyUsagePlanResponse):void} cb
* @public
*/
ModifyUsagePlan(req, cb) {
let resp = new ModifyUsagePlanResponse();
this.request("ModifyUsagePlan", req, resp, cb);
}
/**
* This API is used to search for logs.
* @param {DescribeLogSearchRequest} req
* @param {function(string, DescribeLogSearchResponse):void} cb
* @public
*/
DescribeLogSearch(req, cb) {
let resp = new DescribeLogSearchResponse();
this.request("DescribeLogSearch", req, resp, cb);
}
/**
* This API is used to query the list of keys bound to a usage plan.
In API Gateway, a usage plan can be bound to multiple key pairs. You can use this API to query the list of keys bound to it.
* @param {DescribeUsagePlanSecretIdsRequest} req
* @param {function(string, DescribeUsagePlanSecretIdsResponse):void} cb
* @public
*/
DescribeUsagePlanSecretIds(req, cb) {
let resp = new DescribeUsagePlanSecretIdsResponse();
this.request("DescribeUsagePlanSecretIds", req, resp, cb);
}
/**
* This API is used to query the details of a service, such as its description, domain name, and protocol.
* @param {DescribeServiceForApiAppRequest} req
* @param {function(string, DescribeServiceForApiAppResponse):void} cb
* @public
*/
DescribeServiceForApiApp(req, cb) {
let resp = new DescribeServiceForApiAppResponse();
this.request("DescribeServiceForApiApp", req, resp, cb);
}
/**
* This API is used to modify a service IP policy.
* @param {ModifyIPStrategyRequest} req
* @param {function(string, ModifyIPStrategyResponse):void} cb
* @public
*/
ModifyIPStrategy(req, cb) {
let resp = new ModifyIPStrategyResponse();
this.request("ModifyIPStrategy", req, resp, cb);
}
/**
* This API is used to delete a service in API Gateway.
* @param {DeleteServiceRequest} req
* @param {function(string, DeleteServiceResponse):void} cb
* @public
*/
DeleteService(req, cb) {
let resp = new DeleteServiceResponse();
this.request("DeleteService", req, resp, cb);
}
/**
* This API is used to unbind an application from an API.
* @param {UnbindApiAppRequest} req
* @param {function(string, UnbindApiAppResponse):void} cb
* @public
*/
UnbindApiApp(req, cb) {
let resp = new UnbindApiAppResponse();
this.request("UnbindApiApp", req, resp, cb);
}
/**
* This API is used to unbind an IP policy from a service.
* @param {UnBindIPStrategyRequest} req
* @param {function(string, UnBindIPStrategyResponse):void} cb
* @public
*/
UnBindIPStrategy(req, cb) {
let resp = new UnBindIPStrategyResponse();
this.request("UnBindIPStrategy", req, resp, cb);
}
/**
* This API is used to create an API document.
* @param {CreateAPIDocRequest} req
* @param {function(string, CreateAPIDocResponse):void} cb
* @public
*/
CreateAPIDoc(req, cb) {
let resp = new CreateAPIDocResponse();
this.request("CreateAPIDoc", req, resp, cb);
}
/**
* This API is used to modify a created API.
* @param {ModifyApiAppRequest} req
* @param {function(string, ModifyApiAppResponse):void} cb
* @public
*/
ModifyApiApp(req, cb) {
let resp = new ModifyApiAppResponse();
this.request("ModifyApiApp", req, resp, cb);
}
/**
* This API is used to switch the running version of a service published in an environment to a specified version. After you create a service by using API Gateway and publish it to an environment, multiple versions will be generated during development. In this case, you can call this API to switch versions.
* @param {UpdateServiceRequest} req
* @param {function(string, UpdateServiceResponse):void} cb
* @public
*/
UpdateService(req, cb) {
let resp = new UpdateServiceResponse();
this.request("UpdateService", req, resp, cb);
}
/**
* This API is used to query the list of APIs to which an IP policy can be bound, i.e., the difference set between all APIs under the service and the APIs already bound to the policy.
* @param {DescribeIPStrategyApisStatusRequest} req
* @param {function(string, DescribeIPStrategyApisStatusResponse):void} cb
* @public
*/
DescribeIPStrategyApisStatus(req, cb) {
let resp = new DescribeIPStrategyApisStatusResponse();
this.request("DescribeIPStrategyApisStatus", req, resp, cb);
}
/**
* This API is used to modify a plugin.
* @param {ModifyPluginRequest} req
* @param {function(string, ModifyPluginResponse):void} cb
* @public
*/
ModifyPlugin(req, cb) {
let resp = new ModifyPluginResponse();
this.request("ModifyPlugin", req, resp, cb);
}
/**
* This API is used to deactivate a service.
Only after a service is published to an environment can its APIs be called. You can call this API to deactivate a service in the release environment. Once deactivated, the service cannot be called.
* @param {UnReleaseServiceRequest} req
* @param {function(string, UnReleaseServiceResponse):void} cb
* @public
*/
UnReleaseService(req, cb) {
let resp = new UnReleaseServiceResponse();
this.request("UnReleaseService", req, resp, cb);
}
/**
* This API is used to query the list of applications bound to an API.
* @param {DescribeApiBindApiAppsStatusRequest} req
* @param {function(string, DescribeApiBindApiAppsStatusResponse):void} cb
* @public
*/
DescribeApiBindApiAppsStatus(req, cb) {
let resp = new DescribeApiBindApiAppsStatusResponse();
this.request("DescribeApiBindApiAppsStatus", req, resp, cb);
}
/**
* This API is used to incrementally update an API and mainly called by programs (different from `ModifyApi`, which requires that full API parameters be passed in and is suitable for use in the console).
* @param {ModifyApiIncrementRequest} req
* @param {function(string, ModifyApiIncrementResponse):void} cb
* @public
*/
ModifyApiIncrement(req, cb) {
let resp = new ModifyApiIncrementResponse();
this.request("ModifyApiIncrement", req, resp, cb);
}
/**
* This API is used to delete a created application.
* @param {DeleteApiAppRequest} req
* @param {function(string, DeleteApiAppResponse):void} cb
* @public
*/
DeleteApiApp(req, cb) {
let resp = new DeleteApiAppResponse();
this.request("DeleteApiApp", req, resp, cb);
}
/**
* This API is used to query the details of an API document.
* @param {DescribeAPIDocDetailRequest} req
* @param {function(string, DescribeAPIDocDetailResponse):void} cb
* @public
*/
DescribeAPIDocDetail(req, cb) {
let resp = new DescribeAPIDocDetailResponse();
this.request("DescribeAPIDocDetail", req, resp, cb);
}
/**
* This API is used to query the release history in a service environment.
A service can only be used when it is published to an environment after creation. This API is used to query the release history in an environment under a service.
* @param {DescribeServiceEnvironmentReleaseHistoryRequest} req
* @param {function(string, DescribeServiceEnvironmentReleaseHistoryResponse):void} cb
* @public
*/
DescribeServiceEnvironmentReleaseHistory(req, cb) {
let resp = new DescribeServiceEnvironmentReleaseHistoryResponse();
this.request("DescribeServiceEnvironmentReleaseHistory", req, resp, cb);
}
/**
* This API is used to query the details of API usage plans in a service.
To make authentication and throttling for a service take effect, you need to bind a usage plan to it. This API is used to query all usage plans bound to a service and APIs under it.
* @param {DescribeApiUsagePlanRequest} req
* @param {function(string, DescribeApiUsagePlanResponse):void} cb
* @public
*/
DescribeApiUsagePlan(req, cb) {
let resp = new DescribeApiUsagePlanResponse();
this.request("DescribeApiUsagePlan", req, resp, cb);
}
/**
* This API is used to delete a created API.
* @param {DeleteApiRequest} req
* @param {function(string, DeleteApiResponse):void} cb
* @public
*/
DeleteApi(req, cb) {
let resp = new DeleteApiResponse();
this.request("DeleteApi", req, resp, cb);
}
/**
* This API is used to query the list of API documents.
* @param {DescribeAPIDocsRequest} req
* @param {function(string, DescribeAPIDocsResponse):void} cb
* @public
*/
DescribeAPIDocs(req, cb) {
let resp = new DescribeAPIDocsResponse();
this.request("DescribeAPIDocs", req, resp, cb);
}
/**
* This API is used to query the list of service IP policies.
* @param {DescribeIPStrategysStatusRequest} req
* @param {function(string, DescribeIPStrategysStatusResponse):void} cb
* @public
*/
DescribeIPStrategysStatus(req, cb) {
let resp = new DescribeIPStrategysStatusResponse();
this.request("DescribeIPStrategysStatus", req, resp, cb);
}
/**
* This API is used to query the list of environments under a service. All environments and their statuses under the queried service will be returned.
* @param {DescribeServiceEnvironmentListRequest} req
* @param {function(string, DescribeServiceEnvironmentListResponse):void} cb
* @public
*/
DescribeServiceEnvironmentList(req, cb) {
let resp = new DescribeServiceEnvironmentListResponse();
this.request("DescribeServiceEnvironmentList", req, resp, cb);
}
/**
* This API is used to query the details of usage plans in a service.
To make authentication and throttling for a service take effect, you need to bind a usage plan to it. This API is used to query all usage plans bound to a service.
* @param {DescribeServiceUsagePlanRequest} req
* @param {function(string, DescribeServiceUsagePlanResponse):void} cb
* @public
*/
DescribeServiceUsagePlan(req, cb) {
let resp = new DescribeServiceUsagePlanResponse();
this.request("DescribeServiceUsagePlan", req, resp, cb);
}
/**
* This API is used to modify a service throttling policy.
* @param {ModifyServiceEnvironmentStrategyRequest} req
* @param {function(string, ModifyServiceEnvironmentStrategyResponse):void} cb
* @public
*/
ModifyServiceEnvironmentStrategy(req, cb) {
let resp = new ModifyServiceEnvironmentStrategyResponse();
this.request("ModifyServiceEnvironmentStrategy", req, resp, cb);
}
/**
* This API is used to create a usage plan.
To use API Gateway, you need to create a usage plan and bind it to a service environment.
* @param {CreateUsagePlanRequest} req
* @param {function(string, CreateUsagePlanResponse):void} cb
* @public
*/
CreateUsagePlan(req, cb) {
let resp = new CreateUsagePlanResponse();
this.request("CreateUsagePlan", req, resp, cb);
}
/**
* This API is used to update an application key.
* @param {UpdateApiAppKeyRequest} req
* @param {function(string, UpdateApiAppKeyResponse):void} cb
* @public
*/
UpdateApiAppKey(req, cb) {
let resp = new UpdateApiAppKeyResponse();
this.request("UpdateApiAppKey", req, resp, cb);
}
/**
* This API is used to unbind a usage plan from a specified environment.
* @param {UnBindEnvironmentRequest} req
* @param {function(string, UnBindEnvironmentResponse):void} cb
* @public
*/
UnBindEnvironment(req, cb) {
let resp = new UnBindEnvironmentResponse();
this.request("UnBindEnvironment", req, resp, cb);
}
/**
* This API is used to degrade a usage plan of a service in an environment to the API level.
This operation will be denied if there are no APIs under the service.
This operation will also be denied if the current environment has not been published.
* @param {DemoteServiceUsagePlanRequest} req
* @param {function(string, DemoteServiceUsagePlanResponse):void} cb
* @public
*/
DemoteServiceUsagePlan(req, cb) {
let resp = new DemoteServiceUsagePlanResponse();
this.request("DemoteServiceUsagePlan", req, resp, cb);
}
/**
* This API is used to update a created API key pair.
* @param {UpdateApiKeyRequest} req
* @param {function(string, UpdateApiKeyResponse):void} cb
* @public
*/
UpdateApiKey(req, cb) {
let resp = new UpdateApiKeyResponse();
this.request("UpdateApiKey", req, resp, cb);
}
/**
* This API is used to delete an API Gateway plugin.
* @param {DeletePluginRequest} req
* @param {function(string, DeletePluginResponse):void} cb
* @public
*/
DeletePlugin(req, cb) {
let resp = new DeletePluginResponse();
this.request("DeletePlugin", req, resp, cb);
}
/**
* This API is used to query the path mappings of a custom domain name.
In API Gateway, you can bind a custom domain name to a service and map its paths. You can customize different path mappings to up to 3 environments under the service. This API is used to query the list of path mappings of a custom domain name bound to a service.
* @param {DescribeServiceSubDomainMappingsRequest} req
* @param {function(string, DescribeServiceSubDomainMappingsResponse):void} cb
* @public
*/
DescribeServiceSubDomainMappings(req, cb) {
let resp = new DescribeServiceSubDomainMappingsResponse();
this.request("DescribeServiceSubDomainMappings", req, resp, cb);
}
/**
* This API is used to bind a usage plan to a service or API.
After you publish a service to an environment, if the API requires authentication and can be called only when it is bound to a usage plan, you can use this API to bind a usage plan to the specified environment.
Currently, a usage plan can be bound to an API; however, under the same service, usage plans bound to a service and usage plans bound to an API cannot coexist. Therefore, in an environment to which a service-level usage plan has already been bound, please use the `DemoteServiceUsagePlan` API to degrade it.
* @param {BindEnvironmentRequest} req
* @param {function(string, BindEnvironmentResponse):void} cb
* @public
*/
BindEnvironment(req, cb) {
let resp = new BindEnvironmentResponse();
this.request("BindEnvironment", req, resp, cb);
}
/**
* This API is used to modify an API document.
* @param {ModifyAPIDocRequest} req
* @param {function(string, ModifyAPIDocResponse):void} cb
* @public
*/
ModifyAPIDoc(req, cb) {
let resp = new ModifyAPIDocResponse();
this.request("ModifyAPIDoc", req, resp, cb);
}
/**
* This API is used to unbind a key from a usage plan.
* @param {UnBindSecretIdsRequest} req
* @param {function(string, UnBindSecretIdsResponse):void} cb
* @public
*/
UnBindSecretIds(req, cb) {
let resp = new UnBindSecretIdsResponse();
this.request("UnBindSecretIds", req, resp, cb);
}
/**
* This API is used to bind an IP policy to an API.
* @param {BindIPStrategyRequest} req
* @param {function(string, BindIPStrategyResponse):void} cb
* @public
*/
BindIPStrategy(req, cb) {
let resp = new BindIPStrategyResponse();
this.request("BindIPStrategy", req, resp, cb);
}
/**
* This API is used to query the list of one or more services and return relevant domain name, time, and other information.
* @param {DescribeServicesStatusRequest} req
* @param {function(string, DescribeServicesStatusResponse):void} cb
* @public
*/
DescribeServicesStatus(req, cb) {
let resp = new DescribeServicesStatusResponse();
this.request("DescribeServicesStatus", req, resp, cb);
}
/**
* This API is used to query IP policy details.
* @param {DescribeIPStrategyRequest} req
* @param {function(string, DescribeIPStrategyResponse):void} cb
* @public
*/
DescribeIPStrategy(req, cb) {
let resp = new DescribeIPStrategyResponse();
this.request("DescribeIPStrategy", req, resp, cb);
}
/**
* This API is used to query the list of environments bound to a usage plan.
After binding a usage plan to environments, you can use this API to query all service environments bound to the usage plan.
* @param {DescribeUsagePlanEnvironmentsRequest} req
* @param {function(string, DescribeUsagePlanEnvironmentsResponse):void} cb
* @public
*/
DescribeUsagePlanEnvironments(req, cb) {
let resp = new DescribeUsagePlanEnvironmentsResponse();
this.request("DescribeUsagePlanEnvironments", req, resp, cb);
}
/**
* This API is used to enable a disabled API key.
* @param {EnableApiKeyRequest} req
* @param {function(string, EnableApiKeyResponse):void} cb
* @public
*/
EnableApiKey(req, cb) {
let resp = new EnableApiKeyResponse();
this.request("EnableApiKey", req, resp, cb);
}
/**
* This API is used to list all APIs that can use this plugin, no matter whether the API is bound with the plugin.
* @param {DescribeAllPluginApisRequest} req
* @param {function(string, DescribeAllPluginApisResponse):void} cb
* @public
*/
DescribeAllPluginApis(req, cb) {
let resp = new DescribeAllPluginApisResponse();
this.request("DescribeAllPluginApis", req, resp, cb);
}
/**
* This API is used to create a service IP policy.
* @param {CreateIPStrategyRequest} req
* @param {function(string, CreateIPStrategyResponse):void} cb
* @public
*/
CreateIPStrategy(req, cb) {
let resp = new CreateIPStrategyResponse();
this.request("CreateIPStrategy", req, resp, cb);
}
/**
* This API is used to query the list of all published versions under a service.
A service is generally published on several versions. This API can be used to query the published versions.
* @param {DescribeServiceReleaseVersionRequest} req
* @param {function(string, DescribeServiceReleaseVersionResponse):void} cb
* @public
*/
DescribeServiceReleaseVersion(req, cb) {
let resp = new DescribeServiceReleaseVersionResponse();
this.request("DescribeServiceReleaseVersion", req, resp, cb);
}
/**
* This API is used to view a certain API or the list of all APIs under a service and relevant information.
* @param {DescribeApisStatusRequest} req
* @param {function(string, DescribeApisStatusResponse):void} cb
* @public
*/
DescribeApisStatus(req, cb) {
let resp = new DescribeApisStatusResponse();
this.request("DescribeApisStatus", req, resp, cb);
}
/**
* This API is used to create an API key pair.
* @param {CreateApiKeyRequest} req
* @param {function(string, CreateApiKeyResponse):void} cb
* @public
*/
CreateApiKey(req, cb) {
let resp = new CreateApiKeyResponse();
this.request("CreateApiKey", req, resp, cb);
}
/**
* This API is used to delete an API document.
* @param {DeleteAPIDocRequest} req
* @param {function(string, DeleteAPIDocResponse):void} cb
* @public
*/
DeleteAPIDoc(req, cb) {
let resp = new DeleteAPIDocResponse();
this.request("DeleteAPIDoc", req, resp, cb);
}
/**
* This API is used to unbind an API from the plugin.
* @param {DetachPluginRequest} req
* @param {function(string, DetachPluginResponse):void} cb
* @public
*/
DetachPlugin(req, cb) {
let resp = new DetachPluginResponse();
this.request("DetachPlugin", req, resp, cb);
}
/**
* This API is used to delete a service IP policy.
* @param {DeleteIPStrategyRequest} req
* @param {function(string, DeleteIPStrategyResponse):void} cb
* @public
*/
DeleteIPStrategy(req, cb) {
let resp = new DeleteIPStrategyResponse();
this.request("DeleteIPStrategy", req, resp, cb);
}
/**
* This API is used to publish a service.
An API Gateway service can only be called when it is published to an environment and takes effect after creation. This API is used to publish a service to an environment such as the `release` environment.
* @param {ReleaseServiceRequest} req
* @param {function(string, ReleaseServiceResponse):void} cb
* @public
*/
ReleaseService(req, cb) {
let resp = new ReleaseServiceResponse();
this.request("ReleaseService", req, resp, cb);
}
/**
* This API is used to query APIs bound with a specified plugin.
* @param {DescribePluginApisRequest} req
* @param {function(string, DescribePluginApisResponse):void} cb
* @public
*/
DescribePluginApis(req, cb) {
let resp = new DescribePluginApisResponse();
this.request("DescribePluginApis", req, resp, cb);
}
/**
* This API is used to disable an API key.
* @param {DisableApiKeyRequest} req
* @param {function(string, DisableApiKeyResponse):void} cb
* @public
*/
DisableApiKey(req, cb) {
let resp = new DisableApiKeyResponse();
this.request("DisableApiKey", req, resp, cb);
}
/**
* This API is used to modify the relevant information of a service. After a service is created, its name, description, and service type can be modified.
* @param {ModifyServiceRequest} req
* @param {function(string, ModifyServiceResponse):void} cb
* @public
*/
ModifyService(req, cb) {
let resp = new ModifyServiceResponse();
this.request("ModifyService", req, resp, cb);
}
/**
* This API is used to modify an API throttling policy.
* @param {ModifyApiEnvironmentStrategyRequest} req
* @param {function(string, ModifyApiEnvironmentStrategyResponse):void} cb
* @public
*/
ModifyApiEnvironmentStrategy(req, cb) {
let resp = new ModifyApiEnvironmentStrategyResponse();
this.request("ModifyApiEnvironmentStrategy", req, resp, cb);
}
/**
* This API is used to display the throttling policies bound to an API.
* @param {DescribeApiEnvironmentStrategyRequest} req
* @param {function(string, DescribeApiEnvironmentStrategyResponse):void} cb
* @public
*/
DescribeApiEnvironmentStrategy(req, cb) {
let resp = new DescribeApiEnvironmentStrategyResponse();
this.request("DescribeApiEnvironmentStrategy", req, resp, cb);
}
/**
* This API is used to query the application list.
* @param {DescribeApiAppsStatusRequest} req
* @param {function(string, DescribeApiAppsStatusResponse):void} cb
* @public
*/
DescribeApiAppsStatus(req, cb) {
let resp = new DescribeApiAppsStatusResponse();
this.request("DescribeApiAppsStatus", req, resp, cb);
}
/**
* This API is used to bind a key to a usage plan.
You can bind a key to a usage plan and bind the usage plan to an environment where a service is published, so that callers can use the key to call APIs in the service. You can use this API to bind a key to a usage plan.
* @param {BindSecretIdsRequest} req
* @param {function(string, BindSecretIdsResponse):void} cb
* @public
*/
BindSecretIds(req, cb) {
let resp = new BindSecretIdsResponse();
this.request("BindSecretIds", req, resp, cb);
}
/**
* This API is used to display a service throttling policy.
* @param {DescribeServiceEnvironmentStrategyRequest} req
* @param {function(string, DescribeServiceEnvironmentStrategyResponse):void} cb
* @public
*/
DescribeServiceEnvironmentStrategy(req, cb) {
let resp = new DescribeServiceEnvironmentStrategyResponse();
this.request("DescribeServiceEnvironmentStrategy", req, resp, cb);
}
/**
* This API is used to query the details of a service, such as its description, domain name, protocol, creation time, and releases.
* @param {DescribeServiceRequest} req
* @param {function(string, DescribeServiceResponse):void} cb
* @public
*/
DescribeService(req, cb) {
let resp = new DescribeServiceResponse();
this.request("DescribeService", req, resp, cb);
}
/**
* This API is used to search for an application by application ID.
* @param {DescribeApiAppRequest} req
* @param {function(string, DescribeApiAppResponse):void} cb
* @public
*/
DescribeApiApp(req, cb) {
let resp = new DescribeApiAppResponse();
this.request("DescribeApiApp", req, resp, cb);
}
/**
* This API is used to delete a custom domain name mapping in a service environment.
You can use this API if you use a custom domain name and custom mapping. Please note that if you delete all mappings in all environments, a failure will be returned when this API is called.
* @param {DeleteServiceSubDomainMappingRequest} req
* @param {function(string, DeleteServiceSubDomainMappingResponse):void} cb
* @public
*/
DeleteServiceSubDomainMapping(req, cb) {
let resp = new DeleteServiceSubDomainMappingResponse();
this.request("DeleteServiceSubDomainMapping", req, resp, cb);
}
/**
* This API is used to query the details of a key.
After creating an API key, you can query its details by using this API.
* @param {DescribeApiKeyRequest} req
* @param {function(string, DescribeApiKeyResponse):void} cb
* @public
*/
DescribeApiKey(req, cb) {
let resp = new DescribeApiKeyResponse();
this.request("DescribeApiKey", req, resp, cb);
}
/**
* This API is used to create an API Gateway plugin.
* @param {CreatePluginRequest} req
* @param {function(string, CreatePluginResponse):void} cb
* @public
*/
CreatePlugin(req, cb) {
let resp = new CreatePluginResponse();
this.request("CreatePlugin", req, resp, cb);
}
/**
* This API is used to query the details of a usage plan, such as its name, QPS, creation time, and bound environment.
* @param {DescribeUsagePlanRequest} req
* @param {function(string, DescribeUsagePlanResponse):void} cb
* @public
*/
DescribeUsagePlan(req, cb) {
let resp = new DescribeUsagePlanResponse();
this.request("DescribeUsagePlan", req, resp, cb);
}
/**
* This API is used to unbind a custom domain name.
After binding a custom domain name to a service by using API Gateway, you can use this API to unbind it.
* @param {UnBindSubDomainRequest} req
* @param {function(string, UnBindSubDomainResponse):void} cb
* @public
*/
UnBindSubDomain(req, cb) {
let resp = new UnBindSubDomainResponse();
this.request("UnBindSubDomain", req, resp, cb);
}
/**
* This API is used to bind a custom domain name to a service.
Each service in API Gateway provides a default domain name for users to call. If you want to use your own domain name, you can bind a custom domain name to the target service. After getting the ICP filing and configuring the CNAME record between the custom and default domain names, you can directly call the custom domain name.
* @param {BindSubDomainRequest} req
* @param {function(string, BindSubDomainResponse):void} cb
* @public
*/
BindSubDomain(req, cb) {
let resp = new BindSubDomainResponse();
this.request("BindSubDomain", req, resp, cb);
}
/**
* This API is used to query the plugin details by plugin ID.
* @param {DescribePluginRequest} req
* @param {function(string, DescribePluginResponse):void} cb
* @public
*/
DescribePlugin(req, cb) {
let resp = new DescribePluginResponse();
this.request("DescribePlugin", req, resp, cb);
}
/**
* This API (`DescribeApi`) is used to query the details of the APIs users manage via Tencent Cloud API Gateway.
* @param {DescribeApiRequest} req
* @param {function(string, DescribeApiResponse):void} cb
* @public
*/
DescribeApi(req, cb) {
let resp = new DescribeApiResponse();
this.request("DescribeApi", req, resp, cb);
}
/**
* This API is used to automatically generate API documents and SDKs. One document and one SDK will be generated for each environment under each service, respectively.
* @param {GenerateApiDocumentRequest} req
* @param {function(string, GenerateApiDocumentResponse):void} cb
* @public
*/
GenerateApiDocument(req, cb) {
let resp = new GenerateApiDocumentResponse();
this.request("GenerateApiDocument", req, resp, cb);
}
/**
* This API is used to delete an API key pair.
* @param {DeleteApiKeyRequest} req
* @param {function(string, DeleteApiKeyResponse):void} cb
* @public
*/
DeleteApiKey(req, cb) {
let resp = new DeleteApiKeyResponse();
this.request("DeleteApiKey", req, resp, cb);
}
/**
* This API is used to create an API. Before creating an API, you need to create a service, as each API belongs to a certain service.
* @param {CreateApiRequest} req
* @param {function(string, CreateApiResponse):void} cb
* @public
*/
CreateApi(req, cb) {
let resp = new CreateApiResponse();
this.request("CreateApi", req, resp, cb);
}
/**
* This API is used to reset the password of an API document.
* @param {ResetAPIDocPasswordRequest} req
* @param {function(string, ResetAPIDocPasswordResponse):void} cb
* @public
*/
ResetAPIDocPassword(req, cb) {
let resp = new ResetAPIDocPasswordResponse();
this.request("ResetAPIDocPassword", req, resp, cb);
}
/**
* This API is used to query the details of an API deployed at API Gateway.
* @param {DescribeApiForApiAppRequest} req
* @param {function(string, DescribeApiForApiAppResponse):void} cb
* @public
*/
DescribeApiForApiApp(req, cb) {
let resp = new DescribeApiForApiAppResponse();
this.request("DescribeApiForApiApp", req, resp, cb);
}
} |
JavaScript | class Dialog extends PureComponent {
static propTypes = {
className: PropTypes.string,
title: PropTypes.string,
visible: PropTypes.bool,
closeOnOverlay: PropTypes.bool,
closeOnEsc: PropTypes.bool,
onOk: PropTypes.func, // 点击确定回调
okType: PropTypes.oneOf(['green', 'danger']), // 确定按钮类型
onCancel: PropTypes.func, // 点击遮罩层或右上角叉或取消按钮的回调
closable: PropTypes.bool, // 是否显示右上角的关闭按钮
footer: PropTypes.node // 底部内容
}
static defaultProps = {
visible: false,
closable: true,
closeOnOverlay: true,
okType: 'green'
}
componentDidMount () {
if (this.props.closeOnEsc) {
document.addEventListener('keydown', this.handleEscKeyDown);
}
}
componentWillUnmount () {
if (this.props.closeOnEsc) {
document.removeEventListener('keydown', this.handleEscKeyDown);
}
}
handleOverlayClick = () => {
if (this.props.onCancel && this.props.closeOnOverlay) {
this.props.onCancel();
}
}
handleCloseBtn = () => {
if (this.props.onCancel) {
this.props.onCancel();
}
}
handleEscKeyDown = e => {
if (this.props.onCancel && this.props.closeOnEsc && e.keyCode === 27) {
this.props.onCancel();
}
}
onCancel = () => {
let { onCancel } = this.props;
onCancel && onCancel();
}
handleOK = () => {
if (this.props.onOk) {
this.props.onOk();
} else {
this.onCancel();
}
}
render () {
let { visible, title, closable, okType, footer, className } = this.props;
const classString = classNames(
className,
{
'dialog-content': true,
'dialog-in': visible,
'dialog-out': !visible
}
);
if (!visible) return null;
return (
<div className="dialog-wrapper">
<div className="dialog-mask" onClick={this.onCancel}></div>
<div className={classString}>
{
title || closable ? (
<div className="dialog__header">
{
title ? (
<div className="dialog__title">{title}</div>
) : null
}
{
closable ? (
<Icon type="close" className="dialog__close-btn" onClick={this.onCancel}/>
) : null
}
</div>
) : null
}
<div className="dialog__body">
{this.props.children}
</div>
{
footer === undefined ? (
<div className="dialog__footer">
<Button size="small" onClick={this.onCancel}>取消</Button>
<Button type={okType} size="small" onClick={this.handleOK}>确定</Button>
</div>
) : footer
}
</div>
</div>
);
}
} |
JavaScript | class LayoutHeader extends Component {
static propTypes = {
logo: PropTypes.shape({
aspectRatio: PropTypes.number,
base64: PropTypes.string,
src: PropTypes.string,
srcSet: PropTypes.string,
sizes: PropTypes.string,
}),
name: PropTypes.string,
routes: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string,
label: PropTypes.string,
path: PropTypes.string,
}),
),
}
state = {
isVisible: false,
isMenuOpen: false,
}
componentDidMount() {
window.addEventListener('scroll', this.handleVisibility);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleVisibility);
}
handleVisibility = () => {
const offset = 500;
const position = window.pageYOffset || document.body.scrollTop;
const height = window.innerHeight - offset;
if (position >= height) this.setState({ isVisible: true });
else this.setState({ isVisible: false });
}
handleMenuToggle = () => {
const { isMenuOpen } = this.state;
this.setState({ isMenuOpen: !isMenuOpen });
}
render() {
const { isMenuOpen, isVisible } = this.state;
const { logo, name, routes } = this.props;
return (
<HeaderWrapper
as="header"
isMenuOpen={isMenuOpen}
isVisible={isVisible}
>
<HeaderContainer
as="nav"
isFlex
>
<HeaderBrand
isVisible={isVisible}
logo={logo}
name={name}
/>
<HeaderMenu
isMenuOpen={isMenuOpen}
onMenuToggle={this.handleMenuToggle}
routes={routes}
/>
</HeaderContainer>
</HeaderWrapper>
);
}
} |
JavaScript | class ExperincesComponent extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<div className="work" id="work">
<div className="container">
<h3 className="w3_head w3_head1">Experience & Education <span>More about my past</span></h3>
<h5>Work experience</h5>
<div className="work-info-agileits">
<div className="col-md-4 work-left-agileits-w3layouts">
<h6><i className="fa fa-calendar-check-o" aria-hidden="true"></i> 2017-Present</h6>
</div>
<div className="col-md-8 work-right-w3-agileits">
<h3>Tata Consultancy Services/<span> Web Development (J2EE)</span></h3>
<p>Worked on development, enhancement and maintainence of enterprice level application with Struts framework. Also worked on migrating applications from Struts to Springs boot.</p>
</div>
<div className="clearfix"> </div>
</div>
<div className="work-info-agileits">
<div className="col-md-4 work-left-agileits-w3layouts">
<h6><i className="fa fa-calendar-check-o" aria-hidden="true"></i> 2014-2017</h6>
</div>
<div className="col-md-8 work-right-w3-agileits">
<h3>Tata Consultancy Services/<span> Frontend Web Development (React & Angular)</span></h3>
<p>Worked on development of an enteprice level application in React (Microsite - React; Microservices - Springs Boot). Also worked on small scale internal stand alone applications in Angular.</p>
</div>
<div className="clearfix"> </div>
</div>
<h5 className="work2">Education</h5>
<div className="work-info-agileits">
<div className="col-md-4 work-left-agileits-w3layouts">
<h6><i className="fa fa-calendar-check-o" aria-hidden="true"></i> 2010-2014</h6>
</div>
<div className="col-md-8 work-right-w3-agileits">
<h3>Netaji Subhash Engineering College</h3>
<p>Compeleted Bachelors Degree in Electronics and Communication Engineering.</p>
</div>
<div className="clearfix"> </div>
</div>
</div>
</div>
);
}
} |
JavaScript | class Email extends Model {
/**
* Construct Email Model class
*/
constructor () {
// Run super
super(...arguments);
}
} |
JavaScript | class Command {
/**
* Dispose (release all internal resources).
*
* @example
* command.dispose();
* command = null;
*/
dispose() {}
/**
* Called when command is executed.
*
* @abstract
* @param {WebGLRenderingContext} gl - WebGL context.
* @param {RenderSystem} renderer - Render system that is used to render.
* @param {number} deltaTime - Delta time.
* @param {string} layer - Layer id.
*/
onRender(gl, renderer, deltaTime, layer) {
throw new Error('Not implemented!');
}
/**
* Called on view resize.
*
* @param {number} width - Width.
* @param {number} height - Height.
*/
onResize(width, height) {}
} |
JavaScript | class Pipeline extends Command {
get commands() {
return this._commands;
}
set commands(value) {
if (!value) {
this._commands = null;
return;
}
if (!Array.isArray(value)) {
throw new Error('`value` is not type of Array!');
}
for (const item of value) {
if (!(item instanceof Command)) {
throw new Error('One of `value` items is not type of Command!');
}
}
this._commands = value;
}
/**
* Constructor.
*/
constructor(commands = null) {
super();
this.commands = commands;
}
/**
* @override
*/
dispose() {
const { _commands } = this;
if (!!_commands) {
for (const command of _commands) {
command.dispose();
}
this._commands = null;
}
}
/**
* @override
*/
onRender(gl, renderer, deltaTime, layer) {
const { _commands } = this;
if (!!_commands) {
for (const command of _commands) {
command.onRender(gl, renderer, deltaTime, layer);
}
}
}
/**
* @override
*/
onResize(width, height) {
const { _commands } = this;
if (!!_commands) {
for (const command of _commands) {
command.onResize(width, height);
}
}
}
} |
JavaScript | class RenderFullscreenCommand extends Command {
/** @type {string|null} */
get shader() {
return this._shader;
}
/** @type {string|null} */
set shader(value) {
if (!value) {
this._shader = null;
return;
}
if (typeof value !== 'string') {
throw new Error('`value` is not type of String!');
}
this._shader = value;
}
/** @type {*} */
get overrideUniforms() {
return this._overrideUniforms;
}
/** @type {*} */
get overrideSamplers() {
return this._overrideSamplers;
}
/**
* Constructor.
*/
constructor() {
super();
this._context = null;
this._vertexBuffer = null;
this._indexBuffer = null;
this._shader = null;
this._overrideUniforms = new Map();
this._overrideSamplers = new Map();
this._dirty = true;
}
/**
* Destructor (dispose internal resources).
*
* @example
* command.dispose();
* pass = null;
*/
dispose() {
const { _context, _vertexBuffer, _indexBuffer } = this;
if (!!_context) {
if (!!_vertexBuffer) {
_context.deleteBuffer(_vertexBuffer);
}
if (!!_indexBuffer) {
_context.deleteBuffer(_indexBuffer);
}
}
this._overrideUniforms.clear();
this._overrideSamplers.clear();
this._context = null;
this._vertexBuffer = null;
this._indexBuffer = null;
this._shader = null;
this._overrideUniforms = null;
this._overrideSamplers = null;
}
/**
* Called when camera need to postprocess it's rendered image.
*
* @param {WebGLRenderingContext} gl - WebGL context.
* @param {RenderSystem} renderer - Render system that is used to render.
* @param {number} deltaTime - Delta time.
* @param {string|null} layer - Layer ID.
*/
onRender(gl, renderer, deltaTime, layer) {
const {
_shader,
_overrideUniforms,
_overrideSamplers
} = this;
if (!_shader) {
console.warn('Trying to render PostprocessPass without shader!');
return;
}
this._ensureState(gl, renderer);
gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
if (this._dirty) {
this._dirty = false;
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
}
renderer.enableShader(_shader);
if (_overrideUniforms.size > 0) {
for (const [ name, value ] of _overrideUniforms) {
renderer.overrideShaderUniform(name, value);
}
}
if (_overrideSamplers.size > 0) {
for (const [ name, { texture, filtering } ] of _overrideSamplers) {
if (texture !== '') {
renderer.overrideShaderSampler(name, texture, filtering);
}
}
}
gl.drawElements(
gl.TRIANGLES,
indices.length,
gl.UNSIGNED_SHORT,
0
);
renderer.disableShader();
}
_ensureState(gl, renderer) {
this._context = gl;
if (!this._vertexBuffer) {
this._vertexBuffer = gl.createBuffer();
this._dirty = true;
}
if (!this._indexBuffer) {
this._indexBuffer = gl.createBuffer();
this._dirty = true;
}
}
} |
JavaScript | class RenderSystem extends System {
/** @type {*} */
static get propsTypes() {
return {
useDevicePixelRatio: 'boolean',
timeScale: 'number',
collectStats: 'boolean'
};
}
/** @type {number} */
get contextVersion() {
return this._contextVersion;
}
/** @type {boolean} */
get useDevicePixelRatio() {
return this._useDevicePixelRatio;
}
/** @type {boolean} */
set useDevicePixelRatio(value) {
this._useDevicePixelRatio = !!value;
}
/** @type {number} */
get timeScale() {
return this._timeScale;
}
/** @type {number} */
set timeScale(value) {
if (typeof value !== 'number') {
throw new Error('`value` is not type of Number!');
}
this._timeScale = value;
}
/** @type {boolean} */
get collectStats() {
return this._collectStats;
}
/** @type {boolean} */
set collectStats(value) {
if (typeof value !== 'boolean') {
throw new Error('`value` is not type of Boolean!');
}
this._collectStats = value;
}
/** @type {number} */
get passedTime() {
return this._passedTime;
}
/** @type {HTMLCanvasElement} */
get canvas() {
return this._canvas;
}
/** @type {Events} */
get events() {
return this._events;
}
/** @type {string} */
get activeShader() {
return this._activeShader;
}
/** @type {string} */
get activeRenderTarget() {
return this._activeRenderTarget;
}
/** @type {string} */
get clearColor() {
return this._clearColor;
}
/** @type {mat4} */
get projectionMatrix() {
return this._projectionMatrix;
}
/** @type {mat4} */
get viewMatrix() {
return this._viewMatrix;
}
/** @type {mat4} */
get modelMatrix() {
return this._modelMatrix;
}
/** @type {Map} */
get stats() {
return this._stats;
}
/** @type {string} */
get statsText() {
if (!this._collectStats) {
return '';
}
const { _stats } = this;
const deltaTime = _stats.get('delta-time');
const passedTime = _stats.get('passed-time');
const fps = `FPS: ${(1000 / deltaTime) | 0} (${1000 / deltaTime})`;
const dt = `Delta time: ${deltaTime | 0} ms (${deltaTime})`;
const pt = `Passed time: ${passedTime | 0} ms (${passedTime})`;
const sc = `Shader changes: ${_stats.get('shader-changes')}`;
const f = `Frames: ${_stats.get('frames')}`;
const s = `Shaders: ${_stats.get('shaders')}`;
const t = `Textures: ${_stats.get('textures')}`;
const rt = `Render targets: ${_stats.get('renderTargets')}`;
const e = `Extensions:${_stats.get('extensions').map(e => `\n - ${e}`).join()}`;
return `${fps}\n${dt}\n${pt}\n${sc}\n${f}\n${s}\n${t}\n${rt}\n${e}`;
}
/**
* Constructor.
* Automaticaly binds into specified canvas.
*
* @param {string} canvas - HTML canvas element id.
* @param {boolean} optimize - Optimize rendering pipeline.
* @param {Array.<string>} extensions - array with WebGL extensions list.
* @param {number} contextVersion - WebGL context version number.
* @param {boolean} manualMode - Manually trigger rendering next frames.
*/
constructor(canvas, optimize = true, extensions = null, contextVersion = 1, manualMode = false) {
super();
this._manualMode = !!manualMode;
this._extensions = new Map();
this._contextVersion = contextVersion | 0;
this._useDevicePixelRatio = false;
this._timeScale = 1;
this._collectStats = false;
this._animationFrame = 0;
this._lastTimestamp = null;
this._canvas = null;
this._context = null;
this._shaders = new Map();
this._textures = new Map();
this._renderTargets = new Map();
this._renderTargetsStack = [];
this._events = new Events();
this._activeShader = null;
this._activeRenderTarget = null;
this._activeViewportSize = vec2.create();
this._clearColor = vec4.create();
this._projectionMatrix = mat4.create();
this._viewMatrix = mat4.create();
this._modelMatrix = mat4.create();
this._blendingConstants = {};
this._stats = new Map();
this._counterShaderChanges = 0;
this._counterFrames = 0;
this._optimize = !!optimize;
this._passedTime = 0;
this._shaderApplierOut = mat4.create();
this._shaderApplierGetValue = name => {
if (name === 'model-matrix') {
return this._modelMatrix;
} else if (name === 'view-matrix') {
return this._viewMatrix;
} else if (name === 'projection-matrix') {
return this._projectionMatrix;
} else {
throw new Error(`Unknown matrix: ${name}`);
}
};
this.__onFrame = this._onFrame.bind(this);
if (!!extensions) {
for (const name of extensions) {
this._extensions.set(name, null);
}
}
this._setup(canvas);
}
/**
* Destructor (disposes internal resources).
*
* @example
* system.dispose();
* sustem = null;
*/
dispose() {
const { _context, _shaders, _textures, _renderTargets, _events } = this;
this._stopAnimation();
_context.clear(_context.COLOR_BUFFER_BIT);
for (const shader of _shaders.keys()) {
this.unregisterShader(shader);
}
for (const texture of _textures.keys()) {
this.unregisterTexture(texture);
}
for (const renderTarget of _renderTargets.keys()) {
this.unregisterRenderTarget(renderTarget);
}
_events.dispose();
this._extensions = null;
this._lastTimestamp = null;
this._canvas = null;
this._context = null;
this._shaders = null;
this._textures = null;
this._renderTargets = null;
this._renderTargetsStack = null;
this._events = null;
this._activeShader = null;
this._activeRenderTarget = null;
this._activeViewportSize = null;
this._clearColor = null;
this._projectionMatrix = null;
this._viewMatrix = null;
this._modelMatrix = null;
this._blendingConstants = null;
this._stats = null;
this._shaderApplierOut = null;
this._shaderApplierGetValue = null;
this.__onFrame = null;
}
/**
* Get loaded WebGL extension by it's name.
*
* @param {string} name - Extension name.
*
* @return {*|null} WebGL extension or null if not found.
*
* @example
* const extension = system.extension('vertex_array_object');
* if (!!extension) {
* const vao = extension.createVertexArrayOES();
* extension.bindVertexArrayOES(vao);
* }
*/
extension(name) {
return this._extensions.get(name) || null;
}
/**
* Load WebGL extension by it's name.
*
* @param {string} name - Extension name.
*
* @return {*|null} WebGL extension or null if not supported.
*
* @example
* const extension = system.requestExtension('vertex_array_object');
* if (!!extension) {
* const vao = extension.createVertexArrayOES();
* extension.bindVertexArrayOES(vao);
* }
*/
requestExtension(name) {
const { _context, _contextVersion, _extensions } = this;
if (!_context) {
throw new Error('WebGL context is not yet ready!');
}
let ext = _extensions.get(name);
if (!!ext) {
return ext;
}
const meta = extensions[name];
if (!meta) {
throw new Error(`Unsupported extension: ${name}`);
}
ext = getExtensionByVersion(meta, _context, _contextVersion);
if (!!ext) {
_extensions.set(name, ext);
} else {
console.warn(`Could not get WebGL extension: ${name}`);
}
return ext || null;
}
/**
* Load WebGL extensions by their names.
*
* @param {string[]} args - Extension names.
*
* @return {boolean} True if all are supported and loaded, false otherwise.
*
* @example
* const supported = system.requestExtensions('texture_float', 'texture_float_linear');
* if (!supported) {
* throw new Error('One of requested WebGL extensions is not supported!');
* }
*/
requestExtensions(...args) {
for (const arg of args) {
if (!this.requestExtension(arg)) {
return false;
}
}
return true;
}
/**
* Execute rendering command.
*
* @param {Command} command - command to execute.
* @param {number} deltaTime - Delta time.
* @param {string|null} layer - Layer ID.
*/
executeCommand(command, deltaTime, layer) {
if (!(command instanceof Command)) {
throw new Error('`command` is not type of Command!');
}
if (typeof deltaTime !== 'number') {
throw new Error('`deltaTime` is not type of Number!');
}
command.onRender(this._context, this, deltaTime, layer);
}
/**
* Register new shader.
*
* @param {string} id - Shader id.
* @param {string} vertex - Vertex shader code.
* @param {string} fragment - Fragment shader code.
* @param {*} layoutInfo - Vertex layout description.
* @param {*} uniformsInfo - Uniforms description.
* @param {*} samplersInfo - Samplers description.
* @param {*} blendingInfo - Blending mode description.
* @param {string[]|null} extensionsInfo - Required extensions list.
*
* @example
* system.registerShader(
* 'red',
* 'attribute vec2 aPosition;\nvoid main() { gl_Position = vec4(aPosition, 0.0, 1.0); }',
* 'void main() { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); }',
* { aPosition: { size: 2, stride: 2, offset: 0 } },
* {},
* { source: 'src-alpha', destination: 'one-minus-src-alpha' }
* );
*/
registerShader(
id,
vertex,
fragment,
layoutInfo,
uniformsInfo,
samplersInfo,
blendingInfo,
extensionsInfo
) {
if (typeof id !== 'string') {
throw new Error('`id` is not type of String!');
}
if (typeof vertex !== 'string') {
throw new Error('`vertex` is not type of String!');
}
if (typeof fragment !== 'string') {
throw new Error('`fragment` is not type of String!');
}
if (!layoutInfo) {
throw new Error('`layoutInfo` cannot be null!');
}
this.unregisterShader(id);
if (Array.isArray(extensionsInfo) && extensionsInfo.length > 0) {
if (!this.requestExtensions(...extensionsInfo)) {
throw new Error(`One of shader extensions is not supported (${id})!`);
}
}
const gl = this._context;
const shader = gl.createProgram();
const vshader = gl.createShader(gl.VERTEX_SHADER);
const fshader = gl.createShader(gl.FRAGMENT_SHADER);
const deleteAll = () => {
gl.deleteShader(vshader);
gl.deleteShader(fshader);
gl.deleteProgram(shader);
};
// TODO: fix problem with forced GLSL 3 in WebGL 2.
// const { _contextVersion } = this;
// if (_contextVersion > 1) {
// vertex = `#version 300 es\n#define OXY_ctx_ver ${_contextVersion}\n${vertex}`;
// fragment = `#version 300 es\n#define OXY_ctx_ver ${_contextVersion}\n${fragment}`;
// } else {
// vertex = `#define OXY_ctx_ver ${_contextVersion}\n${vertex}`;
// fragment = `#define OXY_ctx_ver ${_contextVersion}\n${fragment}`;
// }
gl.shaderSource(vshader, vertex);
gl.shaderSource(fshader, fragment);
gl.compileShader(vshader);
gl.compileShader(fshader);
if (!gl.getShaderParameter(vshader, gl.COMPILE_STATUS)) {
const log = gl.getShaderInfoLog(vshader);
deleteAll();
throw new Error(`Cannot compile vertex shader: ${id}\nLog: ${log}`);
}
if (!gl.getShaderParameter(fshader, gl.COMPILE_STATUS)) {
const log = gl.getShaderInfoLog(fshader);
deleteAll();
throw new Error(`Cannot compile fragment shader: ${id}\nLog: ${log}`);
}
gl.attachShader(shader, vshader);
gl.attachShader(shader, fshader);
gl.linkProgram(shader);
if (!gl.getProgramParameter(shader, gl.LINK_STATUS)) {
const log = gl.getProgramInfoLog(shader);
deleteAll();
throw new Error(`Cannot link shader program: ${id}\nLog: ${log}`);
}
const layout = new Map();
const uniforms = new Map();
const samplers = new Map();
let blending = null;
for (const name in layoutInfo) {
const { size, stride, offset } = layoutInfo[name];
if (typeof size !== 'number' ||
typeof stride !== 'number' ||
typeof offset !== 'number'
) {
deleteAll();
throw new Error(
`Shader layout does not have proper settings: ${id} (${name})`
);
}
const location = gl.getAttribLocation(shader, name);
if (location < 0) {
deleteAll();
throw new Error(
`Shader does not have attribute: ${id} (${name})`
);
}
layout.set(name, {
location,
size,
stride,
offset
});
}
if (layout.size === 0) {
deleteAll();
throw new Error(`Shader layout cannot be empty: ${id}`);
}
if (!!uniformsInfo) {
for (const name in uniformsInfo) {
const mapping = uniformsInfo[name];
if (typeof mapping !== 'string' &&
typeof mapping !== 'number' &&
!(mapping instanceof Array)
) {
deleteAll();
throw new Error(
`Shader uniform does not have proper settings: ${id} (${name})`
);
}
let func = null;
if (typeof mapping === 'string' && mapping.startsWith('@')) {
func = functions[mapping];
if (!func) {
func = functions[mapping] = makeApplierFunction(mapping);
}
}
const location = gl.getUniformLocation(shader, name);
if (!location) {
deleteAll();
throw new Error(
`Shader does not have uniform: ${id} (${name})`
);
}
const forcedUpdate =
!!func ||
mapping === 'projection-matrix' ||
mapping === 'view-matrix' ||
mapping === 'model-matrix' ||
mapping === 'time' ||
mapping === 'viewport-size' ||
mapping === 'inverse-viewport-size';
uniforms.set(name, {
location,
mapping: !func ? mapping : func,
forcedUpdate
});
}
}
if (!!samplersInfo) {
for (const name in samplersInfo) {
const { channel, texture, filtering } = samplersInfo[name];
if (typeof channel !== 'number' ||
(!!texture && typeof texture !== 'string') ||
(!!filtering && typeof filtering !== 'string')
) {
deleteAll();
throw new Error(
`Shader sampler does not have proper settings: ${id} (${name})`
);
}
const location = gl.getUniformLocation(shader, name);
if (!location) {
deleteAll();
throw new Error(
`Shader does not have sampler: ${id} (${name})`
);
}
samplers.set(name, {
location,
channel,
texture,
filtering
});
}
}
if (!!blendingInfo) {
const { source, destination } = blendingInfo;
if (typeof source !== 'string' || typeof destination !== 'string') {
throw new Error(`Shader blending does not have proper settings: ${id}`);
}
blending = {
source: this._getBlendingFromName(source),
destination: this._getBlendingFromName(destination)
};
}
this._shaders.set(id, { shader, layout, uniforms, samplers, blending });
}
/**
* Unregister existing shader.
*
* @param {string} id - Shader id.
*
* @example
* system.unregisterShader('red');
*/
unregisterShader(id) {
const { _shaders } = this;
const gl = this._context;
const meta = _shaders.get(id);
if (!meta) {
return;
}
const { shader } = meta;
const shaders = gl.getAttachedShaders(shader);
for (let i = 0, c = shaders.length; i < c; ++i) {
gl.deleteShader(shaders[i]);
}
gl.deleteProgram(shader);
_shaders.delete(id);
}
/**
* Enable given shader (make it currently active for further rendering).
*
* @param {string} id - Shader id.
* @param {boolean} forced - ignore optimizations (by default it will not enable if is currently active).
*
* @example
* system.enableShader('red');
*/
enableShader(id, forced = false) {
const {
_shaders,
_textures,
_activeShader,
_projectionMatrix,
_viewMatrix,
_modelMatrix,
_optimize,
_passedTime
} = this;
const changeShader = forced || _activeShader !== id || !_optimize;
const gl = this._context;
const meta = _shaders.get(id);
if (!meta) {
console.warn(`Trying to enable non-existing shader: ${id}`);
return;
}
const { shader, layout, uniforms, samplers, blending } = meta;
if (changeShader) {
gl.useProgram(shader);
this._activeShader = id;
++this._counterShaderChanges;
}
for (const { location, size, stride, offset } of layout.values()) {
gl.vertexAttribPointer(
location,
size,
gl.FLOAT,
false,
stride * 4,
offset * 4
);
gl.enableVertexAttribArray(location);
}
for (const [name, { location, mapping, forcedUpdate }] of uniforms.entries()) {
const { length } = mapping;
if (mapping === '' || (!changeShader && !forcedUpdate)) {
continue;
} else if (mapping === 'projection-matrix') {
gl.uniformMatrix4fv(location, false, _projectionMatrix);
} else if (mapping === 'view-matrix') {
gl.uniformMatrix4fv(location, false, _viewMatrix);
} else if (mapping === 'model-matrix') {
gl.uniformMatrix4fv(location, false, _modelMatrix);
} else if (mapping === 'time') {
gl.uniform1f(location, _passedTime * 0.001);
} else if (mapping === 'viewport-size') {
gl.uniform2f(
location,
this._activeViewportSize[0],
this._activeViewportSize[1]
);
} else if (mapping === 'inverse-viewport-size') {
const [ width, height ] = this._activeViewportSize;
gl.uniform2f(
location,
width === 0 ? 1 : 1 / width,
height === 0 ? 1 : 1 / height
);
} else if (typeof mapping === 'number') {
gl.uniform1f(location, mapping);
} else if (length === 2) {
gl.uniform2fv(location, mapping);
} else if (length === 3) {
gl.uniform3fv(location, mapping);
} else if (length === 4) {
gl.uniform4fv(location, mapping);
} else if (length === 9) {
gl.uniformMatrix3fv(location, false, mapping);
} else if (length === 16) {
gl.uniformMatrix4fv(location, false, mapping);
} else if (mapping instanceof Function) {
mapping(
location,
gl,
this._shaderApplierOut,
this._shaderApplierGetValue,
mat4
);
} else {
console.warn(`Trying to set non-proper uniform: ${name} (${id})`);
}
}
if (!changeShader) {
return;
}
for (const { location, channel, texture, filtering } of samplers.values()) {
const tex = _textures.get(texture);
if (!tex) {
console.warn(`Trying to enable non-existing texture: ${texture} (${id})`);
continue;
}
gl.activeTexture(gl.TEXTURE0 + channel | 0);
gl.bindTexture(gl.TEXTURE_2D, tex.texture);
if (filtering === 'trilinear') {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
} else if (filtering === 'bilinear') {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_LINEAR);
} else if (filtering === 'linear') {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
} else {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
}
gl.uniform1i(location, channel | 0);
}
if (!!blending) {
gl.enable(gl.BLEND);
gl.blendFunc(blending.source, blending.destination);
} else {
gl.disable(gl.BLEND);
}
}
/**
* Disable active shader.
* Make sure that this is currently active shader (otherwise it will unbind wrong shader locations)!
*
* @example
* system.enableShader('red');
* system.disableShader();
*/
disableShader() {
const gl = this._context;
const meta = this._shaders.get(this._activeShader);
if (!meta) {
console.warn(`Trying to disable non-existing shader: ${this._activeShader}`);
return;
}
const { layout } = meta;
for (const { location } of layout.values()) {
gl.disableVertexAttribArray(location);
}
}
/**
* Give active shader uniform a different than it's default value.
*
* @param {string} name - Uniform name.
* @param {*} value - Uniform value. Can be number of array of numbers.
*
* @example
* system.enableShader('color');
* system.overrideShaderUniform('uColor', [1, 0, 0, 1]);
*/
overrideShaderUniform(name, value) {
const { _shaders, _activeShader } = this;
const gl = this._context;
const meta = _shaders.get(_activeShader);
if (!meta) {
console.warn(`Trying to set uniform of non-existing shader: ${_activeShader}`);
return;
}
const { uniforms } = meta;
const uniform = uniforms.get(name);
if (!uniform) {
console.warn(`Trying to set value of non-existing uniform: ${_activeShader} (${name})`);
return;
}
const { location } = uniform;
const { length } = value;
if (typeof value === 'number') {
gl.uniform1f(location, value);
} else if (length === 2) {
gl.uniform2fv(location, value);
} else if (length === 3) {
gl.uniform3fv(location, value);
} else if (length === 4) {
gl.uniform4fv(location, value);
} else if (length === 9) {
gl.uniformMatrix3fv(location, false, value);
} else if (length === 16) {
gl.uniformMatrix4fv(location, false, value);
}
}
/**
* Give active shader sampler different than it's default texture.
*
* @param {string} name - Sampler id.
* @param {string|null} texture - Texture id.
* @param {string|null} filtering - Sampler filtering. Can be trilinear, bilinear, linear or nearest.
*
* @example
* system.enableShader('sprite');
* system.overrideShaderSampler('sTexture', 'martian', 'linear');
*/
overrideShaderSampler(name, texture, filtering) {
const { _shaders, _textures, _activeShader } = this;
const gl = this._context;
const meta = _shaders.get(_activeShader);
if (!meta) {
console.warn(`Trying to set sampler of non-existing shader: ${_activeShader}`);
return;
}
const { samplers } = meta;
const sampler = samplers.get(name);
if (!sampler) {
console.warn(`Trying to set non-existing sampler: ${_activeShader} (${name})`);
return;
}
texture = texture || sampler.texture;
filtering = filtering || sampler.filtering;
const tex = _textures.get(texture);
if (!tex) {
console.warn(`Trying to enable non-existing texture: ${texture} (${name})`);
return;
}
const { location, channel } = sampler;
gl.activeTexture(gl.TEXTURE0 + channel | 0);
gl.bindTexture(gl.TEXTURE_2D, tex.texture);
if (filtering === 'trilinear') {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
} else if (filtering === 'bilinear') {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_LINEAR);
} else if (filtering === 'linear') {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
} else {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
}
gl.uniform1i(location, channel | 0);
}
/**
* Register new texture.
*
* @param {string} id - Texture id.
* @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} image - Image, canvas or video instance.
* @param {boolean} generateMipmap - Should generate mipmaps.
*
* @example
* const image = new Image();
* image.src = 'martian.png';
* system.registerTexture('martian', image);
*/
registerTexture(id, image, generateMipmap = false) {
this.unregisterTexture(id);
const gl = this._context;
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.bindTexture(gl.TEXTURE_2D, null);
this._textures.set(id, {
texture,
width: image.width,
height: image.height
});
if (!!generateMipmap) {
this.generateTextureMipmap(id);
}
}
/**
* Register empty texture (mostly used in offscreen rendering cases).
*
* @param {string} id - Texture id.
* @param {number} width - Width.
* @param {number} height - Height.
* @param {boolean} floatPointData - Tells if this texture will store floating point data.
* @param {ArrayBufferView|null} pixelData - ArrayBuffer view with pixel data or null if empty.
*
* @example
* system.registerTextureEmpty('offscreen', 512, 512);
*/
registerTextureEmpty(id, width, height, floatPointData = false, pixelData = null) {
if (!!floatPointData && !this.requestExtensions(
'texture_float',
'texture_float_linear'
)) {
throw new Error('Float textures are not supported!');
}
this.unregisterTexture(id);
const gl = this._context;
width = Math.max(1, width | 0);
height = Math.max(1, height | 0);
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
width,
height,
0,
gl.RGBA,
!!floatPointData ? gl.FLOAT : gl.UNSIGNED_BYTE,
pixelData
);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.bindTexture(gl.TEXTURE_2D, null);
this._textures.set(id, {
texture,
width,
height
});
}
/**
* Register colored texture (mostly used to create solid color textures).
*
* @param {string} id - Texture id.
* @param {number} width - Width.
* @param {number} height - Height.
* @param {number} r - Red value.
* @param {number} g - Green value.
* @param {number} b - Blue value.
* @param {number} a - Alpha value.
*
* @example
* system.registerTextureEmpty('offscreen', 512, 512);
*/
registerTextureColor(id, width, height, r, g, b, a) {
const c = width * height * 4;
const data = new Uint8Array(c);
for (let i = 0; i < c; i += 4) {
data[i] = r;
data[i + 1] = g;
data[i + 2] = b;
data[i + 3] = a;
}
return this.registerTextureEmpty(id, width, height, false, data);
}
/**
* Unregister existing texture.
*
* @param {string} id - Texture id.
*
* @example
* system.unregisterTexture('red');
*/
unregisterTexture(id) {
const { _textures } = this;
const gl = this._context;
const texture = _textures.get(id);
if (!!texture) {
gl.deleteTexture(texture.texture);
_textures.delete(id);
}
}
/**
* Get texture meta information (width and height).
*
* @param {string} id - Texture id.
*
* @return {*|null} Object with width and height properties or null if not found.
*/
getTextureMeta(id) {
const { _textures } = this;
const texture = _textures.get(id);
return !!texture
? { width: texture.width, height: texture.height }
: null;
}
/**
* Try to generate mipmaps for given texture.
*
* @param {string} id - Texture id.
*/
generateTextureMipmap(id) {
const { _textures } = this;
const gl = this._context;
const texture = _textures.get(id);
if (!!texture) {
if ((!isPOT(texture.width, texture.height)) && this._contextVersion < 2) {
console.warn(
'Cannot generate mipmaps for non-POT texture within version < 2'
);
return;
}
gl.bindTexture(gl.TEXTURE_2D, texture.texture);
gl.generateMipmap(gl.TEXTURE_2D);
gl.bindTexture(gl.TEXTURE_2D, null);
}
}
/**
* Register new render target.
*
* @param {string} id - Render target id.
* @param {number} width - Width.
* @param {number} height - Height.
* @param {boolean} floatPointData - Tells if render target will store floating point data.
*
* @example
* system.registerRenderTarget('offscreen', 512, 512);
*/
registerRenderTarget(
id,
width,
height,
floatPointData = false
) {
if (!!floatPointData && !this.requestExtensions(
'texture_float',
'texture_float_linear'
)) {
throw new Error('Float textures are not supported!');
}
this.unregisterRenderTarget(id);
const gl = this._context;
width = Math.max(1, width);
height = Math.max(1, height);
this.registerTextureEmpty(id, width, height, floatPointData);
const texture = this._textures.get(id);
if (!texture) {
return;
}
const target = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, target);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D,
texture.texture,
0
);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
this._renderTargets.set(id, {
target,
width,
height,
multiTargets: null,
textures: [ texture ]
});
}
/**
* Register new multiple render target.
*
* @param {string} id - Render target id.
* @param {number} width - Width.
* @param {number} height - Height.
* @param {number|*[]} targets - Number of render targets or array with target descriptors.
*
* @example
* system.registerRenderTargetMulti('offscreen', 512, 512, 2);
*/
registerRenderTargetMulti(id, width, height, targets) {
if (!this.requestExtensions('draw_buffers')) {
throw new Error('Draw buffers are not supported!');
}
this.unregisterRenderTarget(id);
const gl = this._context;
width = Math.max(1, width);
height = Math.max(1, height);
const isArray = Array.isArray(targets);
const c = isArray ? targets.length : (targets | 0);
const ext = this.extension('draw_buffers');
const textures = [];
const buffers = [];
if (isArray) {
for (let i = 0; i < c; ++i) {
const target = targets[i];
const tid = `${id}-${i}`;
const w = 'width' in target ? Math.max(1, target.width | 0) : width;
const h = 'height' in target ? Math.max(1, target.height | 0) : height;
this.registerTextureEmpty(tid, w, h, !!target.floatPointData);
const texture = this._textures.get(tid);
if (!texture) {
return;
}
textures.push(texture);
buffers.push(ext.COLOR_ATTACHMENT0_WEBGL + i);
}
} else {
for (let i = 0; i < c; ++i) {
const tid = `${id}-${i}`;
this.registerTextureEmpty(tid, width, height, false);
const texture = this._textures.get(tid);
if (!texture) {
return;
}
textures.push(texture);
buffers.push(ext.COLOR_ATTACHMENT0_WEBGL + i);
}
}
const target = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, target);
for (let i = 0; i < c; ++i) {
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
buffers[i],
gl.TEXTURE_2D,
textures[i].texture,
0
);
}
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
this._renderTargets.set(id, {
target,
width,
height,
multiTargets: buffers,
textures
});
}
/**
* Unregister existing render target.
*
* @param {string} id - Render target id.
*
* @example
* system.unregisterRenderTarget('offscreen');
*/
unregisterRenderTarget(id) {
const { _renderTargets } = this;
const gl = this._context;
const target = _renderTargets.get(id);
if (!!target) {
if (target.multiTargets && target.multiTargets.length > 0) {
for (let i = 0; i < target.multiTargets.length; ++i) {
this.unregisterTexture(`${id}-${i}`);
}
} else {
this.unregisterTexture(id);
}
gl.deleteFramebuffer(target.target);
_renderTargets.delete(id);
target.textures = null;
target.multiTargets = null;
}
}
/**
* Get render target meta information (width and height).
*
* @param {string} id - Texture id.
*
* @return {*|null} Object with width and height properties or null if not found.
*/
getRenderTargetMeta(id) {
const { _renderTargets } = this;
const target = _renderTargets.get(id);
return !!target
? {
width: target.width,
height: target.height,
targets: !!target.multiTargets ? target.multiTargets.length : 0
}
: null;
}
/**
* Make given render target active for further rendering.
*
* @param {string} id - Render target id
* @param {bool} clearBuffer - clear buffer.
*
* @example
* system.enableRenderTarget('offscreen');
*/
enableRenderTarget(id, clearBuffer = true) {
const { _renderTargets } = this;
const gl = this._context;
const target = _renderTargets.get(id);
if (!target) {
this.disableRenderTarget();
return;
}
gl.bindFramebuffer(gl.FRAMEBUFFER, target.target);
if (!!target.multiTargets) {
gl.drawBuffers(target.multiTargets);
}
gl.viewport(0, 0, target.width, target.height);
gl.scissor(0, 0, target.width, target.height);
vec2.set(this._activeViewportSize, target.width, target.height);
if (!!clearBuffer) {
gl.clear(gl.COLOR_BUFFER_BIT);
}
this._activeRenderTarget = id;
}
/**
* Disable active render target.
*
* @example
* system.disableRenderTarget();
*/
disableRenderTarget() {
const { _context, _canvas, _activeRenderTarget } = this;
if (!_activeRenderTarget) {
return;
}
const target = this._renderTargets.get(_activeRenderTarget);
const { width, height } = _canvas;
if (!!target.multiTargets) {
_context.drawBuffers([]);
}
_context.bindFramebuffer(_context.FRAMEBUFFER, null);
_context.viewport(0, 0, width, height);
_context.scissor(0, 0, width, height);
vec2.set(this._activeViewportSize, width, height);
this._activeRenderTarget = null;
}
/**
* Push current render target on stack and make given render target active for further rendering.
*
* @param {string} id - Render target id
* @param {bool} clearBuffer - clear buffer.
*
* @example
* system.pushRenderTarget('offscreen');
*/
pushRenderTarget(id, clearBuffer) {
this._renderTargetsStack.push(this._activeRenderTarget);
this.enableRenderTarget(id, clearBuffer);
}
/**
* Enable last render target stored on stack (or disable if stack is empty).
*
* @example
* system.popRenderTarget();
*/
popRenderTarget() {
const last = this._renderTargetsStack.pop();
if (!last) {
this.disableRenderTarget();
} else {
this.enableRenderTarget(last, false);
}
}
/**
* Tells if there is registered given shader.
*
* @param {string} id - Shader id.
*
* @return {boolean}
*/
hasShader(id) {
return this._shaders.has(id);
}
/**
* Tells if there is registered given texture.
*
* @param {string} id - Texture id.
*
* @return {boolean}
*/
hasTexture(id) {
return this._textures.has(id);
}
/**
* Tells if there is registered given render target.
*
* @param {string} id - Render target id.
*
* @return {boolean}
*/
hasRenderTarget(id) {
return this._renderTargets.has(id);
}
/**
* Resize frame buffer to match canvas size.
*
* @param {boolean} forced - True if ignore optimizations.
*/
resize(forced = false) {
const { _canvas, _context } = this;
let { width, height, clientWidth, clientHeight } = _canvas;
if (this._useDevicePixelRatio) {
const { devicePixelRatio } = window;
clientWidth = (clientWidth * devicePixelRatio) | 0;
clientHeight = (clientHeight * devicePixelRatio) | 0;
}
if (forced || width !== clientWidth || height !== clientHeight) {
_canvas.width = clientWidth;
_canvas.height = clientHeight;
_context.viewport(0, 0, clientWidth, clientHeight);
_context.scissor(0, 0, clientWidth, clientHeight);
vec2.set(this._activeViewportSize, clientWidth, clientHeight);
this._events.trigger('resize', clientWidth, clientHeight);
}
}
renderFrame() {
if (!this._manualMode) {
console.warn('Trying to manually render frame without manual render mode!');
return;
}
this._onFrame(this._lastTimestamp);
}
/**
* @override
*/
onRegister() {
this._startAnimation();
}
/**
* @override
*/
onUnregister() {
this._stopAnimation();
}
_setup(canvas) {
if (typeof canvas === 'string') {
canvas = document.getElementById(canvas);
}
if (!(canvas instanceof HTMLCanvasElement)) {
throw new Error('`canvas` is not type of either HTMLCanvasElement or String!');
}
this._canvas = canvas;
let { _contextVersion } = this;
const options = {
alpha: false,
depth: false,
stencil: false,
antialias: false,
premultipliedAlpha: false,
preserveDrawingBuffer: false,
failIfMajorPerformanceCaveat: false
};
let version = versions.reduce((r, v) => {
if (!!r || v[0] > _contextVersion) {
return r;
}
const gl =
canvas.getContext(v[1], options) ||
canvas.getContext(`experimental-${v[1]}`, options);
return !!gl ? { context: gl, contextVersion: v[0] } : r;
}, null);
if (!version) {
throw new Error(
`Cannot create WebGL context for version: ${_contextVersion}`
);
}
const gl = this._context = version.context;
this._contextVersion = version.contextVersion;
for (const name of this._extensions.keys()) {
this.requestExtension(name);
}
gl.enable(gl.SCISSOR_TEST);
gl.viewport(0, 0, canvas.width, canvas.height);
gl.scissor(0, 0, canvas.width, canvas.height);
vec2.set(this._activeViewportSize, canvas.width, canvas.height);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.clear(gl.COLOR_BUFFER_BIT);
this.registerTextureColor(
'',
1, 1,
255, 255, 255, 255
);
this.registerTextureColor(
'#default-albedo',
1, 1,
255, 255, 255, 255
);
this.registerTextureColor(
'#default-normal',
1, 1,
(255 * 0.5) | 0,
(255 * 0.5) | 0,
255,
255
);
this.registerTextureColor(
'#default-metalness-smoothness-emission',
1, 1,
0, 0, 0, 255
);
this.registerTextureColor(
'#default-environment',
1, 1,
0, 0, 0, 255
);
this._blendingConstants = {
'zero': gl.ZERO,
'one': gl.ONE,
'src-color': gl.SRC_COLOR,
'one-minus-src-color': gl.ONE_MINUS_SRC_COLOR,
'dst-color': gl.DST_COLOR,
'one-minus-dst-color': gl.ONE_MINUS_DST_COLOR,
'src-alpha': gl.SRC_ALPHA,
'one-minus-src-alpha': gl.ONE_MINUS_SRC_ALPHA,
'dst-alpha': gl.DST_ALPHA,
'one-minus-dst-alpha': gl.ONE_MINUS_DST_ALPHA,
'constant-color': gl.CONSTANT_COLOR,
'one-minus-constant-color': gl.ONE_MINUS_CONSTANT_COLOR,
'constant-alpha': gl.CONSTANT_ALPHA,
'one-minus-constant-alpha': gl.ONE_MINUS_CONSTANT_ALPHA,
'src-alpha-saturate': gl.SRC_ALPHA_SATURATE
};
}
_startAnimation() {
this._stopAnimation();
this._passedTime = 0;
this._lastTimestamp = performance.now();
this._requestFrame();
}
_stopAnimation() {
cancelAnimationFrame(this._animationFrame);
this._passedTime = 0;
this._lastTimestamp = null;
}
_requestFrame() {
if (!!this._manualMode) {
return;
}
this._animationFrame = requestAnimationFrame(this.__onFrame);
}
_onFrame(timestamp) {
this.resize();
const { _clearColor, _stats, _counterShaderChanges } = this;
const [ cr, cg, cb, ca ] = _clearColor;
const gl = this._context;
const deltaTime = (timestamp - this._lastTimestamp) * this._timeScale;
this._passedTime += deltaTime;
this._lastTimestamp = timestamp;
this._counterShaderChanges = 0
this._activeShader = null;
this._activeRenderTarget = null;
gl.clearColor(cr, cg, cb, ca);
gl.clear(gl.COLOR_BUFFER_BIT);
this.events.trigger('render', gl, this, deltaTime);
if (!!this._collectStats) {
_stats.set('delta-time', deltaTime);
_stats.set('passed-time', this._passedTime);
_stats.set('shader-changes', _counterShaderChanges);
_stats.set('frames', ++this._counterFrames);
_stats.set('shaders', this._shaders.size);
_stats.set('textures', this._textures.size);
_stats.set('renderTargets', this._renderTargets.size);
_stats.set('extensions', [...this._extensions.keys()]);
}
if (this._renderTargetsStack.length > 0) {
console.warn(
`There are ${this._renderTargetsStack.length} render targets on stack after frame!`
);
this._renderTargetsStack = [];
this.disableRenderTarget();
}
this._requestFrame();
}
_getBlendingFromName(name) {
const { _blendingConstants } = this;
if (!(name in _blendingConstants)) {
throw new Error(`There is no blending function: ${name}`);
}
return _blendingConstants[name];
}
} |
JavaScript | class Dictionary extends React.Component {
constructor(props) {
super(props);
this.state = {
//Given to us by Search
searchResults: [],
showTopicChooser: false,
createData: false,
statusMessage: "",
displayMain: "main",
finalResult: false,
inCreatorMode: false
}
}
//showSearch needs to take the name of the pressed topic as a parameter.
//When showSearch state is changed, it will be trusly,and we show search form.
giveSearchResultsToDictionary(searchResults) {
this.setState({searchResults: searchResults});
}
topicSelected(topic) {
this.props.giveTopicToMainApp(topic);
}
handleFinalResult(finalResult) {
this.setState({finalResult: finalResult,
displayMain: "finalResult",
searchResults: []});
}
showCreateForm() {
// Denne funksjonen er litt treg, burde fikse den da det ofte blir nødvendig med 2 klikk.
(this.state.inCreatorMode) ? this.setState({inCreatorMode: false}) : this.setState({inCreatorMode: true});
(this.state.displayMain !== "createForm") ?
this.setState({displayMain: "createForm"}) :
this.setState({displayMain: "main"})
}
// handleCreateSubmit just takes info from create to update state. Everything with creations happends in create.js
handleCreateSubmit(success) {
// need to post data to server.
(this.state.inCreatorMode) ? this.setState({inCreatorMode: false}) : this.setState({inCreatorMode: true});
if(success) {
this.setState({displayMain: "main", statusMessage: "Succesfully saved to database!"});
}
else {
this.setState({displayMain: "main", statusMessage: "Failed to save to database!"});
}
}
handleDocumentDeletion(success) {
if(success) {
this.setState({displayMain: "main", statusMessage: "Succesfully deleted from database!"});
}
else {
this.setState({displayMain: "main", statusMessage: "Failed to delete from database!"});
}
}
render() {
return (
<section className="dictionaryWrapper">
<header className="dictionaryHeader">
<div className="dictionaryHeaderStyleBox">
<h1>Dictionary</h1>
</div>
</header>
<nav className="dictionaryNav">
{this.props.isNotesActive ? null : (
<TopicChooser activeTopic={this.props.activeTopic}
loggedInUser={this.props.loggedInUser}
topicSelected={this.topicSelected.bind(this)}
inNotes={false}/>
)}
{this.props.activeTopic !== "Select topic" ? (
<DictionarySearch activeTopic={this.props.activeTopic}
giveSearchResultsToDictionary={this.giveSearchResultsToDictionary.bind(this)}
dictionaryWordSearch={this.props.dictionaryWordSearch}/>
) : null}
</nav>
<article className="dictionaryMainSection">
{(this.state.searchResults.length > 0) ?
<DictionarySearchResults searchResults={this.state.searchResults}
handleFinalResult={this.handleFinalResult.bind(this)}/>
: null}
{(this.state.displayMain === "finalResult" && this.state.searchResults.length == 0) ?
<DictionaryFinalResult finalResult={this.state.finalResult}
loggedInUser={this.props.loggedInUser}
handleDocumentDeletion={this.handleDocumentDeletion.bind(this)} /> :
null}
{(this.state.displayMain === "createForm" && this.state.searchResults.length == 0) ?
<DictionaryCreate topic={this.props.activeTopic}
handleCreateSubmit={this.handleCreateSubmit.bind(this)}/>
: null}
</article>
<footer className="dictionaryFooter">
{(this.props.loggedInUser !== "guest" && this.props.activeTopic !== "Select topic") ?
<DictionaryFooter showCreateForm={this.showCreateForm.bind(this)}
topic={this.props.activeTopic}
inCreatorMode={this.state.inCreatorMode}/>
: null }
</footer>
</section>
)
}
} |
JavaScript | class Backoff {
n = 0;
constructor(min, max) {
this.min = min;
this.max = max;
}
reset() {
this.n = 0;
}
next() {
if (this.n === 0) {
this.n = 1;
return this.min;
}
let dur = this.n * this.min;
if (dur > this.max) {
dur = this.max;
} else {
this.n *= 2;
}
return dur;
}
} |
JavaScript | class ObservedContext {
/**
* @param {INode} node
* @param {IRenderContext} renderContext
*/
constructor(node, renderContext) {
this.node = node;
this.graphComponent = renderContext.canvasComponent;
this.defsSupport = renderContext.svgDefsManager;
this.reset();
}
/**
* @param {IRenderContext} renderContext
*/
update(renderContext) {
this.defsSupport = renderContext.svgDefsManager;
}
/**
* Resets the context object to an empty object if none of the properties is used.
* @return {Object|null}
*/
reset() {
const oldState = this.observed;
this.observed = {};
if (
oldState &&
[
"tag",
"layout",
"zoom",
"selected",
"highlighted",
"focused",
].some((name) => oldState.hasOwnProperty(name))
) {
return oldState;
}
return null;
}
/**
* Checks the current state for changes and returns the differences to the old state.
* @param {Object} oldState
* @return {{change: boolean, delta: {}}}
*/
checkModification(oldState) {
const delta = {};
let change = false;
if (oldState.hasOwnProperty("layout")) {
const layout = this.node.layout;
const newValue = {
x: layout.x,
y: layout.y,
width: layout.width,
height: layout.height,
};
if (
newValue.x !== oldState.layout.x ||
newValue.y !== oldState.layout.y ||
newValue.width !== oldState.layout.width ||
newValue.height !== oldState.layout.height
) {
delta.layout = newValue;
change = true;
}
}
if (oldState.hasOwnProperty("zoom")) {
const newValue = this.graphComponent.zoom;
if (newValue !== oldState.zoom) {
delta.zoom = newValue;
change = true;
}
}
if (oldState.hasOwnProperty("tag")) {
const newValue = this.node.tag;
if (newValue !== oldState.tag) {
delta.tag = newValue;
change = true;
}
}
if (oldState.hasOwnProperty("selected")) {
const newValue = this.graphComponent.selection.selectedNodes.isSelected(
this.node
);
if (newValue !== oldState.selected) {
delta.selected = newValue;
change = true;
}
}
if (oldState.hasOwnProperty("highlighted")) {
const newValue = this.graphComponent.highlightIndicatorManager.selectionModel.isSelected(
this.node
);
if (newValue !== oldState.highlighted) {
delta.highlighted = newValue;
change = true;
}
}
if (oldState.hasOwnProperty("focused")) {
const newValue =
this.graphComponent.focusIndicatorManager.focusedItem === this.node;
if (newValue !== oldState.focused) {
delta.focused = newValue;
change = true;
}
}
return {
change,
delta,
};
}
/**
* Returns the layout.
* @return {{x, y, height, width:}}
*/
get layout() {
if (this.observed.hasOwnProperty("layout")) {
return this.observed.layout;
}
const layout = this.node.layout;
const val = {
x: layout.x,
y: layout.y,
height: layout.height,
width: layout.width,
};
return (this.observed.layout = val);
}
/**
* Returns the zoom level.
* @return {number}
*/
get zoom() {
if (this.observed.hasOwnProperty("zoom")) {
return this.observed.zoom;
}
return (this.observed.zoom = this.graphComponent.zoom);
}
/**
* Returns the tag.
* @return {Object}
*/
get tag() {
if (this.observed.hasOwnProperty("tag")) {
return this.observed.tag;
}
return (this.observed.tag = this.node.tag);
}
/**
* Returns the selected state.
* @return {boolean}
*/
get selected() {
if (this.observed.hasOwnProperty("selected")) {
return this.observed.selected;
}
return (this.observed.selected = this.graphComponent.selection.selectedNodes.isSelected(
this.node
));
}
/**
* Returns the highlighted state.
* @return {boolean}
*/
get highlighted() {
if (this.observed.hasOwnProperty("highlighted")) {
return this.observed.highlighted;
}
return (this.observed.highlighted = this.graphComponent.highlightIndicatorManager.selectionModel.isSelected(
this.node
));
}
/**
* Returns the focused state.
* @return {boolean}
*/
get focused() {
if (this.observed.hasOwnProperty("focused")) {
return this.observed.focused;
}
return (this.observed.focused =
this.graphComponent.focusIndicatorManager.focusedItem === this.node);
}
/**
* Generates an id for use in SVG defs elements that is unique for the current rendering context.
*/
generateDefsId() {
return this.defsSupport.generateUniqueDefsId();
}
} |
JavaScript | class VuejsNodeStyle extends NodeStyleBase {
/**
* @param {Component} component
*/
constructor(component) {
super();
this.component = component;
}
/**
* Returns the Vuejs template.
* @return {Component}
*/
get component() {
return this.$component;
}
/**
* Sets the Vuejs template.
* @param {Component} value
*/
set component(value) {
if (value !== this.$component) {
this.$component = value;
this.constructorFunction = Vue.extend({
render(createElement) {
return createElement(value, {
props: {
tag: this.$options.computed.tag.call(this),
layout: this.$options.computed.layout.call(this),
selected: this.$options.computed.selected.call(this),
zoom: this.$options.computed.zoom.call(this),
focused: this.$options.computed.zoom.call(this),
highlighted: this.$options.computed.highlighted.call(this),
fill: this.$options.computed.fill.call(this),
scale: this.$options.computed.scale.call(this),
localId: this.$options.methods.localId.bind(this),
localUrl: this.$options.methods.localUrl.bind(this),
},
});
},
data() {
return {
yFilesContext: null,
idMap: {},
urlMap: {},
};
},
methods: {
localId(id) {
let localId = this.idMap[id];
if (typeof localId === "undefined") {
localId = this.yFilesContext.observedContext.generateDefsId();
this.idMap[id] = localId;
}
return localId;
},
localUrl(id) {
let localUrl = this.urlMap[id];
if (typeof localUrl === "undefined") {
const localId = this.localId(id);
localUrl = `url(#${localId})`;
this.urlMap[id] = localUrl;
}
return localUrl;
},
},
computed: {
layout() {
const yFilesContext = this.yFilesContext;
if (yFilesContext.hasOwnProperty("layout")) {
return yFilesContext.layout;
}
const layout = yFilesContext.observedContext.layout;
return {
width: layout.width,
height: layout.height,
x: layout.x,
y: layout.y,
};
},
tag() {
const yFilesContext = this.yFilesContext;
if (yFilesContext.hasOwnProperty("tag")) {
return yFilesContext.tag || {};
}
return yFilesContext.observedContext.tag || {};
},
selected() {
const yFilesContext = this.yFilesContext;
if (yFilesContext.hasOwnProperty("selected")) {
return yFilesContext.selected;
}
return yFilesContext.observedContext.selected;
},
zoom() {
const yFilesContext = this.yFilesContext;
if (yFilesContext.hasOwnProperty("zoom")) {
return yFilesContext.selected;
}
return yFilesContext.observedContext.zoom;
},
focused() {
const yFilesContext = this.yFilesContext;
if (yFilesContext.hasOwnProperty("focused")) {
return yFilesContext.focused;
}
return yFilesContext.observedContext.focused;
},
highlighted() {
const yFilesContext = this.yFilesContext;
if (yFilesContext.hasOwnProperty("highlighted")) {
return yFilesContext.highlighted;
}
return yFilesContext.observedContext.highlighted;
},
fill() {
return this.tag.fill;
},
scale() {
return this.tag.scale;
},
},
});
}
}
/**
* Creates a visual that uses a Vuejs component to display a node.
* @param {IRenderContext} context
* @param {INode} node
* @return {SvgVisual}
* @see Overrides {@link LabelStyleBase#createVisual}
*/
createVisual(context, node) {
const component = new this.constructorFunction();
this.prepareVueComponent(component, context, node);
// mount the component without passing in a DOM element
component.$mount();
const svgElement = component.$el;
if (!(svgElement instanceof SVGElement)) {
throw "VuejsNodeStyle: Invalid template!";
}
const yFilesContext = component.yFilesContext;
const observedContext = yFilesContext.observedContext;
if (observedContext) {
const changes = observedContext.reset();
if (changes) {
observedContext.changes = changes;
}
}
// set the location
this.updateLocation(node, svgElement);
// save the component instance with the DOM element so we can retrieve it later
svgElement["data-vueComponent"] = component;
// return an SvgVisual that uses the DOM element of the component
const svgVisual = new SvgVisual(svgElement);
context.setDisposeCallback(svgVisual, (context, visual) => {
// clean up vue component instance after the visual is disposed
visual.svgElement["data-vueComponent"].$destroy();
});
return svgVisual;
}
/**
* Updates the visual by returning the old visual, as Vuejs handles updating the component.
* @param {IRenderContext} context
* @param {SvgVisual} oldVisual
* @param {INode} node
* @return {SvgVisual}
* @see Overrides {@link LabelStyleBase#updateVisual}
*/
updateVisual(context, oldVisual, node) {
if (oldVisual instanceof SvgVisual && oldVisual.svgElement) {
const component = oldVisual.svgElement["data-vueComponent"];
if (component) {
const yfilesContext = component.yFilesContext;
const observedContext = yfilesContext.observedContext;
observedContext.update(context);
if (
observedContext &&
observedContext.changes &&
!observedContext.updatePending
) {
const { change } = observedContext.checkModification(
observedContext.changes
);
if (change) {
observedContext.updatePending = true;
this.updateVueComponent(component, yfilesContext, node);
component.$nextTick(() => {
if (observedContext.updatePending) {
observedContext.updatePending = false;
const changes = observedContext.reset();
if (changes) {
observedContext.changes = changes;
} else {
delete observedContext.changes;
}
}
});
}
}
this.updateLocation(node, oldVisual.svgElement);
return oldVisual;
}
}
return this.createVisual(context, node);
}
/**
* Prepares the Vuejs component for rendering.
* @param {Object} component
* @param {IRenderContext} context
* @param {INode} node
*/
prepareVueComponent(component, context, node) {
const yFilesContext = {};
const ctx = new ObservedContext(node, context);
Object.defineProperty(yFilesContext, "observedContext", {
configurable: false,
enumerable: false,
value: ctx,
});
component.yFilesContext = yFilesContext;
}
/**
* Updates the Vuejs component for rendering.
* @param {Object} component
* @param {IRenderContext} context
* @param {INode} node
*/
updateVueComponent(component, context, node) {
const yFilesContext = {};
const ctx = component.yFilesContext.observedContext;
Object.defineProperty(yFilesContext, "observedContext", {
configurable: false,
enumerable: false,
value: ctx,
});
component.yFilesContext = yFilesContext;
component.$forceUpdate();
}
/**
* Updates the location of the given visual.
* @param {INode} node
* @param {SVGElement} svgElement
*/
updateLocation(node, svgElement) {
if (svgElement.transform) {
SvgVisual.setTranslate(svgElement, node.layout.x, node.layout.y);
}
}
} |
JavaScript | class AnimatedObject {
constructor() {
this.objectID = -1;
this.x = 0;
this.y = 0;
this.backgroundColor = '#FFFFFF';
this.foregroundColor = '#000000';
this.highlighted = false;
this.label = '';
this.labelColor = '#000000';
this.layer = 0;
this.alpha = 1.0;
this.minHeightDiff = 3;
this.range = 5;
this.highlightIndex = -1;
this.highlightIndexDirty = true;
this.addedToScene = true;
}
setBackgroundColor(newColor) {
this.backgroundColor = newColor;
}
setNull() {}
getNull() {
return false;
}
setAlpha(newAlpha) {
this.alpha = newAlpha;
}
getAlpha() {
return this.alpha;
}
setForegroundColor(newColor) {
this.foregroundColor = newColor;
this.labelColor = newColor;
}
getHighlight() {
return this.highlighted;
}
getWidth() {
// TODO: Do we want to throw here? Should always override this ...
return 0;
}
getHeight() {
// TODO: Do we want to throw here? Should always override this ...
return 0;
}
setHighlight(value, color) {
this.highlighted = value;
this.highlightColor = color || '#ff0000';
}
centerX() {
return this.x;
}
setWidth() {
throw new Error('setWidth() should be implemented in a base class');
}
centerY() {
return this.y;
}
getAlignLeftPos(otherObject) {
return [otherObject.right() + this.getWidth() / 2, otherObject.centerY()];
}
getAlignRightPos(otherObject) {
return [otherObject.left() - this.getWidth() / 2, otherObject.centerY()];
}
getAlignTopPos(otherObject) {
return [otherObject.centerX(), otherObject.top() - this.getHeight() / 2];
}
getAlignBottomPos(otherObject) {
return [otherObject.centerX(), otherObject.bottom() + this.getHeight() / 2];
}
alignLeft(otherObject) {
// Assuming centering. Overridden method could modify if not centered
// (See AnimatedLabel, for instance)
this.y = otherObject.centerY();
this.x = otherObject.right() + this.getWidth() / 2;
}
alignRight(otherObject) {
// Assuming centering. Overridden method could modify if not centered
// (See AnimatedLabel, for instance)
this.y = otherObject.centerY();
this.x = otherObject.left() - this.getWidth() / 2;
}
alignTop(otherObject) {
// Assuming centering. Overridden method could modify if not centered
this.x = otherObject.centerX();
this.y = otherObject.top() - this.getHeight() / 2;
}
alignBottom(otherObject) {
this.x = otherObject.centerX();
this.y = otherObject.bottom() + this.getHeight() / 2;
}
getClosestCardinalPoint(fromX, fromY) {
let xDelta;
let yDelta;
let xPos;
let yPos;
if (fromX < this.left()) {
xDelta = this.left() - fromX;
xPos = this.left();
} else if (fromX > this.right()) {
xDelta = fromX - this.right();
xPos = this.right();
} else {
xDelta = 0;
xPos = this.centerX();
}
if (fromY < this.top()) {
yDelta = this.top() - fromY;
yPos = this.top();
} else if (fromY > this.bottom()) {
yDelta = fromY - this.bottom();
yPos = this.bottom();
} else {
yDelta = 0;
yPos = this.centerY();
}
if (yDelta > xDelta) {
xPos = this.centerX();
} else {
yPos = this.centerY();
}
return [xPos, yPos];
}
centered() {
return false;
}
pulseHighlight(frameNum) {
if (this.highlighted) {
const frameMod = frameNum / 7.0;
const delta = Math.abs((frameMod % (2 * this.range - 2)) - this.range + 1);
this.highlightDiff = delta + this.minHeightDiff;
}
}
getTailPointerAttachPos() {
return [this.x, this.y];
}
getHeadPointerAttachPos() {
return [this.x, this.y];
}
identifier() {
return this.objectID;
}
getText() {
return this.label;
}
getTextColor() {
return this.labelColor;
}
setTextColor(color) {
this.labelColor = color;
}
setText(newText) {
this.label = newText;
}
setHighlightIndex(hlIndex) {
this.highlightIndex = hlIndex;
this.highlightIndexDirty = true;
}
getHighlightIndex() {
return this.highlightIndex;
}
} |
JavaScript | class PictureUpload extends React.Component {
handleFileChange = event => {
const { target } = event;
const { files } = target;
if (files && files[0]) {
const reader = new FileReader();
reader.onload = event => {
// console.log(event.target.result);
const callback = this.props.fileSelect || function() {};
this.props.fileSelect(event.target.result);
};
reader.readAsDataURL(files[0]);
}
};
render() {
const { classes, src } = this.props;
const preview = src || DEFAULT_AVATAR;
return (
<div>
<label style={{ display: 'block', maxWidth: '100%' }}>
<input
id="art"
type="file"
accept="image/*"
capture="camera"
onChange={this.handleFileChange}
style={{ visibility: 'hidden' }}
/>
<div className={classes.uploaderWrapper}>
<div
className={classes.container}
style={{ backgroundImage: `url(${preview})` }}
>
</div>
</div>
</label>
</div>
);
}
} |
JavaScript | class EventModel extends AbstractModel {
/**
* @param {string} args.url The URL/page associated with the event.
* @param {number} args.time The time at which the event took place.
*/
constructor({ url, time }) {
super()
this.url = url
this.time = typeof time === 'number' ? time : +time
}
} |
JavaScript | class GetSubscriptionResponse extends BaseModel {
/**
* @constructor
* @param {Object} obj The object passed to constructor
*/
constructor(obj) {
super(obj);
if (obj === undefined || obj === null) return;
this.id = this.constructor.getValue(obj.id);
this.code = this.constructor.getValue(obj.code);
this.startAt = this.constructor.getValue(obj.startAt || obj.start_at);
this.interval = this.constructor.getValue(obj.interval);
this.intervalCount = this.constructor.getValue(obj.intervalCount || obj.interval_count);
this.billingType = this.constructor.getValue(obj.billingType || obj.billing_type);
this.currentCycle = this.constructor.getValue(obj.currentCycle || obj.current_cycle);
this.paymentMethod = this.constructor.getValue(obj.paymentMethod || obj.payment_method);
this.currency = this.constructor.getValue(obj.currency);
this.installments = this.constructor.getValue(obj.installments);
this.status = this.constructor.getValue(obj.status);
this.createdAt = this.constructor.getValue(obj.createdAt || obj.created_at);
this.updatedAt = this.constructor.getValue(obj.updatedAt || obj.updated_at);
this.customer = this.constructor.getValue(obj.customer);
this.card = this.constructor.getValue(obj.card);
this.items = this.constructor.getValue(obj.items);
this.statementDescriptor =
this.constructor.getValue(obj.statementDescriptor
|| obj.statement_descriptor);
this.metadata = this.constructor.getValue(obj.metadata);
this.setup = this.constructor.getValue(obj.setup);
this.gatewayAffiliationId =
this.constructor.getValue(obj.gatewayAffiliationId
|| obj.gateway_affiliation_id);
this.nextBillingAt = this.constructor.getValue(obj.nextBillingAt || obj.next_billing_at);
this.billingDay = this.constructor.getValue(obj.billingDay || obj.billing_day);
this.minimumPrice = this.constructor.getValue(obj.minimumPrice || obj.minimum_price);
this.canceledAt = this.constructor.getValue(obj.canceledAt || obj.canceled_at);
this.discounts = this.constructor.getValue(obj.discounts);
this.increments = this.constructor.getValue(obj.increments);
this.boletoDueDays = this.constructor.getValue(obj.boletoDueDays || obj.boleto_due_days);
this.split = this.constructor.getValue(obj.split);
}
/**
* Function containing information about the fields of this model
* @return {array} Array of objects containing information about the fields
*/
static mappingInfo() {
return super.mappingInfo().concat([
{ name: 'id', realName: 'id' },
{ name: 'code', realName: 'code' },
{ name: 'startAt', realName: 'start_at', isDateTime: true, dateTimeValue: 'rfc3339' },
{ name: 'interval', realName: 'interval' },
{ name: 'intervalCount', realName: 'interval_count' },
{ name: 'billingType', realName: 'billing_type' },
{ name: 'currentCycle', realName: 'current_cycle', type: 'GetPeriodResponse' },
{ name: 'paymentMethod', realName: 'payment_method' },
{ name: 'currency', realName: 'currency' },
{ name: 'installments', realName: 'installments' },
{ name: 'status', realName: 'status' },
{
name: 'createdAt',
realName: 'created_at',
isDateTime: true,
dateTimeValue: 'rfc3339',
},
{
name: 'updatedAt',
realName: 'updated_at',
isDateTime: true,
dateTimeValue: 'rfc3339',
},
{ name: 'customer', realName: 'customer', type: 'GetCustomerResponse' },
{ name: 'card', realName: 'card', type: 'GetCardResponse' },
{ name: 'items', realName: 'items', array: true, type: 'GetSubscriptionItemResponse' },
{ name: 'statementDescriptor', realName: 'statement_descriptor' },
{ name: 'metadata', realName: 'metadata' },
{ name: 'setup', realName: 'setup', type: 'GetSetupResponse' },
{ name: 'gatewayAffiliationId', realName: 'gateway_affiliation_id' },
{
name: 'nextBillingAt',
realName: 'next_billing_at',
isDateTime: true,
dateTimeValue: 'rfc3339',
},
{ name: 'billingDay', realName: 'billing_day' },
{ name: 'minimumPrice', realName: 'minimum_price' },
{
name: 'canceledAt',
realName: 'canceled_at',
isDateTime: true,
dateTimeValue: 'rfc3339',
},
{ name: 'discounts', realName: 'discounts', array: true, type: 'GetDiscountResponse' },
{
name: 'increments',
realName: 'increments',
array: true,
type: 'GetIncrementResponse',
},
{ name: 'boletoDueDays', realName: 'boleto_due_days' },
{ name: 'split', realName: 'split', type: 'GetSubscriptionSplitResponse' },
]);
}
/**
* Function containing information about discriminator values
* mapped with their corresponding model class names
*
* @return {object} Object containing Key-Value pairs mapping discriminator
* values with their corresponding model classes
*/
static discriminatorMap() {
return {};
}
} |
JavaScript | class App {
constructor(httpClientConfig) {
this.httpClientConfig = httpClientConfig;
}
configureRouter(config, router) {
config.title = 'Split EASE';
config.map([
{ route: [''], name: 'NewEntry', moduleId: 'NewEntry', nav: true, title: "new entry" },
{ route: ['-', 'Report'], name: 'Report', moduleId: 'Report', nav: true, title: "Report"},
{ route: ['returnPage', 'rp'], moduleId: "NewEntry", name: 'redirectNew',nav: true }
]);
config.options.pushState = true;
this.router = router;
}
activate() {
// configure the / initiate http client configurations.
this.httpClientConfig.configure();
}
} |
JavaScript | class ToolRunner extends events.EventEmitter {
constructor(toolPath, args, options) {
super();
if (!toolPath) {
throw new Error("Parameter 'toolPath' cannot be null or empty.");
}
this.toolPath = toolPath;
this.args = args || [];
this.options = options || {};
}
_debug(message) {
if (this.options.listeners && this.options.listeners.debug) {
this.options.listeners.debug(message);
}
}
_getCommandString(options, noPrefix) {
const toolPath = this._getSpawnFileName();
const args = this._getSpawnArgs(options);
let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool
if (IS_WINDOWS) {
// Windows + cmd file
if (this._isCmdFile()) {
cmd += toolPath;
for (const a of args) {
cmd += ` ${a}`;
}
}
// Windows + verbatim
else if (options.windowsVerbatimArguments) {
cmd += `"${toolPath}"`;
for (const a of args) {
cmd += ` ${a}`;
}
}
// Windows (regular)
else {
cmd += this._windowsQuoteCmdArg(toolPath);
for (const a of args) {
cmd += ` ${this._windowsQuoteCmdArg(a)}`;
}
}
}
else {
// OSX/Linux - this can likely be improved with some form of quoting.
// creating processes on Unix is fundamentally different than Windows.
// on Unix, execvp() takes an arg array.
cmd += toolPath;
for (const a of args) {
cmd += ` ${a}`;
}
}
return cmd;
}
_processLineBuffer(data, strBuffer, onLine) {
try {
let s = strBuffer + data.toString();
let n = s.indexOf(os.EOL);
while (n > -1) {
const line = s.substring(0, n);
onLine(line);
// the rest of the string ...
s = s.substring(n + os.EOL.length);
n = s.indexOf(os.EOL);
}
return s;
}
catch (err) {
// streaming lines to console is best effort. Don't fail a build.
this._debug(`error processing line. Failed with error ${err}`);
return '';
}
}
_getSpawnFileName() {
if (IS_WINDOWS) {
if (this._isCmdFile()) {
return process.env['COMSPEC'] || 'cmd.exe';
}
}
return this.toolPath;
}
_getSpawnArgs(options) {
if (IS_WINDOWS) {
if (this._isCmdFile()) {
let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`;
for (const a of this.args) {
argline += ' ';
argline += options.windowsVerbatimArguments
? a
: this._windowsQuoteCmdArg(a);
}
argline += '"';
return [argline];
}
}
return this.args;
}
_endsWith(str, end) {
return str.endsWith(end);
}
_isCmdFile() {
const upperToolPath = this.toolPath.toUpperCase();
return (this._endsWith(upperToolPath, '.CMD') ||
this._endsWith(upperToolPath, '.BAT'));
}
_windowsQuoteCmdArg(arg) {
// for .exe, apply the normal quoting rules that libuv applies
if (!this._isCmdFile()) {
return this._uvQuoteCmdArg(arg);
}
// otherwise apply quoting rules specific to the cmd.exe command line parser.
// the libuv rules are generic and are not designed specifically for cmd.exe
// command line parser.
//
// for a detailed description of the cmd.exe command line parser, refer to
// http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912
// need quotes for empty arg
if (!arg) {
return '""';
}
// determine whether the arg needs to be quoted
const cmdSpecialChars = [
' ',
'\t',
'&',
'(',
')',
'[',
']',
'{',
'}',
'^',
'=',
';',
'!',
"'",
'+',
',',
'`',
'~',
'|',
'<',
'>',
'"'
];
let needsQuotes = false;
for (const char of arg) {
if (cmdSpecialChars.some(x => x === char)) {
needsQuotes = true;
break;
}
}
// short-circuit if quotes not needed
if (!needsQuotes) {
return arg;
}
// the following quoting rules are very similar to the rules that by libuv applies.
//
// 1) wrap the string in quotes
//
// 2) double-up quotes - i.e. " => ""
//
// this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately
// doesn't work well with a cmd.exe command line.
//
// note, replacing " with "" also works well if the arg is passed to a downstream .NET console app.
// for example, the command line:
// foo.exe "myarg:""my val"""
// is parsed by a .NET console app into an arg array:
// [ "myarg:\"my val\"" ]
// which is the same end result when applying libuv quoting rules. although the actual
// command line from libuv quoting rules would look like:
// foo.exe "myarg:\"my val\""
//
// 3) double-up slashes that precede a quote,
// e.g. hello \world => "hello \world"
// hello\"world => "hello\\""world"
// hello\\"world => "hello\\\\""world"
// hello world\ => "hello world\\"
//
// technically this is not required for a cmd.exe command line, or the batch argument parser.
// the reasons for including this as a .cmd quoting rule are:
//
// a) this is optimized for the scenario where the argument is passed from the .cmd file to an
// external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule.
//
// b) it's what we've been doing previously (by deferring to node default behavior) and we
// haven't heard any complaints about that aspect.
//
// note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be
// escaped when used on the command line directly - even though within a .cmd file % can be escaped
// by using %%.
//
// the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts
// the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing.
//
// one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would
// often work, since it is unlikely that var^ would exist, and the ^ character is removed when the
// variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args
// to an external program.
//
// an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file.
// % can be escaped within a .cmd file.
let reverse = '"';
let quoteHit = true;
for (let i = arg.length; i > 0; i--) {
// walk the string in reverse
reverse += arg[i - 1];
if (quoteHit && arg[i - 1] === '\\') {
reverse += '\\'; // double the slash
}
else if (arg[i - 1] === '"') {
quoteHit = true;
reverse += '"'; // double the quote
}
else {
quoteHit = false;
}
}
reverse += '"';
return reverse
.split('')
.reverse()
.join('');
}
_uvQuoteCmdArg(arg) {
// Tool runner wraps child_process.spawn() and needs to apply the same quoting as
// Node in certain cases where the undocumented spawn option windowsVerbatimArguments
// is used.
//
// Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV,
// see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details),
// pasting copyright notice from Node within this function:
//
// Copyright Joyent, Inc. and other Node contributors. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
if (!arg) {
// Need double quotation for empty argument
return '""';
}
if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) {
// No quotation needed
return arg;
}
if (!arg.includes('"') && !arg.includes('\\')) {
// No embedded double quotes or backslashes, so I can just wrap
// quote marks around the whole thing.
return `"${arg}"`;
}
// Expected input/output:
// input : hello"world
// output: "hello\"world"
// input : hello""world
// output: "hello\"\"world"
// input : hello\world
// output: hello\world
// input : hello\\world
// output: hello\\world
// input : hello\"world
// output: "hello\\\"world"
// input : hello\\"world
// output: "hello\\\\\"world"
// input : hello world\
// output: "hello world\\" - note the comment in libuv actually reads "hello world\"
// but it appears the comment is wrong, it should be "hello world\\"
let reverse = '"';
let quoteHit = true;
for (let i = arg.length; i > 0; i--) {
// walk the string in reverse
reverse += arg[i - 1];
if (quoteHit && arg[i - 1] === '\\') {
reverse += '\\';
}
else if (arg[i - 1] === '"') {
quoteHit = true;
reverse += '\\';
}
else {
quoteHit = false;
}
}
reverse += '"';
return reverse
.split('')
.reverse()
.join('');
}
_cloneExecOptions(options) {
options = options || {};
const result = {
cwd: options.cwd || process.cwd(),
env: options.env || process.env,
silent: options.silent || false,
windowsVerbatimArguments: options.windowsVerbatimArguments || false,
failOnStdErr: options.failOnStdErr || false,
ignoreReturnCode: options.ignoreReturnCode || false,
delay: options.delay || 10000
};
result.outStream = options.outStream || process.stdout;
result.errStream = options.errStream || process.stderr;
return result;
}
_getSpawnOptions(options, toolPath) {
options = options || {};
const result = {};
result.cwd = options.cwd;
result.env = options.env;
result['windowsVerbatimArguments'] =
options.windowsVerbatimArguments || this._isCmdFile();
if (options.windowsVerbatimArguments) {
result.argv0 = `"${toolPath}"`;
}
return result;
}
/**
* Exec a tool.
* Output will be streamed to the live console.
* Returns promise with return code
*
* @param tool path to tool to exec
* @param options optional exec options. See ExecOptions
* @returns number
*/
exec() {
return __awaiter(this, void 0, void 0, function* () {
// root the tool path if it is unrooted and contains relative pathing
if (!ioUtil.isRooted(this.toolPath) &&
(this.toolPath.includes('/') ||
(IS_WINDOWS && this.toolPath.includes('\\')))) {
// prefer options.cwd if it is specified, however options.cwd may also need to be rooted
this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath);
}
// if the tool is only a file name, then resolve it from the PATH
// otherwise verify it exists (add extension on Windows if necessary)
this.toolPath = yield io.which(this.toolPath, true);
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
this._debug(`exec tool: ${this.toolPath}`);
this._debug('arguments:');
for (const arg of this.args) {
this._debug(` ${arg}`);
}
const optionsNonNull = this._cloneExecOptions(this.options);
if (!optionsNonNull.silent && optionsNonNull.outStream) {
optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL);
}
const state = new ExecState(optionsNonNull, this.toolPath);
state.on('debug', (message) => {
this._debug(message);
});
if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) {
return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`));
}
const fileName = this._getSpawnFileName();
const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName));
let stdbuffer = '';
if (cp.stdout) {
cp.stdout.on('data', (data) => {
if (this.options.listeners && this.options.listeners.stdout) {
this.options.listeners.stdout(data);
}
if (!optionsNonNull.silent && optionsNonNull.outStream) {
optionsNonNull.outStream.write(data);
}
stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => {
if (this.options.listeners && this.options.listeners.stdline) {
this.options.listeners.stdline(line);
}
});
});
}
let errbuffer = '';
if (cp.stderr) {
cp.stderr.on('data', (data) => {
state.processStderr = true;
if (this.options.listeners && this.options.listeners.stderr) {
this.options.listeners.stderr(data);
}
if (!optionsNonNull.silent &&
optionsNonNull.errStream &&
optionsNonNull.outStream) {
const s = optionsNonNull.failOnStdErr
? optionsNonNull.errStream
: optionsNonNull.outStream;
s.write(data);
}
errbuffer = this._processLineBuffer(data, errbuffer, (line) => {
if (this.options.listeners && this.options.listeners.errline) {
this.options.listeners.errline(line);
}
});
});
}
cp.on('error', (err) => {
state.processError = err.message;
state.processExited = true;
state.processClosed = true;
state.CheckComplete();
});
cp.on('exit', (code) => {
state.processExitCode = code;
state.processExited = true;
this._debug(`Exit code ${code} received from tool '${this.toolPath}'`);
state.CheckComplete();
});
cp.on('close', (code) => {
state.processExitCode = code;
state.processExited = true;
state.processClosed = true;
this._debug(`STDIO streams have closed for tool '${this.toolPath}'`);
state.CheckComplete();
});
state.on('done', (error, exitCode) => {
if (stdbuffer.length > 0) {
this.emit('stdline', stdbuffer);
}
if (errbuffer.length > 0) {
this.emit('errline', errbuffer);
}
cp.removeAllListeners();
if (error) {
reject(error);
}
else {
resolve(exitCode);
}
});
if (this.options.input) {
if (!cp.stdin) {
throw new Error('child process missing stdin');
}
cp.stdin.end(this.options.input);
}
}));
});
}
} |
JavaScript | class RequestError extends Error {
constructor(message, statusCode, options) {
super(message); // Maintains proper stack trace (only available on V8)
/* istanbul ignore next */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
this.name = "HttpError";
this.status = statusCode;
let headers;
if ("headers" in options && typeof options.headers !== "undefined") {
headers = options.headers;
}
if ("response" in options) {
this.response = options.response;
headers = options.response.headers;
} // redact request credentials without mutating original request options
const requestCopy = Object.assign({}, options.request);
if (options.request.headers.authorization) {
requestCopy.headers = Object.assign({}, options.request.headers, {
authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]")
});
}
requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit
// see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications
.replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended
// see https://developer.github.com/v3/#oauth2-token-sent-in-a-header
.replace(/\baccess_token=\w+/g, "access_token=[REDACTED]");
this.request = requestCopy; // deprecations
Object.defineProperty(this, "code", {
get() {
logOnceCode(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`."));
return statusCode;
}
});
Object.defineProperty(this, "headers", {
get() {
logOnceHeaders(new deprecation.Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`."));
return headers || {};
}
});
}
} |
JavaScript | class Response {
constructor() {
let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
Body.call(this, body, opts);
const status = opts.status || 200;
const headers = new Headers(opts.headers);
if (body != null && !headers.has('Content-Type')) {
const contentType = extractContentType(body);
if (contentType) {
headers.append('Content-Type', contentType);
}
}
this[INTERNALS$1] = {
url: opts.url,
status,
statusText: opts.statusText || STATUS_CODES[status],
headers,
counter: opts.counter
};
}
get url() {
return this[INTERNALS$1].url || '';
}
get status() {
return this[INTERNALS$1].status;
}
/**
* Convenience property representing if the request ended normally
*/
get ok() {
return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
}
get redirected() {
return this[INTERNALS$1].counter > 0;
}
get statusText() {
return this[INTERNALS$1].statusText;
}
get headers() {
return this[INTERNALS$1].headers;
}
/**
* Clone this response
*
* @return Response
*/
clone() {
return new Response(clone(this), {
url: this.url,
status: this.status,
statusText: this.statusText,
headers: this.headers,
ok: this.ok,
redirected: this.redirected
});
}
} |
JavaScript | class Request {
constructor(input) {
let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
let parsedURL;
// normalize input
if (!isRequest(input)) {
if (input && input.href) {
// in order to support Node.js' Url objects; though WHATWG's URL objects
// will fall into this branch also (since their `toString()` will return
// `href` property anyway)
parsedURL = parse_url(input.href);
} else {
// coerce input to a string before attempting to parse
parsedURL = parse_url(`${input}`);
}
input = {};
} else {
parsedURL = parse_url(input.url);
}
let method = init.method || input.method || 'GET';
method = method.toUpperCase();
if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
throw new TypeError('Request with GET/HEAD method cannot have body');
}
let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
Body.call(this, inputBody, {
timeout: init.timeout || input.timeout || 0,
size: init.size || input.size || 0
});
const headers = new Headers(init.headers || input.headers || {});
if (inputBody != null && !headers.has('Content-Type')) {
const contentType = extractContentType(inputBody);
if (contentType) {
headers.append('Content-Type', contentType);
}
}
let signal = isRequest(input) ? input.signal : null;
if ('signal' in init) signal = init.signal;
if (signal != null && !isAbortSignal(signal)) {
throw new TypeError('Expected signal to be an instanceof AbortSignal');
}
this[INTERNALS$2] = {
method,
redirect: init.redirect || input.redirect || 'follow',
headers,
parsedURL,
signal
};
// node-fetch-only options
this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
this.counter = init.counter || input.counter || 0;
this.agent = init.agent || input.agent;
}
get method() {
return this[INTERNALS$2].method;
}
get url() {
return format_url(this[INTERNALS$2].parsedURL);
}
get headers() {
return this[INTERNALS$2].headers;
}
get redirect() {
return this[INTERNALS$2].redirect;
}
get signal() {
return this[INTERNALS$2].signal;
}
/**
* Clone this request
*
* @return Request
*/
clone() {
return new Request(this);
}
} |
JavaScript | class GridHelper extends Helper {
/**
* Construct Grid Helper class
*
* @param {object} options
*/
constructor (options) {
// Run super
super();
// Bind public methods
this.data = this.data.bind(this);
this.type = this.type.bind(this);
this.rows = this.rows.bind(this);
this.live = this.live.bind(this);
this.page = this.page.bind(this);
this.post = this.post.bind(this);
this.sort = this.sort.bind(this);
this.model = this.model.bind(this);
this.query = this.query.bind(this);
this.route = this.route.bind(this);
this.filter = this.filter.bind(this);
this.render = this.render.bind(this);
this.querySort = this.querySort.bind(this);
// Bind private methods
this._bind = this._bind.bind(this);
// Set default options
options = options || {};
// Set private variables
this._way = options.way || false;
this._rows = options.rows || 20;
this._type = options.type || 'columns';
this._live = options.live || false;
this._page = options.page || 1;
this._sort = options.sort || false;
this._model = options.model || false;
this._where = options.where || this._model;
this._route = options.route || '';
this._filter = options.filter || {};
this._filters = options.filters || {};
this._columns = options.columns || {};
// Run bind
this._bind();
}
/**
* Set rows
*
* @param {*} rows
*
* @return {GridHelper}
*/
rows (rows) {
// Set rows
this._rows = rows;
// Allow chainable
return this;
}
/**
* Set type
*
* @param {*} type
*
* @return {GridHelper}
*/
type (type) {
// Set type
this._type = type;
// Allow chainable
return this;
}
/**
* Set live
*
* @param {boolean} live
*
* @return {GridHelper}
*/
live (live) {
// Set live
this._live = live;
// Allow chainable
return this;
}
/**
* Set page
*
* @param {*} page
*
* @return {GridHelper}
*/
page (page) {
// Set page
this._page = page;
// Allow chainable
return this;
}
/**
* Set sort
*
* @param {string} sort
* @param {number} way
*
* @return {GridHelper}
*/
sort (sort, way) {
// Set way and sort
this._way = way;
this._sort = sort;
// Allow chainable
return this;
}
/**
* Set model
*
* @param {*} model
*
* @return {GridHelper}
*/
model (model) {
// Set model
this._model = model;
// Run model bind
this._bind();
// Allow chainable
return this;
}
/**
* Set route
*
* @param {string} route
*
* @return {GridHelper}
*/
route (route) {
// Set route
this._route = route;
// Allow chainable
return this;
}
/**
* Returns filtered query
*
* @return {Promise}
*
* @async
*/
async query () {
// Check filters
for (const filter in this._filter) {
// Check this filter has filter
if (this._filter.hasOwnProperty(filter)) {
// Check filter exists
if (!this._filters[filter]) {
continue;
}
// Check if filter has query
if (this._filters[filter].query) {
// Run query
await this._filters[filter].query(this._filter[filter]);
} else {
// Run and
this.where(filter, this._filter[filter]);
}
}
}
// Return this
return this;
}
/**
* Returns sorted query
*
* @return {Promise}
*
* @async
*/
async querySort () {
// Check sort
if (this._sort && this._columns[this._sort] && this._columns[this._sort].sort && this._way !== false) {
// Check type
if (typeof this._columns[this._sort].sort === 'function') {
// Set sort
this._where = await this._columns[this._sort].sort(this._where, this._way);
} else if (this._columns[this._sort].sort === true) {
// Set sort directly
this._where = this._where.sort(this._sort, this._way);
}
} else if (this._sort && this._way !== false) {
// Set sort directly
this._where = this._where.sort(this._sort, this._way);
}
// Allow chainable
return this;
}
/**
* Add filter
*
* @param {string} key
* @param {*} filter
*
* @return {GridHelper}
*/
filter (key, filter) {
// Set filter
this._filters[key] = filter;
// Allow chainable
return this;
}
/**
* Add column
*
* @param {string} key
* @param {*} column
*
* @return {GridHelper}
*/
column (key, column) {
// Set column
this._columns[key] = column;
// Allow chainable
return this;
}
/**
* Runs post request
*
* @param {Request} req
* @param {Response} res
*/
async post (req, res) {
// Check rows
if (req.body.rows) this._rows = parseInt(req.body.rows);
// Check page
if (req.body.page) this._page = parseInt(req.body.page);
// Check sort
if (req.body.sort) this._sort = req.body.sort;
// Set way
this._way = req.body.way;
// Check filter
if (req.body.filter) {
// Loop filter
for (const key in req.body.filter) {
// Check filter has key
if (req.body.filter.hasOwnProperty(key)) {
// Check value
if (!req.body.filter[key].length && !Object.keys(req.body.filter[key]).length) continue;
// Set filter
this._filter[key] = req.body.filter[key];
}
}
}
// Send result
res.json(await this.render());
}
/**
* Exports columns
*
* @param {array} rows
* @param {string} type
*
* @return {Promise}
*/
data (rows, type) {
// Check type
if (this._type !== 'columns') {
// Return sanitised
return Promise.all(rows.map((row) => {
return row.sanitise();
}));
} else {
// Return map
return Promise.all(rows.map(async (row) => {
// Set sanitised
const sanitised = {};
// Loop columns
await Promise.all(Object.keys(this._columns).map(async (column) => {
// Check if column export
if (typeof this._columns[column].type !== 'undefined' && type !== this._columns[column].type) return;
// Load column
let load = await row.get(column);
// Check format
if (this._columns[column].format) load = await this._columns[column].format(load, row, type);
// Set to sanitised
sanitised[column] = (load || '').toString();
}));
// Return sanitised
return sanitised;
}));
}
}
/**
* Runs post request
*
* @param {Request} req
* @param {string} type
*
* @return {Promise}
*
* @async
*/
async export (req, type) {
// Check order
if (req.body.sort) this._sort = req.body.sort;
// Set way
this._way = req.body.way;
// Check where
if (req.body.filter) {
// Loop filter
for (const key in req.body.filter) {
// Check filter has key
if (req.body.filter.hasOwnProperty(key)) {
// Set filter
this._filter[key] = req.body.filter[key];
}
}
}
// Run query
await this.query();
// Return result
return await this.data(await this._where.find(), type);
}
/**
* Renders grid view
*
* @param {Request} req
*
* @return {*}
*
* @async
*/
async render (req) {
// Check rows
if (req && req.query.rows) this._rows = parseInt(req.query.rows);
// Check page
if (req && req.query.page) this._page = parseInt(req.query.page);
// Check order
if (req && req.query.sort) this._sort = req.query.sort;
// Set way
if (req && req.query.way) this._way = (req.query.way === 'false' ? false : parseInt(req.query.way));
// Check filter
if (req && req.query.filter) {
// Loop filter
for (const key in req.query.filter) {
// Check filter has key
if (req.query.filter.hasOwnProperty(key)) {
// Check value
if (!req.query.filter[key].length || !Object.keys(req.query.filter[key]).length) continue;
// Set value
this._filter[key] = req.query.filter[key];
}
}
}
// Set response
const response = {
'data' : [],
'filter' : this._filter,
'filters' : [],
'columns' : []
};
// Set standard vars
response.way = this._way;
response.page = this._page;
response.rows = this._rows;
response.sort = this._sort;
response.live = this._live;
response.type = this._type;
response.route = this._route;
// Do query
await this.query();
// Set total
response.total = await this._where.count();
// Do query
await this.querySort();
// Complete query
let rows = await this._where.skip(this._rows * (this._page - 1)).limit(this._rows).find();
// Get data
response.data = await this.data(rows, false);
// Check type columns
if (this._type === 'columns') {
// Loop columns
for (const col in this._columns) {
// Check columns has col
if (this._columns.hasOwnProperty(col)) {
// Check type
if (this._columns[col].type) continue;
// Push into columns
response.columns.push({
'id' : col,
'sort' : !!this._columns[col].sort,
'width' : this._columns[col].width || false,
'title' : this._columns[col].title
});
}
}
}
// Loop filters
for (const filter in this._filters) {
// Check filters has filter
if (this._filters.hasOwnProperty(filter)) {
// Push into filters
response.filters.push({
'id' : filter,
'type' : this._filters[filter].type,
'ajax' : this._filters[filter].ajax,
'title' : this._filters[filter].title,
'socket' : this._filters[filter].socket,
'options' : this._filters[filter].options
});
}
}
// Return response
return response;
}
/**
* Binds model
*/
_bind () {
// Check model
if (!this._model) return;
// Check where
if (!this._where) this._where = this._model;
// Bind query methods
['where', 'match', 'eq', 'ne', 'or', 'and', 'elem', 'in', 'nin', 'gt', 'lt', 'gte', 'lte'].forEach((method) => {
// Create new function
this[method] = (...args) => {
// Set where
return this._where = this._where[method](...args);
};
});
}
} |
JavaScript | class SessionManager extends WildEmitter$1 {
constructor(conf) {
super();
conf = conf || {};
this.selfID = conf.selfID;
this.sessions = {};
this.peers = {};
this.prepareSession =
conf.prepareSession ||
function(opts) {
if (opts.applicationTypes.indexOf('rtp') >= 0) {
return new MediaSession(opts);
}
if (opts.applicationTypes.indexOf('filetransfer') >= 0) {
return new FileTransferSession(opts);
}
};
this.performTieBreak =
conf.performTieBreak ||
function(sess, req) {
const applicationTypes = req.jingle.contents.map(content => {
if (content.application) {
return content.application.applicationType;
}
});
const intersection = sess.pendingApplicationTypes.filter(appType =>
applicationTypes.includes(appType)
);
return intersection.length > 0;
};
this.config = Object.assign(
{
debug: false,
peerConnectionConfig: {
bundlePolicy: conf.bundlePolicy || 'balanced',
iceServers: conf.iceServers || [{ urls: 'stun:stun.l.google.com:19302' }],
iceTransportPolicy: conf.iceTransportPolicy || 'all',
rtcpMuxPolicy: conf.rtcpMuxPolicy || 'require'
},
peerConnectionConstraints: {
optional: [{ DtlsSrtpKeyAgreement: true }, { RtpDataChannels: false }]
}
},
conf
);
this.iceServers = this.config.peerConnectionConfig.iceServers;
}
addICEServer(server) {
// server == {
// url: '',
// [username: '',]
// [credential: '']
// }
if (typeof server === 'string') {
server = { urls: server };
}
this.iceServers.push(server);
}
addSession(session) {
const sid = session.sid;
const peer = session.peerID;
this.sessions[sid] = session;
if (!this.peers[peer]) {
this.peers[peer] = [];
}
this.peers[peer].push(session);
// Automatically clean up tracked sessions
session.on('terminated', () => {
const peers = this.peers[peer] || [];
if (peers.length) {
peers.splice(peers.indexOf(session), 1);
}
delete this.sessions[sid];
});
// Proxy session events
session.on('*', (name, data, ...extraData) => {
// Listen for when we actually try to start a session to
// trigger the outgoing event.
if (name === 'send') {
const action = data.jingle && data.jingle.action;
if (session.isInitiator && action === 'session-initiate') {
this.emit('outgoing', session);
}
}
if (this.config.debug && (name === 'log:debug' || name === 'log:error')) {
console.log('Jingle:', data, ...extraData);
}
// Don't proxy change:* events, since those don't apply to
// the session manager itself.
if (name.indexOf('change') === 0) {
return;
}
this.emit(name, data, ...extraData);
});
this.emit('createdSession', session);
return session;
}
createMediaSession(peer, sid, stream) {
const session = new MediaSession({
config: this.config.peerConnectionConfig,
constraints: this.config.peerConnectionConstraints,
iceServers: this.iceServers,
initiator: true,
maxRelayBandwidth: MAX_RELAY_BANDWIDTH,
parent: this,
peerID: peer,
sid,
stream
});
this.addSession(session);
return session;
}
createFileTransferSession(peer, sid) {
const session = new FileTransferSession({
config: this.config.peerConnectionConfig,
constraints: this.config.peerConnectionConstraints,
iceServers: this.iceServers,
initiator: true,
maxRelayBandwidth: MAX_RELAY_BANDWIDTH,
parent: this,
peerID: peer,
sid
});
this.addSession(session);
return session;
}
endPeerSessions(peer, reason, silent) {
peer = peer.full || peer;
const sessions = this.peers[peer] || [];
delete this.peers[peer];
sessions.forEach(function(session) {
session.end(reason || 'gone', silent);
});
}
endAllSessions(reason, silent) {
Object.keys(this.peers).forEach(peer => {
this.endPeerSessions(peer, reason, silent);
});
}
_createIncomingSession(meta, req) {
let session;
if (this.prepareSession) {
session = this.prepareSession(meta, req);
}
// Fallback to a generic session type, which can
// only be used to end the session.
if (!session) {
session = new JingleSession(meta);
}
this.addSession(session);
return session;
}
_sendError(to, id, data) {
if (!data.type) {
data.type = 'cancel';
}
this.emit('send', {
error: data,
id,
to,
type: 'error'
});
}
_log(level, message, ...args) {
this.emit('log:' + level, message, ...args);
}
process(req) {
const self = this;
// Extract the request metadata that we need to verify
const sid = !!req.jingle ? req.jingle.sid : null;
let session = this.sessions[sid] || null;
const rid = req.id;
const sender = req.from ? req.from.full || req.from : undefined;
if (req.type === 'error') {
const isTieBreak = req.error && req.error.jingleCondition === 'tie-break';
if (session && session.state === 'pending' && isTieBreak) {
return session.end('alternative-session', true);
} else {
if (session) {
session.pendingAction = false;
}
return this.emit('error', req);
}
}
if (req.type === 'result') {
if (session) {
session.pendingAction = false;
}
return;
}
const action = req.jingle.action;
const contents = req.jingle.contents || [];
const applicationTypes = contents.map(function(content) {
if (content.application) {
return content.application.applicationType;
}
});
const transportTypes = contents.map(function(content) {
if (content.transport) {
return content.transport.transportType;
}
});
// Now verify that we are allowed to actually process the
// requested action
if (action !== 'session-initiate') {
// Can't modify a session that we don't have.
if (!session) {
this._log('error', 'Unknown session', sid);
return this._sendError(sender, rid, {
condition: 'item-not-found',
jingleCondition: 'unknown-session'
});
}
// Check if someone is trying to hijack a session.
if (session.peerID !== sender || session.state === 'ended') {
this._log('error', 'Session has ended, or action has wrong sender');
return this._sendError(sender, rid, {
condition: 'item-not-found',
jingleCondition: 'unknown-session'
});
}
// Can't accept a session twice
if (action === 'session-accept' && session.state !== 'pending') {
this._log('error', 'Tried to accept session twice', sid);
return this._sendError(sender, rid, {
condition: 'unexpected-request',
jingleCondition: 'out-of-order'
});
}
// Can't process two requests at once, need to tie break
if (action !== 'session-terminate' && action === session.pendingAction) {
this._log('error', 'Tie break during pending request');
if (session.isInitiator) {
return this._sendError(sender, rid, {
condition: 'conflict',
jingleCondition: 'tie-break'
});
}
}
} else if (session) {
// Don't accept a new session if we already have one.
if (session.peerID !== sender) {
this._log('error', 'Duplicate sid from new sender');
return this._sendError(sender, rid, {
condition: 'service-unavailable'
});
}
// Check if we need to have a tie breaker because both parties
// happened to pick the same random sid.
if (session.state === 'pending') {
if (this.selfID > session.peerID && this.performTieBreak(session, req)) {
this._log('error', 'Tie break new session because of duplicate sids');
return this._sendError(sender, rid, {
condition: 'conflict',
jingleCondition: 'tie-break'
});
}
} else {
// The other side is just doing it wrong.
this._log('error', 'Someone is doing this wrong');
return this._sendError(sender, rid, {
condition: 'unexpected-request',
jingleCondition: 'out-of-order'
});
}
} else if (this.peers[sender] && this.peers[sender].length) {
// Check if we need to have a tie breaker because we already have
// a different session with this peer that is using the requested
// content application types.
for (let i = 0, len = this.peers[sender].length; i < len; i++) {
const sess = this.peers[sender][i];
if (
sess &&
sess.state === 'pending' &&
sess.sid > sid &&
this.performTieBreak(sess, req)
) {
this._log('info', 'Tie break session-initiate');
return this._sendError(sender, rid, {
condition: 'conflict',
jingleCondition: 'tie-break'
});
}
}
}
// We've now weeded out invalid requests, so we can process the action now.
if (action === 'session-initiate') {
if (!contents.length) {
return self._sendError(sender, rid, {
condition: 'bad-request'
});
}
session = this._createIncomingSession(
{
applicationTypes,
config: this.config.peerConnectionConfig,
constraints: this.config.peerConnectionConstraints,
iceServers: this.iceServers,
initiator: false,
parent: this,
peerID: sender,
sid,
transportTypes
},
req
);
}
session.process(action, req.jingle, err => {
if (err) {
this._log('error', 'Could not process request', req, err);
this._sendError(sender, rid, err);
} else {
this.emit('send', {
id: rid,
to: sender,
type: 'result'
});
// Wait for the initial action to be processed before emitting
// the session for the user to accept/reject.
if (action === 'session-initiate') {
this.emit('incoming', session);
}
}
});
}
} |
JavaScript | class PopupSidebar {
constructor(pt) {
// to trigger event (e.g. on modal)
this.pt = pt;
// Topic array to keep track of existing Topics
this.topics = [];
// BrowsingWindow array to keep track of open Browser Windows
this.windows = [];
// DOM Nodes
this.nodes = {
divSidebar: document.getElementById('divSidebar'),
navSidebar: document.getElementById('navSidebar'),
divOverlay: document.getElementById('divOverlay'),
ulSidebarTopics: document.getElementById('ulSidebarTopics'),
ulSidebarWindows: document.getElementById('ulSidebarWindows'),
butSideBarMenu: document.getElementById('butSidebarMenu'),
butAddTopic: document.getElementById('butAddTopic'),
butAddWindow: document.getElementById('butAddWindow'),
};
// This could be better
this.draw = this.draw.bind(this);
this.drawTopics = this.drawTopics.bind(this);
this.drawWindows = this.drawWindows.bind(this);
this.addTopic = this.addTopic.bind(this);
this.addWindow = this.addWindow.bind(this);
this.toggleDisplay = this.toggleDisplay.bind(this);
this.registerEvents = this.registerEvents.bind(this);
this.saveTopicOrderToDb = this.saveTopicOrderToDb.bind(this);
this.getTopicForWindowId = this.getTopicForWindowId.bind(this);
this.draw()
.then()
.catch(err => console.error("PopupSidebar.constructor(): draw() failed with err=%s", err));
}
// Toggle between showing and hiding the sidebar, and add overlay effect
toggleDisplay() {
// hide the sidebar if its shown, else show it
if (this.nodes.divSidebar.style.display === 'block') {
this.nodes.divSidebar.style.display = 'none';
this.nodes.divOverlay.style.display = "none";
} else {
this.nodes.divSidebar.style.display = 'block';
this.nodes.divOverlay.style.display = "block";
}
}
// draw - completely refreshes the sidebar
async draw() {
await this.drawTopics();
this.drawWindows();
// menu button (only for small screens)
this.nodes.butSideBarMenu.onclick = this.toggleDisplay;
}
async drawTopics() {
this.nodes.ulSidebarTopics.innerHTML = '';
if (typeof this.sortableTopics !== 'undefined') {
this.sortableTopics.destroy();
}
// get topics from Database
let topics = await dbGetTopicsAsArray();
topics.forEach(this.addTopic);
// apply Sortable.js to sidebar topics
let options = {
handle: '.drag-handle',
onUpdate: (evt) => {
if (evt.from === evt.to) {
console.debug("Moved Topic %s (id=%s) from %d to %d", evt.item.innerText, evt.item.id, evt.oldIndex, evt.newIndex);
this.saveTopicOrderToDb().then(() => {
// Send global MoveTopic event, so all other Sidebar instances can get it
browser.runtime.sendMessage({
action: 'TopicMove',
detail: {id: evt.item.id, from: evt.oldIndex, to: evt.newIndex}
});
});
} else {
console.warn("Moved Topic to unsupported destination (from=%O, to=%O).", evt.from, evt.to);
}
}
};
this.sortableTopics = Sortable.create(this.nodes.ulSidebarTopics, options);
}
drawWindows() {
this.nodes.ulSidebarWindows.innerHTML = '';
// get all Windows
browser.windows.getAll({populate: false})
.then((windows) => {
for (let win of windows) {
// only draw if this is not a topic window
if (typeof this.getTopicForWindowId(win.id) === 'undefined') {
this.addWindow(win);
}
}
});
}
// add one (existing or new) topic to the topic list
addTopic(item) {
if ('deleted' in item) {
console.debug("Sidebar.addTopic() skipped for deleted topic: %O", item);
return undefined;
}
console.debug("Sidebar.addTopic(): Adding topic=%O", item);
/*
// check if Topic was a BrowsingWindow - then remove it
if (item.windowId) {
this.removeWindow(item.windowId);
}
*/
let newTopic = new Topic({
pt: this.pt,
id: item.id,
name: item.name,
color: item.color,
windowId: item.windowId,
tabs: item.tabs,
favorites: item.favorites
});
if (typeof newTopic.id === 'undefined') {
console.error("Sidebar.addTopic() new topic id is undefined!");
return false;
}
newTopic.add(this.nodes.ulSidebarTopics);
this.topics.push(newTopic);
return newTopic;
}
// removes a topic from Topic list
removeTopic(item) {
console.debug("Sidebar.removeTopic() id=%d", item.id);
this.topics.find(topic => topic.id === item.id).remove(this.nodes.ulSidebarTopics);
this.topics = this.topics.filter(topic => topic.id !== item.id);
}
moveTopic(detail) {
// currently redraw whole topics content
this.drawTopics().then();
}
// store the (updated) order of the Topics to the DB by checking <li> order
async saveTopicOrderToDb() {
for (let i = 0; i < this.nodes.ulSidebarTopics.childNodes.length; i++) {
let topicId = this.nodes.ulSidebarTopics.childNodes[i].id;
let updated = await debe.topics.update(Topic.idToInt(topicId), {order: i});
if (updated)
console.debug("saveTopicOrderToDb(): Topic %d order=%d", Topic.idToInt(topicId), i);
else
console.debug("Nothing was updated for Topic %d", Topic.idToInt(topicId));
}
}
// add one window to the sidebar window list
addWindow(win) {
console.debug("Sidebar.addWindow(): Adding window with id %d", win.id);
let newWindow = new BrowsingWindow(this.pt, win);
if (typeof newWindow.id === 'undefined') {
console.error("Sidebar.addWindow() window id is undefined!");
return false;
}
newWindow.add(this.nodes.ulSidebarWindows);
this.windows.push(newWindow);
}
// remove window with specified window id
removeWindow(windowId) {
console.debug("Sidebar.removeWindow(): Removing window with id %d", windowId);
let win = this.windows.find(win => win.id === windowId);
if (win) {
win.remove(this.nodes.ulSidebarWindows);
}
this.windows = this.windows.filter((window) => window.id !== windowId);
}
/*
* Update certain information when a Tab Opened/Closed/Updated:
* - For Topic update the Topic Info
* - For Windows update the Title
*/
updateWindowInfo(windowId) {
console.debug("Sidebar.updateWindowInfo(): Update info for window with id %d", windowId);
let win = this.windows.find(win => win.id === windowId);
if (win) {
win.updateWindowTitle();
} else {
console.info('PopupSidebar.updateWindowInfo(): Window with id=%d does not exist', windowId);
}
}
// called when TopicTabUpdated event received
updateTopicInfo(detail) {
let topic = this.topics.find(topic => detail.topicId === topic.id);
if (topic) {
console.debug("Sidebar.updateTopicInfo(id=%d), detail=%O", detail.topicId, detail);
if ('tabs' in detail) {
topic.tabs = detail.tabs;
}
if ('name' in detail) {
topic.name = detail.name;
}
if ('color' in detail) {
topic.color = detail.color;
}
// update sidebar info
topic.updateInfo();
}
}
// determine if the specific window belongs to a Topic
getTopicForWindowId(windowId) {
return this.topics.find(topic => {
return topic.windowId === windowId
});
}
registerEvents() {
// listen to local 'TopicAdd' (received from ModalAddTopic)
this.nodes.navSidebar.addEventListener('TopicAdd', (params) => {
console.debug("Sidebar.AddTopic event: params=%O", params);
this.addTopic(params.detail);
});
// listen to local 'TopicRemove')
this.nodes.navSidebar.addEventListener('TopicRemove', (params) => {
console.debug("Sidebar.RemoveTopic event: params=%O", params);
this.removeTopic(params.detail);
});
// listen to global 'AddTopic' (received from other chrome window)
browser.runtime.onMessage.addListener((request, sender) => {
// endpoints called by popup.js
let topic;
switch (request.action) {
case 'TopicAdd':
console.debug("Custom AddTopic event received: detail=%O", request.detail);
this.addTopic(request.detail);
break;
case 'TopicRemove':
console.debug("Custom TopicRemove event received: detail=%O", request.detail);
this.removeTopic(request.detail);
break;
case 'TopicMove':
console.debug("Custom TopicMove event received: detail=%O", request.detail);
this.moveTopic(request.detail);
break;
case 'TopicInfoUpdated':
console.debug("PopupSidebar - Custom TopicInfoUpdated event received: detail=%O", request.detail);
this.updateTopicInfo(request.detail);
break;
case 'TopicLoaded':
console.debug("Custom TopicLoaded event received: detail=%O", request.detail);
// a WindowCreated event can happen before TopicLoaded is received, therefore first cleanup the window
let win = this.windows.find(win => request.detail.windowId === win.id);
if (win) {
console.debug("Browser event TopicLoaded event; removing (wrong) Sidebar Window");
this.removeWindow(request.detail.windowId);
}
topic = this.topics.find(topic => request.detail.id === topic.id);
if (topic) {
topic.windowId = request.detail.windowId;
topic.setOpen();
}
break;
case 'WindowCreated':
console.debug("Custom WindowCreated event received: detail=%O, topics=%O", request.detail, this.topics);
if (this.windows.find(win => win.id === request.detail.window.id)) {
// when a session is restored, the windows are open but WindowCreated is sent again
console.debug("Ignored WindowCreated event for existing window id (%d)", request.detail.window.id);
}
// if a Topic is loaded, WindowCreated will also be sent
// Note: if WindowCreated happens before TopicLoaded, then windowId is unknown and this will not work here
else if (topic = this.getTopicForWindowId(request.detail.window.id)) {
topic.setOpen();
}
else {
this.addWindow(request.detail.window);
}
break;
case 'WindowRemoved':
console.debug("Custom WindowRemoved event received: detail=%O", request.detail);
if ('converted' in request.detail) {
// a Topic can be converted to a Window, in that case WindowRemoved should not touch the Topic
this.removeWindow(request.detail.windowId);
} else if (topic = this.getTopicForWindowId(request.detail.windowId)) {
// A WindowRemoved for a Topic, set Topic to closed
topic.setClosed();
this.removeWindow(request.detail.windowId);
} else {
this.removeWindow(request.detail.windowId);
}
break;
case 'UpdateWindowInfo':
console.debug("Custom UpdateWindowInfo event received: detail=%O", request.detail);
this.updateWindowInfo(request.detail.windowId);
break;
}
});
// when add topic button clicked, dispatch to modal
this.nodes.butAddTopic.addEventListener('click', () => {
let event = new Event('TopicAdd');
this.pt.refModalAddTopic.nodes.div.dispatchEvent(event);
});
// when add window button clicked
this.nodes.butAddWindow.addEventListener('click', () => {
// Send global CreateWindow event
browser.runtime.sendMessage({
action: 'CreateWindow'
}).then(retVal => console.debug("CreateWindow complete: %s", JSON.stringify(retVal)))
.catch(err => console.warn("CreateWindow failed: %O", err));
});
}
} |
JavaScript | class PopupMain {
constructor(pt) {
this.pt = pt;
// DOM Nodes
this.nodes = {
div: document.getElementById('divMainFlex'),
divOptions: document.getElementById('divOptions'),
header: document.getElementById('hMainHeader'),
ulActiveTabs: document.getElementById('ulMainActiveTabs'),
ulSavedTabs: document.getElementById('ulMainSavedTabs'),
butAddTab: document.getElementById('butAddTab'),
inputSearchBar: document.getElementById('inputSearchBar')
};
// store instances of Tab, with index = tab.id
this.tabs = [];
this.favorites = [];
this.drawTabs = this.drawTabs.bind(this);
this.addTab = this.addTab.bind(this);
this.updateTitle = this.updateTitle.bind(this);
this.drawTopicOptions();
this.drawTabs();
this.drawSavedTabs();
this.setupFilter();
// restore previously open tabs (Topic)
this.restoreTabs()
.then()
.catch(err => console.error("PopupMain.constructor(): restoreTabs failed with %s", err));
}
// draw active tabs in current Window or Topic
drawTabs() {
while (this.nodes.ulActiveTabs.firstChild) {
this.nodes.ulActiveTabs.removeChild(this.nodes.ulActiveTabs.firstChild);
}
this.nodes.ulActiveTabs.style.width = '800px';
// add active tabs
for (let tab of this.pt.whoIAm.currentWindow.tabs) {
this.addTab(tab);
}
// apply Sortable.js to active tab list
let options = {
handle: '.drag-handle',
draggable: '.can-be-dragged',
onAdd: function (evt) {
console.debug('onAdd.Tab:', [evt.item, evt.from]);
},
onRemove: function (evt) {
console.debug('onRemove.Tab:', [evt.item, evt.from]);
},
onStart: function (evt) {
console.debug('onStart.Tab:', [evt.item, evt.from]);
},
onSort: function (evt) {
console.debug('onSort.Tab:', [evt.item, evt.from]);
},
onEnd: function (evt) {
console.debug('onEnd.Tab:', [evt.item, evt.from])
},
onUpdate: (evt) => {
// same window (from = to)?
if (evt.from === evt.to) {
console.debug("Moved Tab %s (id=%s) from %d to %d", evt.item.innerText, evt.item.id, evt.oldIndex, evt.newIndex);
this.moveTabInWindow(evt);
return true;
} else {
console.warn("Moved Tab to unsupported destination (from=%O, to=%O).", evt.from, evt.to);
return false;
}
}
};
this.sortableTabs = Sortable.create(this.nodes.ulActiveTabs, options);
}
// draw tabs saved by user (Topic only)
drawSavedTabs() {
if (!this.pt.whoIAm || !this.pt.whoIAm.currentTopic) {
document.getElementById('divMainSavedTabs').classList.add('w3-hide');
return;
} else {
if (this.pt.whoIAm.currentTopic.favorites && this.pt.whoIAm.currentTopic.favorites.length > 0) {
while (this.nodes.ulSavedTabs.firstChild) {
this.nodes.ulSavedTabs.removeChild(this.nodes.ulSavedTabs.firstChild);
}
this.nodes.ulSavedTabs.style.width = '600px';
// add saved/favorite tabs
for (let savedTab of this.pt.whoIAm.currentTopic.favorites) {
this.addFavoriteTab(savedTab);
}
} else {
document.getElementById('divMainSavedTabs').classList.add('w3-hide');
}
}
}
// draw options for current Topic
drawTopicOptions() {
this.nodes.divOptions.innerHTML = "";
// themeSwitcher (maybe not the best location)
let light = document.getElementById("lightTheme");
let dark = document.getElementById("darkTheme");
// get theme state from storage area
dark.disabled = true;
light.disabled = false;
getLocalConfig('darkThemeEnabled')
.then((prop) => {
if ('darkThemeEnabled' in prop && prop['darkThemeEnabled'] === true) {
dark.disabled = false;
light.disabled = true;
butt.checked = true;
}
})
.catch(err => console.warn('drawTopicOptions(): Unable to get option from browser storage: %O', err));
let butt = document.getElementById("cb1");
butt.onclick = function () {
if (butt.checked) {
light.disabled = true;
dark.disabled = false;
setLocalConfig('darkThemeEnabled', true);
} else {
light.disabled = false;
dark.disabled = true;
setLocalConfig('darkThemeEnabled', false);
}
};
if (!this.pt.whoIAm || !this.pt.whoIAm.currentTopic) {
// its a regular Window
// add button to convert to Topic
let divConvert = document.createElement('div');
divConvert.classList.add('w3-display-topright', 'w3-xxlarge', 'w3-text-theme-light', 'far', 'fa-save', 'tooltip', 'my-zoom-hover');
divConvert.id = 'tipSaveAsTopic';
divConvert.style.marginRight = '35px';
divConvert.style.marginTop = '60px';
divConvert.style.position = 'absolute';
let spanConvertHelp = document.createElement('span');
spanConvertHelp.classList.add('tooltiptext', 'w3-text-theme-light');
spanConvertHelp.innerText = getTranslationFor("tipSaveAsTopic");
spanConvertHelp.style.top = '130px';
spanConvertHelp.style.right = '0';
divConvert.addEventListener('click', (e) => {
e.preventDefault();
// find BrowsingWindow instance;
let browsingWindow = this.pt.refSidebar.windows.find(win => win.id === this.pt.whoIAm.currentWindow.id);
if (browsingWindow) {
// call convert
browsingWindow.saveAsTopic()
.then()
.catch(err => console.warn('PopupMain converting window to topic failed: %O', err));
} else {
console.warn("Cannot convert Window to Topic, window not found in %O (current=%O)",
this.pt.refSidebar.windows, this.pt.whoIAm.currentWindow)
}
});
this.nodes.divOptions.appendChild(divConvert);
this.nodes.divOptions.appendChild(spanConvertHelp);
return;
}
// Name
let inputName = document.createElement('input');
inputName.classList.add('w3-border-bottom', 'w3-margin-bottom', 'w3-hover-border-theme');
inputName.name = 'Topic Name';
inputName.type = 'text';
inputName.value = this.pt.whoIAm.currentTopic.name;
inputName.autocomplete = false;
inputName.maxLength = 32;
inputName.required = true;
inputName.align = 'middle';
inputName.spellcheck = false;
inputName.style.border = 'none';
inputName.style.fontSize = '2em';
inputName.style.height = '50px';
inputName.style.width = '400px';
inputName.style.background = 'unset';
inputName.style.color = '36px';
let spanCreateTime = document.createElement('span');
spanCreateTime.classList.add('w3-small', 'w3-opacity-min', 'w3-text-theme-light');
spanCreateTime.innerText = getTranslationFor('Created') + ' ' + timeDifference(this.pt.whoIAm.currentTopic.createdTime);
spanCreateTime.style.userSelect = 'none';
spanCreateTime.style.right = '6%';
spanCreateTime.style.top = '97%';
spanCreateTime.style.position = 'fixed';
let divOptionsRight = document.createElement('div');
divOptionsRight.classList.add('w3-right');
// Topic to Trash
let iTrash = document.createElement('i');
iTrash.classList.add('w3-xxlarge', 'w3-padding-24', 'w3-margin-right', 'w3-text-theme', 'w3-hover-text-red', 'fa', 'fa-trash-alt', 'my-zoom-hover', 'tooltip');
iTrash.id = 'tipTopicToTrash';
let spanTrashTip = document.createElement('span');
spanTrashTip.classList.add('tooltiptext', 'w3-text-theme-light');
spanTrashTip.style.right = '40px';
spanTrashTip.style.top = '150px';
spanTrashTip.innerText = getTranslationFor('tipMoveTopicToTrash', 'Move Topic to Trash');
divOptionsRight.appendChild(iTrash);
divOptionsRight.appendChild(spanTrashTip);
// Color
let inputColor = document.createElement('input');
inputColor.id = 'tipTopicColor';
inputColor.classList.add('w3-border', 'w3-right', 'w3-margin', 'my-zoom-hover', 'colorChooser', 'tooltip');
inputColor.name = 'Topic Color';
inputColor.type = 'color';
inputColor.value = this.pt.whoIAm.currentTopic.color;
inputColor.style.height = '42px';
inputColor.style.width = '42px';
inputColor.style.cursor = 'pointer';
let spanColorTip = document.createElement('span');
spanColorTip.classList.add('tooltiptext', 'w3-text-theme-light');
spanColorTip.style.right = '20px';
spanColorTip.style.top = '150px';
spanColorTip.innerText = getTranslationFor('tipChangeTopicColor', 'Change topic color');
divOptionsRight.appendChild(inputColor);
divOptionsRight.appendChild(spanColorTip);
inputName.addEventListener('focusout', () => {
// save new name to DB
dbUpdateTopic(this.pt.whoIAm.currentTopic.id, {name: inputName.value})
.then(() => {
console.log("Topic Name update succeeded");
// update main
this.pt.refMain.updateTitle(inputName.value, inputColor.value);
PopupMain.updateFavicon(inputName.value, inputColor.value);
this.pt.whoIAm.currentTopic.name = inputName.value;
// update sidebar
this.pt.refSidebar.updateTopicInfo({
topicId: this.pt.whoIAm.currentTopic.id,
name: inputName.value,
color: inputColor.value
});
// inform other browser window instances about the updated tabs
browser.runtime.sendMessage({
action: 'TopicInfoUpdated',
detail: {
source: 'PopupMain.drawTopicOptions',
topicId: this.pt.whoIAm.currentTopic.id,
name: inputName.value,
color: inputColor.value
}
});
// reset input validation error
inputName.setCustomValidity("");
})
.catch(err => {
console.warn("Topic Name update failed: %O", err);
inputName.value = this.pt.whoIAm.currentTopic.name;
inputName.setCustomValidity("Unable to save - invalid name");
});
});
inputName.addEventListener("keyup", function (event) {
// Cancel the default action, if needed
event.preventDefault();
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
inputName.blur();
}
});
inputColor.addEventListener('change', () => {
// save new color to DB
dbUpdateTopic(this.pt.whoIAm.currentTopic.id, {color: inputColor.value})
.then(() => {
console.log("Topic Color update succeeded");
// update main
this.pt.refMain.updateTitle(inputName.value, inputColor.value);
PopupMain.updateFavicon(inputName.value, inputColor.value);
// update sidebar
this.pt.refSidebar.updateTopicInfo({
topicId: this.pt.whoIAm.currentTopic.id,
name: inputName.value,
color: inputColor.value
});
// inform other browser window instances about the updated tabs
browser.runtime.sendMessage({
action: 'TopicInfoUpdated',
detail: {
source: 'PopupMain.drawTopicOptions',
topicId: this.pt.whoIAm.currentTopic.id,
name: inputName.value,
color: inputColor.value
}
}).then().catch(err => console.warn('Unable to send browser message: %O', err));
})
.catch(err => {
console.warn("Topic Color update failed: %s", err);
inputColor.value = this.pt.whoIAm.currentTopic.color;
inputColor.setCustomValidity("Unable to save - invalid color?");
});
});
iTrash.addEventListener('click', (e) => {
e.preventDefault();
// find Topic instance, then call delete on it
let topic = this.pt.refSidebar.topics.find(topic => topic.id === this.pt.whoIAm.currentTopic.id);
if (topic) {
topic.moveToTrash();
} else {
console.warn("Cannot delete Topic, Topic not found in %O (current=%O)", this.pt.refSidebar.topics, this.pt.whoIAm.currentTopic)
}
});
this.nodes.divOptions.appendChild(inputName);
this.nodes.divOptions.appendChild(spanCreateTime);
this.nodes.divOptions.appendChild(divOptionsRight);
// delete button
}
/* on load, restore saved Topic tabs
* Note: This has to be done before PopupMain event listeners are registered
* Tabs will be initialized by PopupMain.draw()
*/
async restoreTabs() {
// close undesired tabs
async function closeSomeTabs() {
let tabs = await browser.tabs.query({currentWindow: true});
let tabCount = tabs.length;
for (let tab of tabs) {
if (tab.url.startsWith('about:') || tab.url.startsWith('chrome://newtab')) {
console.debug('restoreTabs() closed tab before restore: %d=%s', tab.index, tab.url);
await browser.tabs.remove(tab.id);
tabCount--;
}
}
return tabCount;
}
let tabCount = await closeSomeTabs();
if (this.pt.whoIAm && this.pt.whoIAm.currentTopic && 'tabs' in this.pt.whoIAm.currentTopic) {
// check if restore is needed (might be just a popup page refresh, or session restore)
if (tabCount !== 1) {
console.debug("PopupMain.restoreTabs(); restoring Tabs aborted, already %d tabs present", tabCount);
return false;
}
console.debug("PopupMain.restoreTabs(); restoring Tabs for Topic %s", this.pt.whoIAm.currentTopic.name);
// topic tabs are already loaded from Db by Topic init
for (let tab of this.pt.whoIAm.currentTopic.tabs) {
/*
if (tab.url.startsWith('about:')) {
continue;
}
*/
// url
// active
// title
// pinned
// openerTabId (todo this is more difficult as the old tabId has to be matched first)
await browser.tabs.create({url: tab.url, active: tab.active, pinned: tab.pinned});
}
return true;
}
return false;
}
// updates the title according to which window or topic is open
updateTitle(newTitle, newColor) {
document.title = newTitle;
let title = document.createElement('h4');
title.innerText = newTitle;
if (newColor) {
title.style.color = newColor;
} else {
title.style.color = "#ccc";
}
title.style.animation = 'fadein';
title.style.animationDuration = '5s';
this.nodes.header.innerHTML = '';
this.nodes.header.appendChild(title);
}
// add a tab to topic or window
addTab(tab) {
console.debug("PopupMain.addTab(): Adding tab with id %d", tab.id);
let newTab = new Tab(this.pt, tab);
if (typeof newTab.id === 'undefined') {
console.error("PopupMain.addTab(): new tab id is undefined!");
return false;
}
newTab.add(this.nodes.ulActiveTabs);
newTab.saveTabsToDb();
this.tabs.push(newTab);
}
removeTab(tabId) {
console.debug("PopupMain.removeTab(): Removing tab with id %d", tabId);
let tab = this.tabs.find(tab => tab.id === tabId);
if (tab) {
tab.remove(this.nodes.ulActiveTabs);
this.tabs = this.tabs.filter(tab => tab.id !== tabId);
tab.saveTabsToDb();
}
}
updateTab(tabId, newTab, changeInfo) {
console.debug("PopupMain.updateTab(): Updating tab with id %d; %s, allTabs=%O", tabId, JSON.stringify(changeInfo), this.tabs);
let tab = this.tabs.find(tab => tab.id === tabId);
if (tab) {
tab.update(this.nodes.ulActiveTabs, newTab, changeInfo);
// TODO updateTab is called often (loading/complete status), optimization of DB saving should be considered)
tab.saveTabsToDb();
}
}
/*
* Reorder tabs in Sortable list
* called when a tab is moved one Browser Window
*/
moveTab(tabId, moveInfo) {
console.debug("PopupMain.moveTab(): Moving tab with id %d; %s", tabId, JSON.stringify(moveInfo));
let tab = this.tabs.find(tab => tab.id === tabId);
if (tab) {
tab.move(this.nodes.ulActiveTabs, moveInfo.fromIndex, moveInfo.toIndex);
tab.saveTabsToDb();
}
}
/*
* Reorder tabs in Browser Window
* called when a tab is moved within one Sortable list
*/
moveTabInWindow(evt) {
// get tab by tabId
let tabId = Tab.idToInt(evt.item.id);
let tab = this.tabs.find(tab => tab.id === tabId);
if (tab) {
console.debug("PopupMain.moveTabInWindow() tab id=%d , %O", tabId, evt);
browser.tabs.move(tabId, {index: evt.newIndex});
}
}
// add a favorite tab to the list (it has already been saved to DB)
addFavoriteTab(savedTab) {
console.debug("PopupMain.addFavoriteTab(): Adding a saved tab - %O", savedTab);
if (document.getElementById('divMainSavedTabs').classList.contains('w3-hide')) {
document.getElementById('divMainSavedTabs').classList.remove('w3-hide');
}
let newSavedTab = new FavoriteTab(this.pt, savedTab);
newSavedTab.add(this.nodes.ulSavedTabs);
this.favorites.push(newSavedTab);
}
// remove a favorite tab from the list (it has already been updated in DB)
removeFavoriteTab(savedTab) {
console.debug("PopupMain.removeFavoriteTab(): Removing saved tab %O", savedTab);
let removeTab = this.favorites.find(tab => tab.url === savedTab.url);
if (removeTab) {
// remove from <li>
removeTab.remove(this.nodes.ulSavedTabs);
// and update the FavoriteTab array
this.favorites = this.favorites.filter(tab => tab.url !== savedTab.url);
}
if (this.favorites.length === 0) {
document.getElementById('divMainSavedTabs').classList.add('w3-hide');
}
}
/*
* called when any tab is opened, closed or changed
* if the tab belongs to a Topic window - the tabs will be saved to the Topics DB
*/
/* moved this to tab
saveTabsToDb(tab) {
if (this.pt.refSidebar.getTopicForWindowId(tab.windowId)) {
console.debug("saveTabsToDb() Tab with id=%d belongs to Topic window with id %d %O", tab.id, tab.windowId, tab);
} else {
console.debug("saveTabsToDb() Tab with id=%d does not belong to a Topic (window id %d)", tab.id, tab.windowId);
}
}
*/
static updateFavicon(title, color) {
let favUrl = createFavicon(title, color);
if (favUrl) {
favUrl.id = "favicon";
let head = document.getElementsByTagName('head')[0];
if (document.getElementById('favicon')) {
head.removeChild(document.getElementById('favicon'));
}
head.appendChild(favUrl);
}
}
/*
* initialize List filter which is fed by the search bar
*/
setupFilter() {
// search bar place holder
this.nodes.inputSearchBar.placeholder = getTranslationFor('SearchBarPlaceholder');
// jump to searchBar if 's' key is pressed
document.addEventListener('keyup', (event) => {
if ('key' in event) {
if (event.key === 's' && (document.activeElement && document.activeElement.nodeName !== 'INPUT')) {
this.nodes.inputSearchBar.focus();
}
}
});
// search bar event listener
this.nodes.inputSearchBar.addEventListener('keyup', () => {
this.filterTabs(this.nodes.inputSearchBar.value);
this.filterFavorites(this.nodes.inputSearchBar.value);
});
this.nodes.inputSearchBar.addEventListener('search', () => {
this.filterTabs(this.nodes.inputSearchBar.value);
this.filterFavorites(this.nodes.inputSearchBar.value);
});
}
filterTabs(searchTerm) {
console.debug("NEW filterTabs(): Search for %s", searchTerm);
if (!this.tabs || typeof searchTerm === 'undefined') {
return;
}
let foundByTitle = 0;
let foundByUrl = 0;
for (let tab of this.tabs) {
let title = tab.spanTabTitle.textContent;
let url = tab.spanTabUrl.textContent;
if (title && title.toUpperCase().indexOf(searchTerm.toUpperCase()) > -1) {
foundByTitle++;
tab.li.style.display = 'block';
} else if (url && url.toUpperCase().indexOf(searchTerm.toUpperCase()) > -1) {
foundByUrl++;
tab.li.style.display = 'block';
} else {
// hide the LI
tab.li.style.display = 'none';
}
}
console.debug("DONE filterTabs(): Search for %s in active Tabs (foundByTitle=%d, foundByUrl=%d)",
searchTerm, foundByTitle, foundByUrl);
}
filterFavorites(searchTerm) {
if (!this.favorites) {
return;
}
let foundByTitle = 0;
let foundByUrl = 0;
for (let fav of this.favorites) {
let title = fav.spanTabTitle.textContent;
let url = fav.spanTabUrl.textContent;
if (title.toUpperCase().indexOf(searchTerm.toUpperCase()) > -1) {
foundByTitle++;
fav.li.style.display = 'block';
} else if (url.toUpperCase().indexOf(searchTerm.toUpperCase()) > -1) {
foundByUrl++;
fav.li.style.display = 'block';
} else {
// hide the LI
fav.li.style.display = 'none';
}
}
console.debug("filterFavorites(): Search for %s in favorite Tabs (foundByTitle=%d, foundByUrl=%d)",
searchTerm, foundByTitle, foundByUrl);
}
registerEvents() {
// listen to global events (received from other Browser window or background script)
browser.runtime.onMessage.addListener((request) => {
// endpoints called by popup.js
switch (request.action) {
case 'TabCreated':
if (this.pt.whoIAm.currentWindow.id === request.detail.tab.windowId) {
console.debug("Browser Event TabCreated received: detail=%O", request.detail);
this.addTab(request.detail.tab);
// update title (sidebar + main)
this.pt.refSidebar.updateWindowInfo(request.detail.tab.windowId);
browser.runtime.sendMessage({
action: 'UpdateWindowInfo',
detail: {windowId: request.detail.tab.windowId}
});
}
break;
case 'TabRemoved':
if (this.pt.whoIAm.currentWindow.id === request.detail.removeInfo.windowId) {
console.debug("Browser Event TabRemoved received: detail=%O", request.detail);
this.removeTab(request.detail.tabId);
// update title (sidebar + main)
this.pt.refSidebar.updateWindowInfo(request.detail.removeInfo.windowId);
browser.runtime.sendMessage({
action: 'UpdateWindowInfo',
detail: {windowId: request.detail.removeInfo.windowId}
});
}
break;
case 'TabMoved':
if (this.pt.whoIAm.currentWindow.id === request.detail.moveInfo.windowId) {
console.debug("Browser Event TabMoved received: detail=%O", request.detail);
this.moveTab(request.detail.tabId, request.detail.moveInfo);
// update title of other windows (sidebar + main)
this.pt.refSidebar.updateWindowInfo(request.detail.moveInfo.windowId);
browser.runtime.sendMessage({
action: 'UpdateWindowInfo',
detail: {windowId: request.detail.moveInfo.windowId}
});
}
break;
case 'TabUpdated':
if (request.detail.tab && this.pt.whoIAm.currentWindow.id === request.detail.tab.windowId) {
console.debug("Browser Event TabUpdated received: detail=%O", request.detail);
this.updateTab(request.detail.tabId, request.detail.tab, request.detail.changeInfo);
// changeInfo.status == Complete, URL/Title changed?
if (request.detail.changeInfo && 'status' in request.detail.changeInfo && request.detail.changeInfo.status === 'complete') {
// update title on other instances (sidebar + main)
this.pt.refSidebar.updateWindowInfo(request.detail.tab.windowId);
browser.runtime.sendMessage({
action: 'UpdateWindowInfo',
detail: {windowId: request.detail.tab.windowId}
});
}
}
break;
case 'TabReplaced':
// TabReplaced can happen e.g. when Tab gets discarded.
// No windowId is received, so check if old TabId is know to this window
let tab = this.tabs.find(tab => tab.id === request.detail.removedTabId);
if (tab) {
console.debug("Browser Event TabReplaced received: detail=%O", request.detail);
tab.id = request.detail.addedTabId;
}
break;
}
});
// when add tab button clicked
this.nodes.butAddTab.addEventListener('click',() => {
browser.tabs.create({})
.then()
.catch(err => console.warn('Tab creation problem: %O', err));
});
}
} |
JavaScript | class BrowsingWindow {
// windowId
// window open since
// tab list
// isOpen
// open
// check if window contains a Topic
constructor(pt, window) {
this.pt = pt;
// id might be undefined - means its a new topic to be saved
this.id = window.id;
this.window = window;
this.title = "Window";
// li element in sidebar
this.li = "";
this.icon = {};
// bind this
this.add = this.add.bind(this);
this.constructWindowTitle = this.constructWindowTitle.bind(this);
this.updateWindowTitle = this.updateWindowTitle.bind(this);
}
//region Sidebar / Windows
// add one window to the given list
add(ul) {
this.li = document.createElement('li');
this.li.classList.add('w3-bar', 'w3-button');
// this.id is the Window Id
this.li.style.padding = '1px 0px';
this.li.style.lineHeight = '20px';
this.li.style.width = '285px';
this.li.setAttribute("id", "window-" + this.id);
// color-icon
this.icon = document.createElement('img');
this.icon.classList.add('w3-bar-item', 'w3-image', 'w3-circle', 'drag-handle');
let favLink = createFavicon(this.title.charAt(0).toUpperCase(), '#ccc');
if (favLink) {
this.icon.setAttribute('src', favLink.href);
}
this.icon.style.filter = 'opacity(20%)';
this.icon.style.padding = 'unset';
this.icon.style.marginLeft = '5px';
this.icon.style.height = '36px';
// link
let divWindow = document.createElement('div');
divWindow.classList.add('w3-bar-item', 'w3-left-align');
divWindow.style.width = '150px';
this.updateWindowTitle();
// if current window, then add selected css class
if (this.id === this.pt.whoIAm.currentWindow.id) {
this.li.classList.add('statusSelected');
}
//add event listener for each tab link
this.li.addEventListener('mouseenter', () => {
this.icon.style.filter = 'opacity(100%)';
});
this.li.addEventListener('mouseleave', () => {
this.icon.style.filter = 'opacity(20%)';
});
// activate the window
this.li.addEventListener('click', (e) => {
e.preventDefault();
browser.windows.update(this.id, {focused: true})
.then(() => {
let bg = browser.extension.getBackgroundPage();
bg.openPapaTab({windowId: this.id});
})
.catch(err => console.error("BrowsingWindow activate failed: %s", err));
});
this.li.appendChild(this.icon);
this.li.appendChild(divWindow);
ul.appendChild(this.li);
}
// removes this window from specified list
remove(ul) {
if (this.li && ul.contains(this.li)) {
ul.removeChild(this.li);
}
}
// Build title from tabs in the window: google.de +7 , or "New Window" for window without (real) tabs
async constructWindowTitle() {
let title = new String('');
let count = 0;
let win = await browser.windows.get(this.id, {populate: true});
for (let tab of win.tabs) {
count++;
if (tab.pinned === false) {
if (title.valueOf() === '') {
try {
let url = new URL(tab.url);
//title = url.hostname.replace(/^www./, '').trunc(14);
title = punycode.toUnicode(url.hostname).replace(/^www./, '').trunc(14);
console.debug('constructWindowTitle(): title set to "%s" (from tab=%s)', title, tab.url);
} catch (err) {
console.warn("BrowsingWindow.constructWindowTitle() %s", err);
title = tab.url;
}
}
}
}
if (count <= 1 || title.valueOf() === '') {
this.title = getTranslationFor('newWindow');
} else if (count < 3) {
this.title = title;
} else {
this.title = title + " +" + (count - 2);
}
}
updateWindowTitle() {
console.debug("BrowsingWindow.updateWindowTitle() called for id=%d", this.id);
this.constructWindowTitle().then(() => {
let div = this.li.getElementsByTagName('div')[0];
div.innerText = this.title;
// update Sidebar Icon
let favLink = createFavicon(this.title.charAt(0).toUpperCase(), '#ccc');
if (favLink) {
this.icon.setAttribute('src', favLink.href);
}
if (this.pt.whoIAm.currentWindow.id === this.id) {
// update popup title (Browser Window Title) if this is the title of current window
document.title = this.title;
// update Main view title
this.pt.refMain.updateTitle(this.title);
}
});
}
/*
* Convert Browsing Window to topic
*/
async saveAsTopic() {
console.debug("BrowsingWindow.saveAsTopic() called for windowId=%d", this.window.id);
let tabs = await browser.tabs.query({windowId: this.window.id});
tabs = tabs.filter(tab => !tab.url.includes(browser.extension.getURL('')));
let info = {
name: this.title,
color: getRandomColor(),
windowId: this.window.id,
tabs: tabs,
};
// generate Topic DB entry
info.id = await dbAddTopic(this.title,);
// update Topic Info
await dbUpdateTopic(info.id, info);
this.pt.refSidebar.addTopic(info);
// inform other instances about created Topic
browser.runtime.sendMessage({
action: 'TopicAdd',
detail: info
});
// inform other instances about removed window as it is now a Topic (identified by this.id)
browser.runtime.sendMessage({
action: 'WindowRemoved',
detail: {windowId: this.id, converted: true}
});
// reload this instance for easiness' sake
await browser.tabs.reload();
}
} |
JavaScript | class ModalAddTopic {
constructor(pt) {
this.pt = pt;
// DOM Nodes
this.nodes = {
div: document.getElementById('modalAddTopic'),
};
this.divError = {};
this.color = '#ff0000';
this.input = '';
this.registerEvents = this.registerEvents.bind(this);
this.addTopic = this.addTopic.bind(this);
this.show = this.show.bind(this);
this.hide = this.hide.bind(this);
}
draw() {
this.nodes.div.innerHTML = '';
let divCard = document.createElement('div');
divCard.classList.add('w3-card-4', 'w3-modal-content', 'w3-animate-top');
divCard.style.maxWidth = '600px';
// 'X'
let spanClose = document.createElement('span');
spanClose.classList.add('w3-button', 'w3-xlarge', 'w3-hover-deep-orange', 'w3-display-topright');
spanClose.title = getTranslationFor('Close');
spanClose.innerHTML = '×';
divCard.appendChild(spanClose);
// headline
let divHeadline = document.createElement('div');
divHeadline.classList.add('w3-display-bottomright', 'w3-padding', 'w3-xxlarge');
let hHeadline = document.createElement('h5');
hHeadline.innerText = getTranslationFor('modalCreateNewTopic');
divHeadline.appendChild(hHeadline);
divCard.appendChild(divHeadline);
// form
let form = document.createElement('form');
form.classList.add('w3-container', 'w3-padding-16');
// section: name
let divName = document.createElement('div');
divName.classList.add('w3-section');
let labelName = document.createElement('label');
labelName.innerText = getTranslationFor('modalTopicName');
let inputName = document.createElement('input');
inputName.classList.add('w3-input', 'w3-margin-bottom');
inputName.placeholder = getTranslationFor("modalInputNamePlaceholder");
inputName.type = 'text';
inputName.required = true;
inputName.autocomplete = 'off';
inputName.autofocus = true;
inputName.minlength = 3;
inputName.maxLength = 32;
divName.appendChild(labelName);
divName.appendChild(inputName);
form.appendChild(divName);
// section: color
let divColor = document.createElement('div');
divColor.classList.add('w3-section');
let labelColor = document.createElement('label');
labelColor.innerText = getTranslationFor('modalTopicColor');
let inputColor = document.createElement('input');
inputColor.classList.add('w3-responsive');
inputColor.type = 'color';
inputColor.value = this.color;
inputColor.style.width = '70px';
divColor.appendChild(labelColor);
divColor.appendChild(inputColor);
form.appendChild(divColor);
// button: create
let butCreate = document.createElement('button');
butCreate.classList.add('w3-button', 'w3-block', 'w3-green', 'w3-section', 'w3-padding');
butCreate.type = 'submit';
butCreate.accessKey = 's';
butCreate.innerText = getTranslationFor("Create");
form.appendChild(butCreate);
divCard.appendChild(form);
//
let divCancel = document.createElement('div');
divCancel.classList.add('w3-container', 'w3-border-top', 'w3-padding-16', 'w3-light-grey');
// button: cancel
let butCancel = document.createElement('button');
butCancel.classList.add('w3-button', 'w3-deep-orange');
butCancel.accessKey = 'c';
butCancel.innerText = getTranslationFor('Cancel');
divCancel.appendChild(butCancel);
divCard.appendChild(divCancel);
// name error (hidden by default)
this.divError = document.createElement('div');
this.divError.classList.add('w3-container', 'w3-red', 'w3-hide', 'w3-animate-bottom');
this.divError.innerHTML = '<p>No Error</p>';
form.appendChild(this.divError);
butCancel.addEventListener('click', () => {
this.hide();
});
spanClose.addEventListener('click', () => {
this.hide();
});
inputName.addEventListener('input', (e) => {
this.name = inputName.value;
});
inputColor.addEventListener('input', (e) => {
this.color = inputColor.value;
});
form.addEventListener('submit', (event) => {
event.preventDefault();
return this.addTopic(event);
});
// append to pre-created div
this.nodes.div.appendChild(divCard);
}
// TODO: improve topic validation https://pageclip.co/blog/2018-02-20-you-should-use-html5-form-validation.html
addTopic(event) {
console.debug("Modal.addTopic() triggered event=%O", event);
let newTopic = new Topic({
pt: this.pt,
name: this.name,
color: this.color,
});
newTopic.addToDb()
.then(() => {
// reset modal
this.hide();
})
.catch(err => {
this.divError.classList.remove('w3-hide');
// topicAddFailed = Unable to store Topic. Please check the name and try again.
let msg = getTranslationFor('topicAddFailed');
this.divError.innerHTML = '<p>' + msg + '</p>';
console.warn("Modal.addTopic() failed; %s", err)
});
}
registerEvents() {
this.nodes.div.addEventListener('TopicAdd', () => {
this.draw();
this.show();
});
// When the user clicks anywhere outside of the topic creation modal, close it
this.nodes.div.onclick = (event) => {
if (event.target === this.nodes.div) {
this.hide();
}
}
}
show() {
this.nodes.div.style.display = 'block';
}
hide() {
this.nodes.div.style.display = 'none';
}
} |
JavaScript | class Tab {
constructor(pt, tab) {
this.pt = pt;
this.id = tab.id;
// browser.tab object
this.tab = tab;
this.li = "";
this.spanTabTitle = {};
this.spanTabUrl = {};
this.imgFavIcon = {};
this.imgTabPinned = {};
this.imgTabAudible = {};
this.imgTabDiscarded = {};
this.spanPinHelp = {};
// bind this
this.add = this.add.bind(this);
this.update = this.update.bind(this);
}
// add a tab link li element to an existing list (Main view)
add(ul) {
this.li = document.createElement('li');
this.li.classList.add('w3-bar', 'hidden-info');
// this.id is the Window Id
this.li.setAttribute("id", "tab-" + this.id);
this.li.style.padding = '1px 0px';
this.li.style.lineHeight = '13px';
// favicon image
this.imgFavIcon = document.createElement('img');
//try to get best favicon url path
this.imgFavIcon.setAttribute('src', Tab.getFavIconSrc(this.tab.url, this.tab.favIconUrl));
this.imgFavIcon.classList.add('w3-bar-item', 'w3-circle'); // 'w3-padding-small'
this.imgFavIcon.style.height = '32px';
this.imgFavIcon.style.padding = '4px 4px 4px 12px';
//this.imgFavIcon.style.verticalAlign = 'middle';
// tab div
let divTab = document.createElement('div');
divTab.classList.add('w3-bar-item', 'w3-button', 'w3-left-align');
divTab.style.width = '70%';
divTab.style.height = '32px';
divTab.style.padding = '2px 0';
this.spanTabTitle = document.createElement('span');
this.spanTabTitle.classList.add('w3-medium', 'truncate');
this.spanTabTitle.style.width = '95%';
this.spanTabTitle.style.height = '55%';
this.spanTabTitle.innerText = this.tab.title;
this.spanTabUrl = document.createElement('span');
this.spanTabUrl.classList.add('truncate');
this.spanTabUrl.innerText = punycode.toUnicode(this.tab.url);
this.spanTabUrl.classList.add('w3-small', 'hidden-text');
this.spanTabUrl.style.width = '95%';
this.spanTabUrl.style.height = '45%';
divTab.appendChild(this.spanTabTitle);
divTab.appendChild(document.createElement('br'));
divTab.appendChild(this.spanTabUrl);
let statusTipMargin = '75px';
if (this.pt.whoIAm && typeof this.pt.whoIAm.currentTopic !== 'undefined') {
statusTipMargin = '100px'
}
/* create status bar with various icons, these will be hidden by default */
let divStatus = document.createElement('div');
divStatus.classList.add('w3-right', 'tabStatusBar');
this.imgTabDiscarded = document.createElement('i');
this.imgTabDiscarded.title = 'Tab discarded status';
this.imgTabDiscarded.classList.add('w3-large', 'w3-padding-small', 'fas', 'fa-pause-circle');
divStatus.appendChild(this.imgTabDiscarded);
this.imgTabAudible = document.createElement('i');
this.imgTabAudible.title = 'Tab audible status';
this.imgTabAudible.classList.add('w3-large', 'w3-padding-small', 'fas', 'fa-volume-up');
divStatus.appendChild(this.imgTabAudible);
this.imgTabPinned = document.createElement('i');
this.imgTabPinned.id = 'tipPinTab';
this.imgTabPinned.classList.add('w3-large', 'w3-padding-small', 'fas', 'fa-thumbtack', 'tooltip', 'my-zoom-hover');
divStatus.appendChild(this.imgTabPinned);
this.spanPinHelp = document.createElement('span');
this.spanPinHelp.style.marginRight = statusTipMargin;
this.spanPinHelp.classList.add('tooltiptext');
divStatus.appendChild(this.spanPinHelp);
// handle Topic tab favorites
if (this.pt.whoIAm && typeof this.pt.whoIAm.currentTopic !== 'undefined') {
this.imgTabFavorite = document.createElement('i');
this.imgTabFavorite.id = 'tipFavoriteTab';
this.imgTabFavorite.classList.add('w3-large', 'w3-padding-small', 'fas', 'fa-star', 'tooltip', 'my-zoom-hover');
divStatus.appendChild(this.imgTabFavorite);
this.spanFavoriteHelp = document.createElement('span');
this.spanFavoriteHelp.style.marginRight = statusTipMargin;
this.spanFavoriteHelp.classList.add('tooltiptext');
divStatus.appendChild(this.spanFavoriteHelp);
this.imgTabFavorite.style.opacity = '0.05';
this.spanFavoriteHelp.innerText = getTranslationFor('SaveTab');
// determine if a Tab has favorite status by query to Topic instance (URL has to perfectly match)
if (this.isFavorite()) {
this.imgTabFavorite.style.opacity = '0.6';
this.spanFavoriteHelp.innerText = getTranslationFor('UnsaveTab');
}
// toggle favorite click
this.imgTabFavorite.addEventListener('click', (e) => {
e.preventDefault();
this.toggleFavorite();
});
}
// 'X' span
this.imgTabClose = document.createElement('i');
this.imgTabClose.id = 'tipCloseTab';
this.imgTabClose.classList.add('w3-large', 'w3-padding-small', 'w3-hover-text-deep-orange', 'fas', 'fa-times-circle', 'tooltip', 'my-zoom-hover');
this.imgTabClose.style.opacity = '0.6';
divStatus.appendChild(this.imgTabClose);
let spanCloseHelp = document.createElement('span');
spanCloseHelp.classList.add('tooltiptext');
spanCloseHelp.style.marginRight = statusTipMargin;
spanCloseHelp.innerText = getTranslationFor('Close');
divStatus.appendChild(spanCloseHelp);
if (this.tab.pinned) {
this.imgTabPinned.style.opacity = '0.6';
this.li.classList.remove('can-be-dragged');
this.imgFavIcon.classList.remove('drag-handle');
this.spanPinHelp.innerText = getTranslationFor('Unpin');
} else {
this.imgTabPinned.style.opacity = '0.05';
this.li.classList.add('can-be-dragged');
this.imgFavIcon.classList.add('drag-handle');
this.spanPinHelp.innerText = getTranslationFor('Pin');
}
if (this.tab.discarded) {
this.imgTabDiscarded.style.opacity = '0.6';
} else {
this.imgTabDiscarded.style.opacity = '0.05';
}
if (this.tab.audible) {
this.imgTabAudible.style.opacity = '0.6';
} else {
this.imgTabAudible.style.opacity = '0.05';
}
//add event listener for each tab link
divTab.addEventListener("click", (e) => {
e.preventDefault();
this.activate();
});
// close tab on click
this.imgTabClose.addEventListener('click', (e) => {
e.preventDefault();
this.close();
});
// pin tab on click
this.imgTabPinned.addEventListener('click', (e) => {
e.preventDefault();
this.togglePinned();
});
// hide internal tabs (user should not mess with)
if (this.tab.url.match(browser.extension.getURL(''))) {
this.li.classList.add('w3-hide');
}
// todo duplicate tab detection
/*
if (tab.duplicate) {
linkEl.className = 'duplicate';
}
*/
this.li.appendChild(this.imgFavIcon);
this.li.appendChild(divTab);
this.li.appendChild(divStatus);
ul.appendChild(this.li);
}
remove(ul) {
if (this.li && ul.contains(this.li)) {
ul.removeChild(this.li);
}
}
close() {
browser.tabs.remove(this.id)
.then(() => {
console.debug("Tab.close() for id=%d performed", this.id);
})
.catch(err => {
console.error("Tab.close() failed; %s", err);
});
}
togglePinned() {
if (this.tab.pinned) {
browser.tabs.update(this.id, {pinned: false})
.then(() => {
console.debug("Tab.togglePinned() for id=%d performed (unpin)", this.id);
this.tab.pinned = false;
})
.catch(err => {
console.warn("Tab.togglePinned() failed; %s", err)
});
} else {
browser.tabs.update(this.id, {pinned: true})
.then(() => {
console.debug("Tab.togglePinned() for id=%d performed (pin)", this.id);
this.tab.pinned = true;
})
.catch(err => {
console.warn("Tab.togglePinned() failed; %s", err)
});
}
}
move(ul, fromIndex, toIndex) {
if (this.li && ul.contains(this.li)) {
// remove from old index
ul.removeChild(this.li);
// insert at new index
ul.insertBefore(this.li, ul.childNodes[toIndex]);
}
}
// Activate (focus) the tab
activate() {
browser.tabs.update(this.id, {active: true});
}
update(ul, newTab, info) {
console.debug("Tab.update() update tab with id=%d", this.id);
if (newTab) {
this.tab = newTab;
}
if (info && 'status' in info) {
if (info.status === 'complete') {
this.spanTabTitle.innerText = newTab.title;
}
}
if (info && 'title' in info) {
if (this.spanTabTitle) {
this.spanTabTitle.innerText = info.title;
}
}
else if (info && 'url' in info) {
if (this.spanTabUrl) {
this.spanTabUrl.innerText = punycode.toUnicode(info.url);
}
}
else if (info && 'favIconUrl' in info) {
if (this.imgFavIcon) {
this.imgFavIcon.setAttribute('src', Tab.getFavIconSrc(this.tab.url, info.favIconUrl));
}
}
else if (info && 'audible' in info) {
if (info.audible) {
this.imgTabAudible.style.opacity = '0.6';
} else {
this.imgTabAudible.style.opacity = '0.05';
}
}
else if (info && 'discarded' in info) {
if (info.discarded) {
this.imgTabDiscarded.style.opacity = '0.6';
} else {
this.imgTabDiscarded.style.opacity = '0.05';
}
}
else if (info && 'pinned' in info) {
if (info.pinned) {
this.imgTabPinned.style.opacity = '0.6';
this.li.classList.remove('can-be-dragged');
this.imgFavIcon.classList.remove('drag-handle');
this.spanPinHelp.innerText = getTranslationFor('Unpin');
} else {
this.imgTabPinned.style.opacity = '0.05';
this.li.classList.add('can-be-dragged');
this.imgFavIcon.classList.add('drag-handle');
this.spanPinHelp.innerText = getTranslationFor('Pin');
}
}
else if (info && 'favorite' in info) {
if (info.favorite) {
this.imgTabFavorite.style.opacity = '0.6';
} else {
this.imgTabFavorite.style.opacity = '0.05';
}
}
}
// calls Topic.saveTabsToDb if the Tab is located in a Topic Window
saveTabsToDb() {
let topic = this.pt.refSidebar.getTopicForWindowId(this.tab.windowId);
if (topic) {
console.debug("Tab(%d).saveTabsToDb() Tab belongs to Topic %s", this.id, topic.name);
topic.saveTabsToDb()
.then(() => topic.updateInfo())
.catch(err => console.error("PopupMain.addTab(): saveTabsToDb() failed; %s", err));
}
}
// return Topic favorites
getFavorites() {
// get favorites from Topic
let topic = this.pt.whoIAm.currentTopic;
if (topic) {
return typeof topic.favorites !== 'undefined' ? topic.favorites : [];
}
return [];
}
/*
* determine if a Tab is a Favorite by comparing the URL
* the URL has to perfectly match
* @return Returns true if the given URL is stored as a favorite
*/
isFavorite() {
let favorites = this.getFavorites();
if (typeof favorites !== 'undefined' && favorites.find(fav => fav.url === this.tab.url)) {
return true;
} else {
return false;
}
}
/*
* Toggles favorite state for specific tab
* updates the Topic entry in DB
*/
toggleFavorite() {
let favorites = this.getFavorites();
let isFavorite = false;
let newFavorite = {
createdTime: Date.now(),
title: this.tab.title,
url: this.tab.url,
favSrc: this.imgFavIcon.src
};
// prepare 'favorites' Array to be stored in DB
if (this.isFavorite()) {
// Remove Favorite
favorites = favorites.filter(fav => fav.url !== this.tab.url);
} else {
// Add Favorite
favorites.push(newFavorite);
isFavorite = true;
}
// update Topic DB entry
dbUpdateTopic(this.pt.whoIAm.currentTopic.id, {favorites: favorites})
.then(() => {
// update the Favorite Icon
this.update(this.pt.refMain.nodes.ulActiveTabs, undefined, {favorite: isFavorite});
// update the currentTopic info
this.pt.whoIAm.currentTopic.favorites = favorites;
// update the Favorite Tabs List
if (isFavorite) {
// favorite has been added
this.pt.refMain.addFavoriteTab(newFavorite);
} else {
// favorite has been removed (use newFavorite which is good enough, except the createdTime field)
this.pt.refMain.removeFavoriteTab(newFavorite);
}
})
.catch(err => console.error("Tab.toggleFavorite(): Failed to dbUpdateTopic(), err=%O", err));
}
static getFavIconSrc(url, favIconUrl) {
//try to get best favicon url path
if (favIconUrl) {
return favIconUrl;
} else {
// return a default icon
return browser.extension.getURL('globe.png');
}
}
// convert HTML element id to TabId, e.g. "tab-12345" -> 12345
static idToInt(elementId) {
return parseInt(elementId.replace(/^tab-/, ''));
}
} |
JavaScript | class FavoriteTab {
constructor(pt, savedTab) {
this.pt = pt;
this.li = "";
this.title = savedTab.title;
this.url = savedTab.url;
this.favSrc = savedTab.favSrc;
this.spanTabTitle = {};
this.spanTabUrl = {};
this.imgFavIcon = {};
// bind this
this.add = this.add.bind(this);
}
// add a tab link li element to an existing list (Main view)
add(ul) {
this.li = document.createElement('li');
this.li.classList.add('w3-bar', 'hidden-info');
this.li.style.padding = '1px 0px';
this.li.style.lineHeight = '13px';
// favicon image
this.imgFavIcon = document.createElement('img');
//try to get best favicon url path
this.imgFavIcon.setAttribute('src', this.favSrc);
this.imgFavIcon.classList.add('w3-bar-item', 'w3-circle'); // 'w3-padding-small'
this.imgFavIcon.style.height = '32px';
this.imgFavIcon.style.padding = '4px 12px';
// tab div
let divTab = document.createElement('div');
divTab.classList.add('w3-bar-item', 'w3-button', 'w3-left-align');
divTab.style.width = '80%';
divTab.style.padding = '2px 0';
this.spanTabTitle = document.createElement('span');
this.spanTabTitle.classList.add('w3-medium', 'truncate');
this.spanTabTitle.style.width = '95%';
this.spanTabTitle.style.height = '55%';
this.spanTabTitle.innerText = this.title;
this.spanTabUrl = document.createElement('span');
this.spanTabUrl.classList.add('truncate');
this.spanTabUrl.innerText = punycode.toUnicode(this.url);
this.spanTabUrl.classList.add('w3-small', 'hidden-text');
this.spanTabUrl.style.width = '95%';
this.spanTabUrl.style.height = '45%';
divTab.appendChild(this.spanTabTitle);
divTab.appendChild(document.createElement('br'));
divTab.appendChild(this.spanTabUrl);
/* create status bar with various icons, these will be hidden by default */
let divStatus = document.createElement('div');
divStatus.classList.add('w3-right', 'tabStatusBar');
// 'X' span
this.imgTabClose = document.createElement('i');
this.imgTabClose.id = 'tipCloseTab';
this.imgTabClose.classList.add('w3-right', 'w3-large', 'w3-padding-small', 'w3-hover-text-deep-orange', 'fas', 'fa-times-circle', 'tooltip', 'my-zoom-hover');
this.imgTabClose.style.opacity = '0.6';
divStatus.appendChild(this.imgTabClose);
let spanCloseHelp = document.createElement('span');
spanCloseHelp.classList.add('tooltiptext');
spanCloseHelp.style.right = '20px';
spanCloseHelp.innerText = getTranslationFor('Remove');
divStatus.appendChild(spanCloseHelp);
//add event listener for each tab link
divTab.addEventListener("click", (e) => {
e.preventDefault();
this.load();
});
// remove from favorites
this.imgTabClose.addEventListener('click', (e) => {
e.preventDefault();
this.removeFromDb();
});
this.li.appendChild(this.imgFavIcon);
this.li.appendChild(divTab);
this.li.appendChild(divStatus);
ul.appendChild(this.li);
}
remove(ul) {
if (this.li && ul.contains(this.li)) {
ul.removeChild(this.li);
}
}
/*
* remove favorite from DB
* if any open Tab for this Favorite inform it that its not favorite anymore (but leave it open)
*/
async removeFromDb() {
// read topic favorites from DB
let topic = await dbGetTopicBy('id', this.pt.whoIAm.currentTopic.id).first();
let favorites = [];
if (topic) {
// prepare 'favorites' Array to be stored in DB
if ('favorites' in topic) {
console.debug("FavoriteTab.removeFromDb(): removing favorite with url=%s", this.url);
favorites = topic.favorites;
favorites = favorites.filter(fav => fav.url !== this.url);
// update Topic DB entry
await dbUpdateTopic(this.pt.whoIAm.currentTopic.id, {favorites: favorites});
this.pt.whoIAm.currentTopic.favorites = favorites;
this.pt.refMain.removeFavoriteTab(this);
// update tab (Favorite status)
let tabs = this.pt.refMain.tabs.filter(Tab => Tab.tab.url === this.url);
if (tabs) {
for (let tab of tabs) {
tab.update(this.pt.refMain.nodes.ulActiveTabs, undefined, {favorite: false});
}
}
}
}
}
/* load this favorite tab into the browser or activate existing tab */
load() {
// find tab with this URL
browser.tabs.query({url: this.url})
.then((tabs) => {
if (tabs.length === 0) {
// create new tab
browser.tabs.create({url: this.url, active: true});
} else {
browser.tabs.update(tabs[0].id, {active: true});
}
})
.catch(err => console.error("SavedTab.load() error %O", err));
}
} |
JavaScript | class User {
constructor(userName) {
this.userName = userName;
// this.levelRecords = [3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
this.levelRecords = [3, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0];
}
} |
JavaScript | class RGB {
constructor(r = 0, g = 0, b = 0) {
this.r = r
this.g = g
this.b = b
this.red = r
this.green = g
this.blue = b
}
toHex () {
return new Hex('#' + this.r.toString(16) + this.g.toString(16) + this.b.toString(16))
}
toRGB () {
return new RGB(this.r, this.g, this.b)
}
toRGBA () {
return new RGB(this.r, this.g, this.b, this.a || 255)
}
} |
JavaScript | class Hex {
constructor (hex) {
if (typeof hex !== 'string') {
throw new TypeError('Expected a string')
}
let hexParts = hex.split('') // split into array
if (hexParts[0] === '#') hexParts.shift() // remove # if present
if (hexParts.length == 3) {
// Generate a 6 digit hex from 3 digit hex
let newHexParts = []
hexParts = hexParts.map(function (part) {
newHexParts.push(part)
newHexParts.push(part)
return part + part
})
hexParts = newHexParts
}
if (hexParts.length !== 6) {
throw new TypeError('Expected a 6-digit hex string')
}
// Check if only the characters A-F and 0-9 are present
if (!hexParts.every(function (part) {
return /^[0-9A-F]$/i.test(part)
})) {
return false
}
hex = hexParts.join('') // Convert array to string
this.hex = hex // Store hex string
}
toString () {
return this.hex
}
withHash () {
return '#' + this.hex
}
toRGB () {
// Convert hex to RGB
var r = parseInt(this.hex.substring(0, 2), 16)
var g = parseInt(this.hex.substring(2, 4), 16)
var b = parseInt(this.hex.substring(4, 6), 16)
return new RGB(r, g, b)
}
toRGBA () {
// Convert hex to RGBA
var r = parseInt(this.hex.substring(0, 2), 16)
var g = parseInt(this.hex.substring(2, 4), 16)
var b = parseInt(this.hex.substring(4, 6), 16)
var a = 255
return new RGBA(r, g, b, a)
}
} |
JavaScript | class Poi {
constructor(
jsondata,
city,
idstore,
name,
date,
distance,
duration,
latitude,
locationid,
longitude,
zipcode,
radius,
address,
countrycode,
tags,
types,
contact
) {
this.Jsondata = jsondata;
this.City = city;
this.Idstore = idstore;
this.Name = name;
this.Date = date;
this.Distance = distance;
this.Duration = duration;
this.Latitude = latitude;
this.Locationid = locationid;
this.Longitude = longitude;
this.Zipcode = zipcode;
this.Radius = radius;
this.Idstore = idstore;
this.Countrycode = countrycode;
this.Tags = tags;
this.Types = types;
this.Contact = contact;
}
/**
* Converts json object to an object of type Poi.
* @param {Object} json The json representation of the Poi.
* @returns Object
* @memberof Poi
*/
static jsonToObj(json) {
return new Poi(
json.jsondata,
json.city,
json.idstore,
json.name,
json.date,
json.distance,
json.duration,
json.latitude,
json.locationid,
json.longitude,
json.zipcode,
json.radius,
json.address,
json.countrycode,
json.tags,
json.types,
json.contact
);
}
} |
JavaScript | class CompositeWidget extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
formData: { ...props.formData },
};
}
componentWillReceiveProps(props) {
this.setState({
formData: { ...props.formData },
});
}
onPropertyChanged(name, value) {
const dataCopy = { ...this.state.formData, [name]: value };
this.onFormDataChanged(dataCopy);
}
onFormDataChanged(newFormData, callback = undefined) {
this.setState({
formData: newFormData,
}, () => {
this.props.onChange(newFormData);
if (callback) callback();
});
}
isRequired(name) {
const { schema } = this.props;
return (
Array.isArray(schema.required) && schema.required.indexOf(name) !== -1
);
}
// render child schema, while keeps form
renderSchema(name, extraProps = {}, extraUISchema = {},
SpecifiedSchemaField = undefined, extraSchema = {}) {
const { registry, schema, idSchema, formData, uiSchema,
errorSchema, onBlur, onFocus, disabled, readonly } = this.props;
const { fields } = registry;
const { SchemaField } = fields;
const RenderField = SpecifiedSchemaField || SchemaField;
return (
<RenderField
key={name}
name={name}
required={this.isRequired(name)}
schema={{ ...schema.properties[name], ...extraSchema }}
uiSchema={{ ...uiSchema[name], ...extraUISchema }}
errorSchema={errorSchema[name]}
idSchema={idSchema[name]}
formData={formData[name]}
onChange={value => this.onPropertyChanged(name, value)}
onBlur={onBlur}
onFocus={onFocus}
registry={registry}
disabled={disabled}
readonly={readonly}
{...extraProps}
/>
);
}
// render nothing, needs to be extended.
render() { return null; }
} |
JavaScript | class RoomsCollection extends Collection {
static instance = new RoomsCollection();
constructor(){
super("rooms","room","/api/rooms/","/api/rooms/save")
}
/**
* get the rooms on the first floor (ground level)
* @param {Function(json)} callBack list of rooms
*/
firstFloor(callBack){
this.floor(0,callBack);
}
/**
* get the rooms in the basement
* @param {Function(json)} callBack list of rooms
*/
basement(callBack){
this.floor(-1,callBack);
}
/**
* get the rooms on a specified floor
* @param {Number} level the floor
* @param {Function(JSON)} callBack list of rooms
*/
floor(level,callBack){
this.getData(json=>{
var rooms = [];
json.rooms.forEach(room=>{
if(Number(room.floor) == level) rooms.push(room);
});
callBack(rooms);
});
}
} |
JavaScript | class Route {
/**
* Constructor for Route class.
* @param {Object} input
* @param {function} input.match The function that determines whether the
* route matches a given `fetch` event.
*
* See [matchCallback]{@link module:workbox-routing.Route~matchCallback} for
* full details on this function.
* @param {function|module:workbox-runtime-caching.Handler} input.handler
* This parameter can be either a function or an object which is a subclass
* of `Handler`.
*
* Either option should result in a `Response` that the `Route` can use to
* handle the `fetch` event.
*
* See [handlerCallback]{@link module:workbox-routing.Route~handlerCallback}
* for full details on using a callback function as the `handler`.
* @param {string} [input.method] Only match requests that use this
* HTTP method.
*
* Defaults to `'GET'`.
*/
constructor({match, handler, method} = {}) {
this.handler = normalizeHandler(handler);
isType({match}, 'function');
this.match = match;
if (method) {
isOneOf({method}, validMethods);
this.method = method;
} else {
this.method = defaultMethod;
}
}
} |
JavaScript | class SpaceService {
/**
* URL to API proxy server
*
* params: none
*
* return: string
* - base url route to proxy server
**/
static get API_BASE_URL() {
return 'https://andrew-wanex.com/mundusvestro_v1.0.0/satellite';
}
/**
* Satellite Situation Center api base url
*
* params: none
*
* return: string
* - base url for Goddard SFR SSCweb api
**/
static get SSCWEB_BASE_URL() {
return 'https://sscweb.gsfc.nasa.gov/WS/sscr/2';
}
/**
* Satellite tracking complete url
*
* params: object
* query - requested query parameters for http request
*
* return: string
* - complete url with requested paramaters
**/
createCompleteSatelliteURL(query) {
let route = '';
const coords = `${query.latitude}/${query.longitude}/${query.altitude}`;
if (query.type == 'positions') {
route = `${query.type}/${query.satId}/${coords}/${query.duration}`;
} else if (query.type == 'visualpasses') {
route = `${query.type}/${query.satId}/${coords}/${query.predictDays}/${query.minVisibility}`;
} else if (query.type == 'above') {
route = `${query.type}/${coords}/${query.searchRadius}/${query.searchCategory}`;
}
return SpaceService.API_BASE_URL + '/' + route;
}
/**
* Fetch satellite data
*
* params: object
* query - query parameters to form url
*
* return: object
* - Promise that resolves with satellite data or rejects with error
**/
fetchSatelliteData(query) {
return fetch(this.createCompleteSatelliteURL(query))
.then(res => {
return res.json()
.then(satData => {
if (satData.info) {
return Promise.resolve(satData);
} else {
return Promise.reject(satData);
}
})
.catch(error => {
console.log('An error occurred parsing satellite data', error);
return Promise.reject(error);
});
})
.catch(error => {
console.log('An error occurred fetching satellite data', error);
return Promise.reject(error);
});
}
/**
* Fetch the past and future track of the ISS for a given timeframe
*
* params: object
* timeframe - contains time interval as ISOstring
*
* return: object
* - Promise that resolves with object containing ISS trajectory
* coordinates and times
**/
fetchISSTrack(timeframe) {
const fetchHeaders = new Headers();
fetchHeaders.append('accept', 'application/json');
fetchHeaders.append('content-type', 'application/json');
const fetchData = {
'BfieldModel': {
'ExternalBFieldModel': [
'gov.nasa.gsfc.sscweb.schema.Tsyganenko89CBFieldModel',
{
'KeyParameterValues': 'KP_3_3_3'
}
],
'InternalBFieldModel': 'IGRF',
'TraceStopAltitude': 100
},
'Description': 'Complex locator request with nearly all options.',
'FormatOptions': null,
'LocationFilterOptions': null,
'OutputOptions': {
'AllLocationFilters': true,
'CoordinateOptions': [
'java.util.ArrayList',
[
{
'Component': 'LAT',
'CoordinateSystem': 'GEO',
'Filter': null
},
{
'Component': 'LON',
'CoordinateSystem': 'GEO',
'Filter': null
}
]
]
},
'Satellites': [
'java.util.ArrayList',
[
{
'Id': 'iss',
'ResolutionFactor': 2
}
]
],
'TimeInterval': {
'End': [
'javax.xml.datatype.XMLGregorianCalendar',
timeframe.end
],
'Start': [
'javax.xml.datatype.XMLGregorianCalendar',
timeframe.start
]
}
};
return fetch(SpaceService.SSCWEB_BASE_URL + '/locations', {
headers: fetchHeaders,
body: JSON.stringify(fetchData),
method: 'POST'
})
.then(res => {
return res.json()
.then(tracking => {
console.log(tracking);
if (tracking.Result.StatusCode == 'SUCCESS') {
return Promise.resolve(tracking);
} else {
return Promise.reject(tracking);
}
})
.catch(error => {
console.log('An error occurred parsing ISS tracking data', error);
return Promise.reject(error);
});
})
.catch(error => {
console.log('An error occurred fetching ISS tracking data', error);
return Promise.reject(error);
});
}
} |
JavaScript | class Outbreak {
/**
* The constructor takes a config object containing a starting seed for the outbreak,
* a probability distribution for infectivity over time, and a distribution from which to draw the
* number of subsequent infections.
*
* @constructor
* @param {object} params - The parameters governing the outbreak.
* These are curried functions that wait for an x value, and are keyed as {infectivityCDF:,R0cdf:}
*/
constructor(params = {}) {
this.epiParams = params;
this.index = {
onset: 0,
level: 0 };
this.caseList = [...this.preorder()];
this.caseList.forEach((n, index) => n.key = Symbol.for(`case ${index}`));
this.caseMap = new Map(this.caseList.map(node => [node.key, node]));
}
/**
* Gets the index case node of the outbreak
*
* @returns {Object|*}
*/
get indexCase() {
return this.index;
}
/**
* Gets the epiparameters used in the outbreak
*
* @returns {Object|*}
*/
get epiParameters() {
return this.epiParams;
}
/**
* Returns a case from its key (a unique Symbol) stored in
* the node as poperty 'key'.
*
* @param key
* @returns {*}
*/
getCase(key) {
return this.caseMap.get(key);
}
/**
* A generator function that returns the nodes in a post-order traversal.
* This is borrowed from figtree.js c- Andrew Rambaut.
* @returns {IterableIterator<IterableIterator<*|*>>}
*/
*postorder() {
const traverse = function* (node) {
if (node.children) {
for (const child of node.children) {
yield* traverse(child);
}
}
yield node;
};
yield* traverse(this.indexCase);
}
/**
* A generator function that returns the nodes in a pre-order traversal
* This is borrowed from figtree.js c- Andrew Rambaut.
* @returns {IterableIterator<IterableIterator<*|*>>}
*/
*preorder() {
const traverse = function* (node) {
yield node;
if (node.children) {
for (const child of node.children) {
yield* traverse(child);
}
}
};
yield* traverse(this.indexCase);
}
get cases() {
return [...this.caseList];
}
/**
* Gets an array containing all the external node objects
* This is borrowed from figtree.js c- Andrew Rambaut.
* @returns {*}
*/
get externalCases() {
return this.cases.filter(node => node.children);
}
/**
* Returns transmitted cases from a donor case
*
* @param donor - the donor case, epiParameters - object keyed with R0 and infectivity
* where each entry is a function which returns a sample from a distribution.
* @returns adds children to donor case if transmission occurs
*/
transmit(donor, epiParameters) {
// How many transmissions with this case have
const numberOftransmissions = epiParameters.R0();
if (numberOftransmissions > 0) {
donor.children = [];
}
for (let i = 0; i < numberOftransmissions; i++) {
const child = {
parent: donor,
level: donor.level + 1,
onset: donor.onset + epiParameters.infectivity() };
donor.children.push(child);
}
}
/**
* A function that calls a transmission call on all nodes until the desired number of levels is added
* to the outbreak. It starts at the most recent level.
* @param levels - the number of levels to add to the growing transmission chain.
*/
spread(levels) {
for (let i = 0; i < levels; i++) {
const maxLevel = this.cases.map(node => node.level).reduce((max, cur) => Math.max(max, cur), -Infinity);
const possibleDonors = this.cases.filter(x => x.level === maxLevel);
for (const donor of possibleDonors) {
this.transmit(donor, this.epiParams);
}
this.caseList = [...this.preorder()];
}
}} |
JavaScript | class Delete extends Action{
/**
* Creates the action
*/
constructor(){
super();
this.createInput('file: filePath', {exists: true});
}
/**
* Implements the execution of the action
*
* @param {Object} data - plain object containing the value of the inputs
* @return {Promise<boolean>} boolean telling if the
* file has been delete
* @protected
*/
async _perform(data){
await unlink(data.file);
return true;
}
} |
JavaScript | class Diet
{
static DLZ0 = 0x307A6C64;
constructor()
{
this.bitCount = 0;
this.controlWord = 0;
this.ptr = 0;
this.view = null;
}
getbit()
{
var result = ( this.controlWord & ( 1 << this.bitCount++ ) );
if ( this.bitCount >= 0x10 )
{
this.controlWord = this.view.getUint16(this.ptr,true);
this.ptr += 2;
this.bitCount = 0;
}
return result ? 1 : 0;
}
decompress( array_buffer, uncompressed_length )
{
this.view = new DataView(array_buffer, 0, array_buffer.byteLength);
this.ptr = 0;
var dst = new Uint8Array(uncompressed_length ? uncompressed_length : array_buffer.byteLength * 20); // hardwired, let's cross fingers
var dstPtr = 0;
this.controlWord = this.view.getUint16(this.ptr,true);
this.ptr += 2;
while ( true )
{
if ( this.getbit() ) // 1
{
// control bit on - copy byte
dst[dstPtr++] = this.view.getUint8(this.ptr++);
continue;
}
var bit = this.getbit(); // 2
var al = this.view.getUint8(this.ptr++);
var spanLo = al;
var spanHi = 0xff;
if ( !bit )
{
if ( !this.getbit() ) // 3
{
if ( spanHi != spanLo )
{
var spanS16 = new Int16Array([( spanHi << 8 ) | spanLo])[0];
for ( var i = 0; i < 2; i++ )
{
dst[ dstPtr ] = dst[ dstPtr++ + spanS16 ];
}
continue;
}
else
{
if ( this.getbit() ) // 4
{
// end of segment/block
continue;
}
else
{
// end of stream
break;
}
}
}
for ( var i = 0; i < 3; i++ )
{
spanHi = ((( spanHi << 1 ) | this.getbit()) >>> 0) & 0xFF; // 5
}
spanHi--;
// do rewind
var spanS16 = new Int16Array([( spanHi << 8 ) | spanLo])[0];
for ( var i = 0; i < 2; i++ )
{
dst[ dstPtr ] = dst[ dstPtr++ + spanS16 ];
}
continue;
}
spanHi = ( spanHi << 1 ) | this.getbit(); // 6
var count = 0;
if ( !this.getbit() ) // 7
{
count = 2;
for ( var i = 0; i < 3; i++ )
{
if ( this.getbit() ) // 8
{
break;
}
spanHi = ((( spanHi << 1 ) | this.getbit()) >>> 0) & 0xFF; // 9
count <<= 1;
}
spanHi -= count;
}
count = 2;
var bail = false;
for ( var j = 0; j < 4; j++ )
{
count++;
if ( this.getbit() ) // 10
{
// do rewind
var spanS16 = new Int16Array([( spanHi << 8 ) | spanLo])[0];
for ( var i = 0; i < count; i++ )
{
dst[ dstPtr ] = dst[ dstPtr++ + spanS16 ];
}
bail = true;
break;
}
}
if ( bail )
{
continue;
}
if ( this.getbit() ) //11
{
count++;
if ( this.getbit() ) // 12
{
count++;
}
// do rewind
var spanS16 = new Int16Array([( spanHi << 8 ) | spanLo])[0];
for ( var i = 0; i < count; i++ )
{
dst[ dstPtr ] = dst[ dstPtr++ + spanS16 ];
}
continue;
}
if ( !this.getbit() ) // 13
{
count = 0;
for ( var j = 0; j < 3; j++ )
{
count = ( count << 1 ) | this.getbit(); // 14
}
count += 9;
// do rewind
var spanS16 = new Int16Array([( spanHi << 8 ) | spanLo])[0];
for ( var i = 0; i < count; i++ )
{
dst[ dstPtr ] = dst[ dstPtr++ + spanS16 ];
}
continue;
}
al = this.view.getUint8(this.ptr++);
// do rewind
var spanS16 = new Int16Array([( spanHi << 8 ) | spanLo])[0];
for ( var i = 0; i < al + 0x11; i++ )
{
dst[ dstPtr ] = dst[ dstPtr++ + spanS16 ];
}
}
return dst.slice(0,dstPtr);
}
} |
JavaScript | class TargetsHTML {
/**
* Class constructor.
* @param {Events} events To reduce the settings and the template of the generated HTML
* files.
* @param {TempFiles} tempFiles To save a generated HTML file on the temp directory.
*/
constructor(events, tempFiles) {
/**
* A local reference for the `events` service.
* @type {Events}
*/
this.events = events;
/**
* A local reference for the `tempFiles` service.
* @type {TempFiles}
*/
this.tempFiles = tempFiles;
/**
* Bind the method so it can be registered as the service itself.
* @ignore
*/
this.getFilepath = this.getFilepath.bind(this);
}
/**
* Validate if a target HTML template exists or not.
* @param {Target} target The target information.
* @return {Object}
* @property {string} path The absolute path to the HTML template.
* @property {boolean} exists Whether or notthe HTML template exists.
*/
validate(target) {
const htmlPath = path.join(target.paths.source, target.html.template);
return {
path: htmlPath,
exists: fs.pathExistsSync(htmlPath),
};
}
/**
* Given a target, this method will validate if the target has an HTML template file and return
* its absolute path; if the file doesn't exists, it will generate a new one, save it on the
* temp directory and return its path.
* @param {Target} target The target information.
* @param {boolean} [force=false] Optional. If this is `true`, the file will be
* created anyways.
* @param {string} [buildType='production'] Optional. If the HTML is for an specific type of
* build. This may be useful for plugins.
* @return {string}
*/
getFilepath(target, force = false, buildType = 'production') {
const validation = this.validate(target);
return validation.exists && !force ? validation.path : this._generateHTML(target, buildType);
}
/**
* This method generates a default HTML file template for a target, saves it on the temp
* directory and returns its path.
* This method emits two reducer events:
* - `target-default-html-settings`: It receives a {@link TargetDefaultHTMLSettings}, the target
* information and it expects another {@link TargetDefaultHTMLSettings} in return.
* - `target-default-html`: It receives the HTML code for the file, the target information and
* it expects a new HTML code in return.
* @param {Target} target The target information.
* @param {string} buildType The type of build for which the HTML is for.
* @return {string}
* @throws {Error} If the file couldn't be saved on the temp directory.
* @ignore
* @access protected
*/
_generateHTML(target, buildType) {
// Reduce the settings for the template.
const info = this.events.reduce(
'target-default-html-settings',
{
title: target.name,
bodyAttributes: '',
bodyContents: '<div id="app"></div>',
},
target,
buildType
);
// Normalize the body attributes to avoid unnecessary spaces on the tag.
const bodyAttrs = info.bodyAttributes ? ` ${info.bodyAttributes}` : '';
// Generate the HTML code.
const htmlTpl = [
'<!doctype html>',
'<html lang="en">',
'<head>',
' <meta charset="utf-8" />',
' <meta http-equiv="x-ua-compatible" content="ie=edge" />',
' <meta name="viewport" content="width=device-width, initial-scale=1" />',
` <title>${info.title}</title>`,
'</head>',
`<body${bodyAttrs}>`,
` ${info.bodyContents}`,
'</body>',
'</html>',
].join('\n');
// Reduce the HTML code.
const html = this.events.reduce('target-default-html', htmlTpl, target);
// Normalize the target name to avoid issues with packages with scope.
const filename = target.name.replace(/\//g, '-');
// Write the file on the temp directory.
return this.tempFiles.writeSync(`${filename}.index.html`, html);
}
} |
JavaScript | class VmlNoteXform extends BaseXform {
get tag() {
return 'v:shape';
}
render(xmlStream, model, index) {
xmlStream.openNode('v:shape', VmlNoteXform.V_SHAPE_ATTRIBUTES(index));
xmlStream.leafNode('v:fill', {color2: 'infoBackground [80]'});
xmlStream.leafNode('v:shadow', {color: 'none [81]', obscured: 't'});
xmlStream.leafNode('v:path', {'o:connecttype': 'none'});
xmlStream.openNode('v:textbox', {style: 'mso-direction-alt:auto'});
xmlStream.leafNode('div', {style: 'text-align:left'});
xmlStream.closeNode();
xmlStream.openNode('x:ClientData', {ObjectType: 'Note'});
xmlStream.leafNode('x:MoveWithCells');
xmlStream.leafNode('x:SizeWithCells');
VmlNoteXform.vmlAnchorXform.render(xmlStream, model);
xmlStream.leafNode('x:AutoFill', null, 'False');
xmlStream.leafNode('x:Row', null, model.refAddress.row - 1);
xmlStream.leafNode('x:Column', null, model.refAddress.col - 1);
xmlStream.closeNode();
xmlStream.closeNode();
}
} |
JavaScript | class NswCallout extends LitElement {
//styles function
static get styles() {
return [
css`
:host {
display: block;
}
:host([hidden]) {
display: none;
}
`,
];
}
// Template return function
render() {
return html` <slot></slot>
<div>${this.title}</div>
<div>${this.content}</div>
<div>${this.link}</div>
<div>${this.text}</div>`;
}
// properties available to the custom element for data binding
static get properties() {
return {
...super.properties,
title: {
name: "title",
type: String,
value: "",
reflectToAttribute: true,
observer: "_titleChanged",
},
content: {
name: "content",
type: String,
value: "",
reflectToAttribute: true,
observer: "_contentChanged",
},
link: {
name: "link",
type: String,
value: "",
reflectToAttribute: true,
observer: "_linkChanged",
},
text: {
name: "text",
type: String,
value: "",
reflectToAttribute: true,
observer: "_textChanged",
},
};
}
/**
* Convention we use
*/
static get tag() {
return "nsw-callout";
}
/**
* HTMLElement
*/
constructor() {
super();
}
/**
* LitElement ready
*/
firstUpdated(changedProperties) {}
/**
* LitElement life cycle - property changed
*/
updated(changedProperties) {
changedProperties.forEach((oldValue, propName) => {
/* notify example
// notify
if (propName == 'format') {
this.dispatchEvent(
new CustomEvent(`${propName}-changed`, {
detail: {
value: this[propName],
}
})
);
}
*/
/* observer example
if (propName == 'activeNode') {
this._activeNodeChanged(this[propName], oldValue);
}
*/
/* computed example
if (['id', 'selected'].includes(propName)) {
this.__selectedChanged(this.selected, this.id);
}
*/
});
}
// Observer title for changes
_titleChanged(newValue, oldValue) {
if (typeof newValue !== typeof undefined) {
console.log(newValue);
}
}
// Observer content for changes
_contentChanged(newValue, oldValue) {
if (typeof newValue !== typeof undefined) {
console.log(newValue);
}
}
// Observer link for changes
_linkChanged(newValue, oldValue) {
if (typeof newValue !== typeof undefined) {
console.log(newValue);
}
}
// Observer text for changes
_textChanged(newValue, oldValue) {
if (typeof newValue !== typeof undefined) {
console.log(newValue);
}
}
} |
JavaScript | class RemoteService {
constructor(options) {
// This flag indicates to the plugin this is a remote service
this.remote = true;
}
setup(app, path) {
// Create the request manager to remote ones for this service
this.requester = new app.cote.Requester({
name: path + ' requester',
namespace: path,
requests: ['find', 'get', 'create', 'update', 'patch', 'remove']
}, Object.assign({ log: false }, app.coteOptions));
this.path = path;
debug('Requester created for remote service on path ' + this.path);
// Create the subscriber to listen to events from other nodes
this.serviceEventsSubscriber = new app.cote.Subscriber({
name: path + ' events subscriber',
namespace: path,
subscribesTo: ['created', 'updated', 'patched', 'removed']
}, { log: false });
this.serviceEventsSubscriber.on('created', object => {
this.emit('created', object);
});
this.serviceEventsSubscriber.on('updated', object => {
this.emit('updated', object);
});
this.serviceEventsSubscriber.on('patched', object => {
this.emit('patched', object);
});
this.serviceEventsSubscriber.on('removed', object => {
this.emit('removed', object);
});
debug('Subscriber created for remote service events on path ' + this.path);
}
// Perform requests to other nodes
find(params) {
debug('Requesting find() remote service on path ' + this.path, params);
return this.requester.send({ type: 'find', params }).then(result => {
debug('Successfully find() remote service on path ' + this.path);
return result;
});
}
get(id, params) {
debug('Requesting get() remote service on path ' + this.path, id, params);
return this.requester.send({ type: 'get', id, params }).then(result => {
debug('Successfully get() remote service on path ' + this.path);
return result;
});
}
create(data, params) {
debug('Requesting create() remote service on path ' + this.path, data, params);
return this.requester.send({ type: 'create', data, params }).then(result => {
debug('Successfully create() remote service on path ' + this.path);
return result;
});
}
update(id, data, params) {
debug('Requesting update() remote service on path ' + this.path, id, data, params);
return this.requester.send({ type: 'update', id, data, params }).then(result => {
debug('Successfully update() remote service on path ' + this.path);
return result;
});
}
patch(id, data, params) {
debug('Requesting patch() remote service on path ' + this.path, id, data, params);
return this.requester.send({ type: 'patch', id, data, params }).then(result => {
debug('Successfully patch() remote service on path ' + this.path);
return result;
});
}
remove(id, params) {
debug('Requesting remove() remote service on path ' + this.path, id, params);
return this.requester.send({ type: 'remove', id, params }).then(result => {
debug('Successfully remove() remote service on path ' + this.path);
return result;
});
}
} |
JavaScript | class LocalService extends _cote2.default.Responder {
constructor(options) {
const app = options.app;
const path = options.path;
super({ name: path + ' responder', namespace: path, respondsTo: ['find', 'get', 'create', 'update', 'patch', 'remove'] }, { log: false });
debug('Responder created for local service on path ' + path);
let service = app.service(path);
// Answer requests from other nodes
this.on('find', req => {
debug('Responding find() local service on path ' + path);
return service.find(req.params).then(result => {
debug('Successfully find() local service on path ' + path);
return result;
});
});
this.on('get', req => {
debug('Responding get() local service on path ' + path);
return service.get(req.id, req.params).then(result => {
debug('Successfully get() local service on path ' + path);
return result;
});
});
this.on('create', req => {
debug('Responding create() local service on path ' + path);
return service.create(req.data, req.params).then(result => {
debug('Successfully create() local service on path ' + path);
return result;
});
});
this.on('update', req => {
debug('Responding update() local service on path ' + path);
return service.update(req.id, req.data, req.params).then(result => {
debug('Successfully update() local service on path ' + path);
return result;
});
});
this.on('patch', req => {
debug('Responding patch() local service on path ' + path);
return service.patch(req.id, req.data, req.params).then(result => {
debug('Successfully patch() local service on path ' + path);
return result;
});
});
this.on('remove', req => {
debug('Responding remove() local service on path ' + path);
return service.remove(req.id, req.params).then(result => {
debug('Successfully remove() local service on path ' + path);
return result;
});
});
// Dispatch events to other nodes
this.serviceEventsPublisher = new app.cote.Publisher({
name: path + ' events publisher',
namespace: path,
broadcasts: ['created', 'updated', 'patched', 'removed']
}, Object.assign({ log: false }, app.coteOptions));
service.on('created', object => {
this.serviceEventsPublisher.publish('created', object);
});
service.on('updated', object => {
this.serviceEventsPublisher.publish('updated', object);
});
service.on('patched', object => {
this.serviceEventsPublisher.publish('patched', object);
});
service.on('removed', object => {
this.serviceEventsPublisher.publish('removed', object);
});
debug('Publisher created for local service events on path ' + path);
}
} |
JavaScript | class NavigationTabs extends React.Component {
componentDidUpdate (prevProps, prevState, snapshot) {
const { activeTabType } = this.props;
if (activeTabType !== prevProps.activeTabType) {
if (this.props.onActiveTabUpdated) {
this.props.onActiveTabUpdated();
}
}
}
handleChangeTab = (event, value) => {
if (this.props.onChangeActiveTab) {
this.props.onChangeActiveTab(value);
}
};
render() {
const { activeTabType, tabs } = this.props;
const tabsContent = [];
for (let i = 0; i < tabs.length; i++){
tabsContent.push(
<Tab key={`tabItem${i}`} label={tabs[i].tabLabel} value={tabs[i].tabType} />
);
}
return (
<Tabs
value={activeTabType}
onChange={this.handleChangeTab}
indicatorColor="primary"
textColor="primary"
centered
>
{tabsContent}
</Tabs>
);
}
} |
JavaScript | class ArDriveCommunityOracle {
constructor(arweave, contractReaders) {
this.arweave = arweave;
this.defaultContractReaders = [
new verto_contract_oracle_1.VertoContractReader(),
new smartweave_contract_oracle_1.SmartweaveContractReader(this.arweave)
];
this.contractOracle = new ardrive_contract_oracle_1.ArDriveContractOracle(contractReaders ? contractReaders : this.defaultContractReaders);
}
/**
* Given a Winston data cost, returns a calculated ArDrive community tip amount in Winston
*
* TODO: Use big int library on Winston types
*/
getCommunityWinstonTip(winstonCost) {
return __awaiter(this, void 0, void 0, function* () {
const communityTipPercentage = yield this.contractOracle.getTipPercentageFromContract();
const arDriveCommunityTip = winstonCost.times(communityTipPercentage);
return types_1.Winston.max(arDriveCommunityTip, exports.minArDriveCommunityWinstonTip);
});
}
/**
* Gets a random ArDrive token holder based off their weight (amount of tokens they hold)
*
* TODO: This is mostly copy-paste from core -- refactor into a more testable state
*/
selectTokenHolder() {
return __awaiter(this, void 0, void 0, function* () {
// Read the ArDrive Smart Contract to get the latest state
const contract = yield this.contractOracle.getCommunityContract();
const balances = contract.balances;
const vault = contract.vault;
// Get the total number of token holders
let total = 0;
for (const addr of Object.keys(balances)) {
total += balances[addr];
}
// Check for how many tokens the user has staked/vaulted
for (const addr of Object.keys(vault)) {
if (!vault[addr].length)
continue;
const vaultBalance = vault[addr]
.map((a) => a.balance)
.reduce((a, b) => a + b, 0);
total += vaultBalance;
if (addr in balances) {
balances[addr] += vaultBalance;
}
else {
balances[addr] = vaultBalance;
}
}
// Create a weighted list of token holders
const weighted = {};
for (const addr of Object.keys(balances)) {
weighted[addr] = balances[addr] / total;
}
// Get a random holder based off of the weighted list of holders
const randomHolder = common_1.weightedRandom(weighted);
if (randomHolder === undefined) {
throw new Error('Token holder target could not be determined for community tip distribution..');
}
return types_1.ADDR(randomHolder);
});
}
} |
JavaScript | class Camera {
constructor(focus, zoom, rotation) {
this.focus = focus? Vec2.from(focus) : new Vec2;
this._target = null;
this.zoom = zoom !== undefined? zoom : 1;
this.view = 1;
this._za = null;
this.rotation = rotation || 0;
}
copy(includeAnimState) {
var copy = new Camera(this.focus, this.zoom, this.rotation);
copy.view = this.view;
if (includeAnimState) {
copy._target = this._target;
copy._za = this._za;
}
return copy;
}
get scale() {
return this.view * this.zoom;
}
follow(target) {
this._target = target;
}
animZoom(target, time, force) {
if (!this._za || force) this._za = {target: target, time: time};
}
update(dt) {
// TODO: chase the target rather than being locked on.
// Or at least have that be an option
if (this._target) this.focus.set(...this._target.pos);
// TODO: rotate, focus transitions (focus should unset target)
if (this._za) {
if (dt >= this._za.time) {
this.zoom = this._za.target;
this._za = null;
} else {
this.zoom *= Math.pow(
this._za.target / this.zoom,
dt / this._za.time
);
this._za.time -= dt;
}
}
}
applyTransform(ctx) {
this.update(0); // Apply instantaneous transitions
ctx.scale(this.scale, this.scale);
ctx.rotate(this.rotation);
ctx.translate(-this.focus.x, -this.focus.y);
}
getTransform() {
this.update(0); // Apply instantaneous transitions
var trf = new Transform();
trf.scale(this.scale, this.scale);
trf.rotate(this.rotation);
trf.translate(-this.focus.x, -this.focus.y);
return trf;
}
} |
JavaScript | class Popup {
constructor(options) {
this.id = uniqueId("popup-");
this.node = null;
this.options = options;
this.ANIMATION_DURATION = 500;
this.onCreated = () => {};
if (isFunction(options.onCreated)) {
this.onCreated = options.onCreated;
}
}
getHTML() {
return `
<div class="popup">
<div class="popup-content">${this.options.html}</div>
</div>
`;
}
render() {
const popupEl = document.createElement("div");
popupEl.style.setProperty(
"--transition-duration",
`${this.ANIMATION_DURATION / 1000}s`
);
popupEl.className = "popup-wrapper";
popupEl.id = this.id;
popupEl.innerHTML = this.getHTML();
document.body.appendChild(popupEl);
this.node = document.getElementById(popupEl.id);
setTimeout(() => this.node.classList.add("show"));
this.addListeners();
this.onCreated();
return this;
}
addListeners() {
this.addButtonListeners();
this.addCloseListener();
this.addHideListener();
}
getSelector(selector) {
return `#${this.id} ${selector}`;
}
addButtonListeners() {
const listeners = this.options.listeners || {};
Object.entries(listeners).forEach((listenerData) => {
const [id, listener] = listenerData;
const el = document.querySelector(this.getSelector(`#${id}`));
if (!el) {
console.error(`Element with id: "${id} not found"`);
return;
}
el.addEventListener("click", listener);
});
}
addHideListener() {
const hideBtn = document.querySelector(this.getSelector("[data-hide-btn]"));
if (!hideBtn) {
return;
}
hideBtn.addEventListener("click", this.hide.bind(this));
}
addCloseListener() {
const closeBtn = document.querySelector(
this.getSelector("[data-close-btn]")
);
if (!closeBtn) {
return;
}
closeBtn.addEventListener("click", this.close.bind(this));
}
show() {
this.node.classList.add("show");
return this;
}
hide() {
this.node.classList.remove("show");
return this;
}
close() {
this.node.classList.remove("show");
setTimeout(() => this.node.remove(), this.ANIMATION_DURATION);
return this;
}
} |
JavaScript | class AboutMe extends Component {
static navigationOptions = {
title: 'About Me',
headerStyle:{
backgroundColor: 'rgba(245,128,51,0.6)',
},
headerTitleStyle: {
color: 'white',
},
headerBackTitleStyle: {
color: 'black',
},
// headerTintColor: 'rgba(245,128,51,0.6)',
// header: null,
};
render() {
return (
<View style={styles.container}>
<Text>About Me</Text>
</View>
);
}
} |
JavaScript | class UploadableTestCase {
/**
* @param {!UploadableFile} htmlFile
* @param {boolean} isRunnable
*/
constructor({
htmlFile,
isRunnable,
}) {
/** @type {!UploadableFile} */
this.htmlFile = htmlFile;
/** @type {boolean} */
this.isRunnable = isRunnable;
/** @type {!Array<!UploadableFile>} */
this.screenshotImageFiles = [];
}
} |
JavaScript | class UploadableFile {
constructor({
destinationBaseUrl,
destinationParentDirectory,
destinationRelativeFilePath,
queueIndex = null,
queueLength = null,
fileContent = null,
userAgent = null,
}) {
/** @type {string} */
this.destinationParentDirectory = destinationParentDirectory;
/** @type {string} */
this.destinationRelativeFilePath = destinationRelativeFilePath;
/** @type {string} */
this.destinationAbsoluteFilePath = `${this.destinationParentDirectory}/${this.destinationRelativeFilePath}`;
/** @type {string} */
this.publicUrl = `${destinationBaseUrl}${this.destinationAbsoluteFilePath}`;
/** @type {?Buffer|?string} */
this.fileContent = fileContent;
/** @type {?CbtUserAgent} */
this.userAgent = userAgent;
/** @type {number} */
this.queueIndex = queueIndex;
/** @type {number} */
this.queueLength = queueLength;
}
} |
JavaScript | class Shape {
constructor(x, y, radius, ax, ay, m, vx = 0, vy = 0) {
this.x = x;
this.y = y;
this.r = radius;
this.ax = ax;
this.ay = ay;
this.m = m;
this.vx = vx;
this.vy = vy;
this.fx = 0;
this.fy = 0;
}
move(dt) { //dt = time deltas
this.vx += this.ax * dt;
this.vy += this.ay * dt;
if (this.vx > maxSpeed) {
this.vx = maxSpeed
}
if (this.vx < -maxSpeed) {
this.vx = -maxSpeed
}
if (this.vy > maxSpeed) {
this.vy = maxSpeed
}
if (this.vy < -maxSpeed) {
this.vy = -maxSpeed
}
this.x += this.vx * dt;
this.y += this.vy * dt;
}
draw() {
//draw a circle
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, true);
ctx.closePath();
}
drawPath() {
ctx.strokeStyle = 'yellow';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(20, lightYstart);
prevX.push(this.x);
prevY.push(this.y);
tempx.concat(prevX);
tempy.concat(prevY);
/**for (let i = 0; i < round; i++) {
xg=tempx.pop();
yg=tempy.pop();
ctx.lineTo(Math.abs(xg), Math.abs(yg));
}**/
/** for(let i of prevY){
t = tempx.toLocaleString();
ctx.lineTo(Math.abs(t), Math.abs(i))
}**/
if (this.x < j - r / 2) {
if (Math.sqrt((this.x - j) ** 2 + (this.y - w) ** 2) > r) {
if (Math.sqrt((this.x - j) ** 2 + (this.y - w) ** 2) > r) {
if (this.x < h + r) {
prevx = this.x;
prevy = this.y;
}
}
}
}
ctx.lineTo(Math.abs(prevx), Math.abs(prevy))
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = 'cyan';
ctx.lineWidth = 5;
ctx.setLineDash([5, 15]);
if (this.x > h) {
if (Math.sqrt((this.x - j) ** 2 + (this.y - w) ** 2) > r) {
if (this.x < j) {
lightSlope = (this.y - (lightYstart)) / (this.x - 20);
x1 = (-(-2 * h + 2 * lightSlope * lightYstart) - Math.sqrt((-2 * h + 2 * lightSlope * lightYstart - 2 * lightSlope * w) ** 2 - 4 * (1 + lightSlope ** 2) * (h ** 2 + lightYstart ** 2 + w ** 2 - 2 * lightYstart * w - r ** 2))) / (2 * (1 + lightSlope ** 2));
y1 = lightSlope * (-(-2 * h + 2 * lightSlope * lightYstart) - Math.sqrt((-2 * h + 2 * lightSlope * lightYstart - 2 * lightSlope * w) ** 2 - 4 * (1 + lightSlope ** 2) * (h ** 2 + lightYstart ** 2 + w ** 2 - 2 * lightYstart * w - r ** 2))) / (2 * (1 + lightSlope ** 2)) + lightYstart;
}
}
ctx.moveTo(prevx - (-2 * (x1 - j)) / (2 * Math.PI), prevy + (2 * (y1 - w)) / (2 * Math.PI));
ctx.lineTo(prevx + (-2 * (x1 - j)) / (2 * Math.PI), prevy - (2 * (y1 - w)) / (2 * Math.PI));
}
ctx.stroke();
ctx.setLineDash([]);
ctx.lineWidth = 2;
ctx.strokeStyle = 'red';
ctx.beginPath();
ctx.moveTo(Math.abs(prevx), Math.abs(prevy))
if (this.x < j) {
if (Math.sqrt((this.x - h) ** 2 + (this.y - w) ** 2) < r) {
if (Math.sqrt((this.x - h) ** 2 + (this.y - w) ** 2) < r) {
if (this.x < j) {
prevx2 = this.x;
prevy2 = this.y;
}
}
document.getElementById("demo").innerHTML = 'θ1 of 1: ' + (Math.round(Math.atan2(prevy2 - prevy, prevx2 - prevx) * 180 / Math.PI * 1000) / 1000);
}
}
ctx.lineTo(prevx2, prevy2);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.strokeStyle = 'cyan';
ctx.lineWidth = 5;
ctx.setLineDash([5, 15]);
if (this.x < j) {
if (Math.sqrt((this.x - h) ** 2 + (this.y - w) ** 2) < r) {
if (this.x < j) {
lightSlope2 = (this.y - (prevy)) / (this.x - prevx);
lightYstart2 = prevy;
x2 = (-(-2 * j + 2 * lightSlope2 * lightYstart2) - Math.sqrt((-2 * j + 2 * lightSlope2 * lightYstart2 - 2 * lightSlope2 * w) ** 2 - 4 * (1 + lightSlope2 ** 2) * (j ** 2 + lightYstart2 ** 2 + w ** 2 - 2 * lightYstart2 * w - r ** 2))) / (2 * (1 + lightSlope2 ** 2));
y2 = lightSlope2 * (-(-2 * j + 2 * lightSlope2 * lightYstart2) - Math.sqrt((-2 * j + 2 * lightSlope2 * lightYstart2 - 2 * lightSlope2 * w) ** 2 - 4 * (1 + lightSlope2 ** 2) * (j ** 2 + lightYstart2 ** 2 + w ** 2 - 2 * lightYstart2 * w - r ** 2))) / (2 * (1 + lightSlope2 ** 2)) + lightYstart2;
}
}
}
ctx.moveTo(prevx2 - (-2 * (x2 - j)) / (2 * Math.PI), prevy2 - (2 * (y2 - w)) / (2 * Math.PI));
ctx.lineTo(prevx2 + (-2 * (x2 - j)) / (2 * Math.PI), prevy2 + (2 * (y2 - w)) / (2 * Math.PI));
ctx.stroke();
ctx.setLineDash([]);
ctx.strokeStyle = 'yellow';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(prevx2, prevy2)
if (this.x > 800) {
if (this.x < c.width) {
prevx3 = this.x;
prevy3 = this.y;
}
ctx.lineTo(prevx3, prevy3);
document.getElementById("demo2").innerHTML = 'θ2 of 1: ' + Math.round(Math.atan2(prevy3 - prevy2, prevx3 - prevx2) * 180 / Math.PI * 1000) / 1000;
ctx.stroke();
ctx.closePath();
}
if (this.x > c.width - 50) {
this.vx = 0;
this.vy = 0;
this.ax = 0;
this.ay = 0;
}
}
drawPath2() {
ctx.strokeStyle = 'yellow';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(20, lightYstartt);
prevX.push(this.x);
prevY.push(this.y);
tempxx.concat(prevXX);
tempyy.concat(prevYY);
/**for (let i = 0; i < round; i++) {
xg=tempx.pop();
yg=tempy.pop();
ctx.lineTo(Math.abs(xg), Math.abs(yg));
}**/
/** for(let i of prevY){
t = tempx.toLocaleString();
ctx.lineTo(Math.abs(t), Math.abs(i))
}**/
if (this.x < j - r / 2) {
if (Math.sqrt((this.x - j) ** 2 + (this.y - w) ** 2) > r) {
if (Math.sqrt((this.x - j) ** 2 + (this.y - w) ** 2) > r) {
if (this.x < h + r) {
prevxx = this.x;
prevyy = this.y;
}
}
}
}
ctx.lineTo(Math.abs(prevxx), Math.abs(prevyy))
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = 'cyan';
ctx.lineWidth = 5;
ctx.setLineDash([5, 15]);
if (this.x > h) {
if (Math.sqrt((this.x - j) ** 2 + (this.y - w) ** 2) > r) {
if (this.x < h + r) {
lightSlopee = (this.y - (lightYstartt)) / (this.x - 20);
x11 = (-(-2 * j + 2 * lightSlopee * lightYstartt) - Math.sqrt((-2 * j + 2 * lightSlopee * lightYstartt - 2 * lightSlopee * w) ** 2 - 4 * (1 + lightSlopee ** 2) * (j ** 2 + lightYstartt ** 2 + w ** 2 - 2 * lightYstartt * w - r ** 2))) / (2 * (1 + lightSlopee ** 2));
y11 = lightSlopee * (-(-2 * j + 2 * lightSlopee * lightYstartt) - Math.sqrt((-2 * j + 2 * lightSlopee * lightYstartt - 2 * lightSlopee * w) ** 2 - 4 * (1 + lightSlopee ** 2) * (j ** 2 + lightYstartt ** 2 + w ** 2 - 2 * lightYstartt * w - r ** 2))) / (2 * (1 + lightSlopee ** 2)) + lightYstartt;
}
}
ctx.moveTo(prevxx - (-2 * (x11 - j)) / (2 * Math.PI), prevyy + (2 * (y11 - w)) / (2 * Math.PI));
ctx.lineTo(prevxx + (-2 * (x11 - j)) / (2 * Math.PI), prevyy - (2 * (y11 - w)) / (2 * Math.PI));
}
ctx.stroke();
ctx.setLineDash([]);
ctx.lineWidth = 2;
ctx.strokeStyle = 'red';
ctx.beginPath();
ctx.moveTo(Math.abs(prevxx), Math.abs(prevyy));
if (this.x < j) {
if (Math.sqrt((this.x - h) ** 2 + (this.y - w) ** 2) < r) {
if (Math.sqrt((this.x - h) ** 2 + (this.y - w) ** 2) < r) {
if (this.x < j) {
prevx22 = this.x;
prevy22 = this.y;
}
}
document.getElementById("demoo").innerHTML = 'θ1 of 2: ' + Math.round(Math.atan2(prevy22 - prevyy, prevx22 - prevxx) * 180 / Math.PI * 1000) / 1000;
}
}
ctx.lineTo(prevx22, prevy22);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.strokeStyle = 'cyan';
ctx.lineWidth = 5;
ctx.setLineDash([5, 15]);
if (this.x < j) {
if (Math.sqrt((this.x - h) ** 2 + (this.y - w) ** 2) < r) {
if (this.x < j) {
lightSlope22 = (this.y - (prevyy)) / (this.x - prevxx);
lightYstart22 = prevyy;
x22 = (-(-2 * h + 2 * lightSlope22 * lightYstart22) - Math.sqrt((-2 * h + 2 * lightSlope22 * lightYstart22 - 2 * lightSlope22 * w) ** 2 - 4 * (1 + lightSlope22 ** 2) * (h ** 2 + lightYstart22 ** 2 + w ** 2 - 2 * lightYstart22 * w - r ** 2))) / (2 * (1 + lightSlope22 ** 2));
y22 = lightSlope22 * (-(-2 * h + 2 * lightSlope22 * lightYstart22) - Math.sqrt((-2 * h + 2 * lightSlope22 * lightYstart22 - 2 * lightSlope22 * w) ** 2 - 4 * (1 + lightSlope22 ** 2) * (h ** 2 + lightYstart22 ** 2 + w ** 2 - 2 * lightYstart22 * w - r ** 2))) / (2 * (1 + lightSlope22 ** 2)) + lightYstart22;
}
}
}
ctx.moveTo(prevx22 - (-2 * (x22 - h)) / (2 * Math.PI), prevy22 + (2 * (y2 - w)) / (2 * Math.PI));
ctx.lineTo(prevx22 + (-2 * (x22 - h)) / (2 * Math.PI), prevy22 - (2 * (y2 - w)) / (2 * Math.PI));
ctx.stroke();
ctx.setLineDash([]);
ctx.strokeStyle = 'yellow';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(prevx22, prevy22)
if (this.x > 800) {
if (this.x < c.width) {
prevx33 = this.x;
prevy33 = this.y;
}
ctx.lineTo(prevx33, prevy33);
document.getElementById("demo22").innerHTML = 'θ2 of 2: ' + Math.round(Math.atan2(prevy33 - prevy22, prevx33 - prevx22) * 180 / Math.PI * 1000) / 1000;
ctx.stroke();
ctx.closePath();
}
if (this.x > c.width - 50) {
this.vx = 0;
this.vy = 0;
this.ax = 0;
this.ay = 0;
}
}
resolveEdgeCollision() {
// Detect collision with right wall.
if (this.x + this.r > c.width - 750) {
// Need to know how much we overshot the canvas width so we know how far to 'bounce'.
this.x = c.width - 750 - this.r;
this.vx = -this.vx;
this.ax = -this.ax;
}
// Detect collision with bottom wall.
else if (this.y + this.r > c.height - 200) {
this.y = c.height - 200 - this.r;
this.vy = -this.vy;
this.ay = -this.ay;
}
// Detect collision with left wall.
else if (this.x - this.r < 500) {
this.x = this.r + 500;
this.vx = -this.vx;
this.ax = -this.ax;
}
// Detect collision with top wall.
else if (this.y - this.r < 300) {
this.y = this.r + 300;
this.vy = -this.vy;
this.ay = -this.ay;
}
}
resolveRoundEdgeCollision() {
ctx.strokeStyle = 'white';
ctx.beginPath();
//ctx.arc(h, w, r, 1.46 * Math.PI + calcAngle(xpos, itwo), 0.725 * Math.PI - calcAngle(xpos, ione), 0);
ctx.arc(h, w, r, calcAngle(xpos - h, itwo - w), calcAngle(xpos - h, ione - w), 1);
//opp/adj
//context.arc(x,y,r,sAngle,eAngle,counterclockwise);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
//ctx.arc(j, w, r, 1.165 * Math.PI - calcAngle(xpos, ione), 1.02 * Math.PI + calcAngle(xpos, itwo), 0);
ctx.arc(j, w, r, Math.PI - calcAngle(xpos - h, itwo - w), Math.PI - calcAngle(xpos - h, ione - w), 0);
ctx.stroke();
ctx.closePath();
// Detect collision with right wall.
ctx.beginPath();
ctx.moveTo(xpos, ione);
ctx.lineTo(xpos, itwo);
ctx.stroke();
ctx.closePath();
// Detect collision with left wall.
if (Math.sqrt((this.x - j) ** 2 + (this.y - w) ** 2) > r) {
this.x = this.x + this.r;
this.vx = -this.vx;
this.ax = -this.ax;
}
// Detect collision with right wall.
if (Math.sqrt((this.x - h) ** 2 + (this.y - w) ** 2) > r) {
this.x = this.x - this.r;
this.vx = -this.vx;
this.ax = -this.ax;
}
// Detect collision with bottom wall.
else if (this.y - this.r < ione) {
this.y = this.y - this.r + 40;
this.vy = -this.vy;
this.ay = -this.ay;
}
// Detect collision with top wall.
else if (this.y - this.r > itwo) {
this.y = this.r + this.y - 40;
this.vy = -this.vy;
this.ay = -this.ay;
}
}
resolveMedium2Collision() {
// Detect collision with left wall.
if (Math.sqrt((this.x - h) ** 2 + (this.y - w) ** 2) < r) {
this.x = this.x + 4 * this.r;
this.vx = -this.vx;
this.ax = -this.ax;
}
// Detect collision with right wall.
if (this.x + this.r > c.width - 50) {
// Need to know how much we overshot the canvas width so we know how far to 'bounce'.
this.x = c.width - 4 * this.r;
this.vx = -this.vx;
this.ax = -this.ax;
}
// Detect collision with bottom wall.
else if (this.y + this.r > c.height - 200) {
this.y = c.height - 200 - this.r;
this.vy = -this.vy;
this.ay = -this.ay;
}
// Detect collision with top wall.
else if (this.y - this.r < 300) {
this.y = this.r + 300;
this.vy = -this.vy;
this.ay = -this.ay;
}
}
} |
JavaScript | class Collision {
constructor(o1, o2, dx, dy, d) {
this.o1 = o1;
this.o2 = o2;
this.dx = dx;
this.dy = dy;
this.d = d;
}
} |
JavaScript | class VBoxEnvironment extends Environment {
/**
* Adds additional fields to Aragonite options and calls {@link Plugin#constructor}.
* @param {AragoniteVBoxPlugin} vbox the plugin that created this instance.
* @param {Aragonite} server the parent Aragonite server.
* @param {Object} opts the Aragonite options. See {@link AragoniteVBoxPlugin#constructor} for added properties.
* @param {Object} conf standard options passed to runners. See {@link Aragonite#run}.
* @param {Object} machine the machine templates that can be used to test projects
* @param {string} machine.name a human-readable description of the machine.
* @param {string} machine.vbox the VirtualBox identifier of the machine.
* @param {string} machine.snap a VirtualBox snapshot of the given machine to clone
* @param {string} machine.dist the platform the machine is running, e.g. "OSX", "Windows", "Linux"
* @param {string} machine.version the OS version, e.g. Ubuntu: "14.04", Windows: "XP", OSX: "10.11"
* @param {boolean} machine.async if `true`, other environments can run at the same time.
* @param {number} machine.cost the relative cost to run the machine, to prevent over-usage.
*/
constructor(vbox, server, opts, conf, machine) {
let env = {
async: machine.async && opts.totalCost >= machine.cost,
cost: machine.cost && machine.cost <= opts.totalCost ? machine.cost : 0
};
super(env);
this.vbox = vbox;
this.server = server;
this.opts = opts;
this.conf = conf;
this.machine = machine;
}
/**
* Provides the information to distingiush this environment from others.
* @return {Object} {@see Aragonite#report}
*/
get identifier() {
let ident = {};
ident.runner = "aragonite-vbox";
ident.os = this.machine.dist;
ident.version = this.machine.version;
ident.extra = {
vbox: this.machine.vbox
};
return ident;
}
/**
* Run this environment.
* @return {Promise} resolves once the test has finished and reported its data.
*/
run() {
let instance = null;
let error = null;
return this
.provision()
.then((i) => {
instance = i;
this.vbox.runs[instance.mac] = {conf: this.conf};
this.namespace = this.vbox.io.of("/"+instance.mac);
this.finished = new Promise((resolve, reject) => {
this.namespace.on("connection", (socket) => {
this.vbox.sockets.push(socket);
socket.emit("machine", this.machine);
socket.emit("conf", this.conf);
socket.on("done", function() { resolve(); });
socket.on("report", (report) => {
this.server.report.report(this.conf, this.identifier, report);
});
});
});
return this.start(instance.name);
})
.catch((err) => {
error = error;
this.success = false;
return true;
})
.then(() => {
if(instance) {
return this.cleanup(instance.name);
}
})
.then(() => {
if(error) {
return this.server.report.error(this.conf, this.identifier, error);
}
return this.server.report.finished(this.conf, this.identifier);
})
.catch((err) => {
console.error(err);
throw err;
});
}
/**
* Clone the specfied VirtualBox image.
* @return {Promise<Object>} resolves `{name, mac}` once the machine is cloned.
*/
provision() {
let name = this.opts.vbox.prefix + this.machine.vbox + "-" + shortid.generate();
let opts = ["clonevm", this.machine.vbox, "--mode", "machine", "--register", "--name", name];
if(this.machine.snap) {
opts = opts.concat("--snapshot", this.machine.snap);
}
return spawnAsync(this.opts.vbox.exec, opts)
.then(() => {
return spawnAsync(this.opts.vbox.exec, ["showvminfo", "--machinereadable", name], {capture: ['stdout']});
})
.then((res) => {
let mac = res.stdout.toString().match(/macaddress1="([^"]+)"/)[1];
return {name: name, mac: mac};
});
}
/**
* Start the specified VirtualBox instance, and listen to responses.
* @param {string} instance the name of the VirtualBox machine to start.
* @return {Promise} resolves once the machine has run all commands, and is ready to be shut down.
*/
start(instance) {
return startup = spawnAsync(this.opts.vbox.exec, ["startvm", instance, "--type", "headless"])
.then(() => {
return this.server.report.start(this.conf, this.identifier);
})
.then(() => {
return this.finished;
});
}
/**
* Stop the specified VirtualBox instance, and delete the machine.
* @param {string} instance the name of the VirtualBox machine to stop.
* @return {Promise} resolves once the machine has been deleted.
*/
cleanup(instance) {
return spawnAsync(this.opts.vbox.exec, ["controlvm", instance, "poweroff"])
.then(() => {
return spawnAsync(this.opts.vbox.exec, ["unregistervm", instance, "--delete"]);
});
}
} |
JavaScript | class Header extends React.Component {
render() {
return <h1>Welcome to React</h1>;
}
} |
JavaScript | class Accordion_object extends Wrapper{
constructor(selector) {
super(selector);
this.selector = selector;
}
/**
* expanding section.
* function will expand section by clicking on accordion icon.
* @function
*/
expand() {
console.log(`>>> Trying to expand section`);
let accordionIcon = $(this.selector).$('i').getAttribute('class');
console.log(accordionIcon);
if (accordionIcon.includes(accordionExpandedState)) {
console.log('>>> Section was already expanded');
return
}
let i = retryCount;
while (accordionIcon.includes(accordionCollapsedState) && (i > 0)){
console.log('>>> clicking to expand')
$(this.selector).click();
i-- ;
browser.pause(1000);
accordionIcon = $(this.selector).$('i').getAttribute('class');
}
if (accordionIcon.includes(accordionCollapsedState)) {
throw '>>> Was not able to expand section'
}
}
/**
* collapsing seciton.
* function will collaps section by clicking on accordion icon
* @function
*/
collapse() {
console.log(`>>> Trying to collapse section`);
let accordionIcon = $(this.selector).$('i').getAttribute('class');
console.log(accordionIcon);
if (accordionIcon.includes(accordionCollapsedState)) {
console.log('>>> Section was already collapsed');
return
}
let i = retryCount;
while (accordionIcon.includes(accordionExpandedState) && (i > 0)){
console.log('>>> clicking to collapse')
$(this.selector).click();
i--;
browser.pause(1000);
accordionIcon = $(this.selector).$('i').getAttribute('class');
}
if (accordionIcon.includes(accordionExpandedState)) {
throw '>>> Was not able to collapse section'
}
}
} |
JavaScript | class RouteBuilder{
route;
routeStack = [];
constructor(route){
this.route = route;
}
static createNewRoute = () => new RouteBuilder(express.Router());
static loadRoute = (route) => new RouteBuilder(route);
from = (routeEndPt) => {
routeEndPt = this.formatEndpoint(routeEndPt);
this.routeStack.push(routeEndPt);
return this;
}
stepBack = () => {
this.routeStack.pop();
return this;
}
stepToRoot = () => {
this.routeStack = [];
return this;
}
get = (endPoint, ...args) => {
this.route.get(this.createRouteString(endPoint), ...args);
return this;
}
post = (endPoint, ...args) => {
this.route.post(this.createRouteString(endPoint), ...args);
return this;
}
all = (endPoint, ...args) => {
this.route.all(this.createRouteString(endPoint), ...args);
return this;
}
getRoute = () => this.route;
createRouteString = (endPt) => this.routeStack.join('') + this.formatEndpoint(endPt);
formatEndpoint = (endPt) => {
endPt = endPt[0] === "/" ? endPt : `/${endPt}`;
return endPt;
}
} |
JavaScript | class JWTAuthenticator extends carbon.carbond.security.Authenticator {
constructor() {
super()
/*************************************************************************
* secret
*/
this.secret = null
}
/***************************************************************************
* authenticate
*/
authenticate(req) {
// Check the Authorization header is present
if (req.headers && req.headers.authorization) {
let parts = req.headers.authorization.split(' ');
// Check the Authorization Header is well formed
if (parts.length === 2 && parts[0] === 'Bearer') {
let token = parts[1];
try {
// verify JWT and find user in database
let jwtbody = jwt.verify(token, this.secret)
let user = this.service.db.getCollection('users').findOne({ _id: jwtbody._id })
return user
} catch (e) {
this.throwUnauthenticated(`${e.name}: ${e.message}`)
}
} else {
this.throwUnauthenticated('Invalid Authorization Header')
}
} else {
this.throwUnauthenticated('No Authorization Header')
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.