language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
JavaScript | class YArray extends AbstractType {
constructor () {
super();
/**
* @type {Array<any>?}
* @private
*/
this._prelimContent = [];
}
/**
* Integrate this type into the Yjs instance.
*
* * Save this struct in the os
* * This type is sent to other client
* * Observer functions are fired
*
* @param {Doc} y The Yjs instance
* @param {Item} item
*/
_integrate (y, item) {
super._integrate(y, item);
this.insert(0, /** @type {Array<any>} */ (this._prelimContent));
this._prelimContent = null;
}
_copy () {
return new YArray()
}
get length () {
return this._prelimContent === null ? this._length : this._prelimContent.length
}
/**
* Creates YArrayEvent and calls observers.
*
* @param {Transaction} transaction
* @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
*/
_callObserver (transaction, parentSubs) {
callTypeObservers(this, transaction, new YArrayEvent(this, transaction));
}
/**
* Inserts new content at an index.
*
* Important: This function expects an array of content. Not just a content
* object. The reason for this "weirdness" is that inserting several elements
* is very efficient when it is done as a single operation.
*
* @example
* // Insert character 'a' at position 0
* yarray.insert(0, ['a'])
* // Insert numbers 1, 2 at position 1
* yarray.insert(1, [1, 2])
*
* @param {number} index The index to insert content at.
* @param {Array<T>} content The array of content
*/
insert (index, content) {
if (this.doc !== null) {
transact(this.doc, transaction => {
typeListInsertGenerics(transaction, this, index, content);
});
} else {
/** @type {Array<any>} */ (this._prelimContent).splice(index, 0, ...content);
}
}
/**
* Appends content to this YArray.
*
* @param {Array<T>} content Array of content to append.
*/
push (content) {
this.insert(this.length, content);
}
/**
* Preppends content to this YArray.
*
* @param {Array<T>} content Array of content to preppend.
*/
unshift (content) {
this.insert(0, content);
}
/**
* Deletes elements starting from an index.
*
* @param {number} index Index at which to start deleting elements
* @param {number} length The number of elements to remove. Defaults to 1.
*/
delete (index, length = 1) {
if (this.doc !== null) {
transact(this.doc, transaction => {
typeListDelete(transaction, this, index, length);
});
} else {
/** @type {Array<any>} */ (this._prelimContent).splice(index, length);
}
}
/**
* Returns the i-th element from a YArray.
*
* @param {number} index The index of the element to return from the YArray
* @return {T}
*/
get (index) {
return typeListGet(this, index)
}
/**
* Transforms this YArray to a JavaScript Array.
*
* @return {Array<T>}
*/
toArray () {
return typeListToArray(this)
}
/**
* Transforms this Shared Type to a JSON object.
*
* @return {Array<any>}
*/
toJSON () {
return this.map(c => c instanceof AbstractType ? c.toJSON() : c)
}
/**
* Returns an Array with the result of calling a provided function on every
* element of this YArray.
*
* @template T,M
* @param {function(T,number,YArray<T>):M} f Function that produces an element of the new Array
* @return {Array<M>} A new array with each element being the result of the
* callback function
*/
map (f) {
return typeListMap(this, /** @type {any} */ (f))
}
/**
* Executes a provided function on once on overy element of this YArray.
*
* @param {function(T,number,YArray<T>):void} f A function to execute on every element of this YArray.
*/
forEach (f) {
typeListForEach(this, f);
}
/**
* @return {IterableIterator<T>}
*/
[Symbol.iterator] () {
return typeListCreateIterator(this)
}
/**
* @param {encoding.Encoder} encoder
*/
_write (encoder) {
writeVarUint(encoder, YArrayRefID);
}
} |
JavaScript | class YMapEvent extends YEvent {
/**
* @param {YMap<T>} ymap The YArray that changed.
* @param {Transaction} transaction
* @param {Set<any>} subs The keys that changed.
*/
constructor (ymap, transaction, subs) {
super(ymap, transaction);
this.keysChanged = subs;
}
} |
JavaScript | class YMap extends AbstractType {
/**
*
* @param {Iterable<readonly [string, any]>=} entries - an optional iterable to initialize the YMap
*/
constructor (entries) {
super();
/**
* @type {Map<string,any>?}
* @private
*/
this._prelimContent = null;
if (entries === undefined) {
this._prelimContent = new Map();
} else {
this._prelimContent = new Map(entries);
}
}
/**
* Integrate this type into the Yjs instance.
*
* * Save this struct in the os
* * This type is sent to other client
* * Observer functions are fired
*
* @param {Doc} y The Yjs instance
* @param {Item} item
*/
_integrate (y, item) {
super._integrate(y, item);
for (const [key, value] of /** @type {Map<string, any>} */ (this._prelimContent)) {
this.set(key, value);
}
this._prelimContent = null;
}
_copy () {
return new YMap()
}
/**
* Creates YMapEvent and calls observers.
*
* @param {Transaction} transaction
* @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
*/
_callObserver (transaction, parentSubs) {
callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs));
}
/**
* Transforms this Shared Type to a JSON object.
*
* @return {Object<string,T>}
*/
toJSON () {
/**
* @type {Object<string,T>}
*/
const map = {};
for (const [key, item] of this._map) {
if (!item.deleted) {
const v = item.content.getContent()[item.length - 1];
map[key] = v instanceof AbstractType ? v.toJSON() : v;
}
}
return map
}
/**
* Returns the size of the YMap (count of key/value pairs)
*
* @return {number}
*/
get size () {
return [...createMapIterator(this._map)].length
}
/**
* Returns the keys for each element in the YMap Type.
*
* @return {IterableIterator<string>}
*/
keys () {
return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[0])
}
/**
* Returns the keys for each element in the YMap Type.
*
* @return {IterableIterator<string>}
*/
values () {
return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[1].content.getContent()[v[1].length - 1])
}
/**
* Returns an Iterator of [key, value] pairs
*
* @return {IterableIterator<any>}
*/
entries () {
return iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => [v[0], v[1].content.getContent()[v[1].length - 1]])
}
/**
* Executes a provided function on once on every key-value pair.
*
* @param {function(T,string,YMap<T>):void} f A function to execute on every element of this YArray.
*/
forEach (f) {
/**
* @type {Object<string,T>}
*/
const map = {};
for (const [key, item] of this._map) {
if (!item.deleted) {
f(item.content.getContent()[item.length - 1], key, this);
}
}
return map
}
/**
* @return {IterableIterator<T>}
*/
[Symbol.iterator] () {
return this.entries()
}
/**
* Remove a specified element from this YMap.
*
* @param {string} key The key of the element to remove.
*/
delete (key) {
if (this.doc !== null) {
transact(this.doc, transaction => {
typeMapDelete(transaction, this, key);
});
} else {
/** @type {Map<string, any>} */ (this._prelimContent).delete(key);
}
}
/**
* Adds or updates an element with a specified key and value.
*
* @param {string} key The key of the element to add to this YMap
* @param {T} value The value of the element to add
*/
set (key, value) {
if (this.doc !== null) {
transact(this.doc, transaction => {
typeMapSet(transaction, this, key, value);
});
} else {
/** @type {Map<string, any>} */ (this._prelimContent).set(key, value);
}
return value
}
/**
* Returns a specified element from this YMap.
*
* @param {string} key
* @return {T|undefined}
*/
get (key) {
return /** @type {any} */ (typeMapGet(this, key))
}
/**
* Returns a boolean indicating whether the specified key exists or not.
*
* @param {string} key The key to test.
* @return {boolean}
*/
has (key) {
return typeMapHas(this, key)
}
/**
* @param {encoding.Encoder} encoder
*/
_write (encoder) {
writeVarUint(encoder, YMapRefID);
}
} |
JavaScript | class YTextEvent extends YEvent {
/**
* @param {YText} ytext
* @param {Transaction} transaction
*/
constructor (ytext, transaction) {
super(ytext, transaction);
/**
* @type {Array<DeltaItem>|null}
*/
this._delta = null;
}
/**
* Compute the changes in the delta format.
* A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document.
*
* @type {Array<DeltaItem>}
*
* @public
*/
get delta () {
if (this._delta === null) {
const y = /** @type {Doc} */ (this.target.doc);
this._delta = [];
transact(y, transaction => {
const delta = /** @type {Array<DeltaItem>} */ (this._delta);
const currentAttributes = new Map(); // saves all current attributes for insert
const oldAttributes = new Map();
let item = this.target._start;
/**
* @type {string?}
*/
let action = null;
/**
* @type {Object<string,any>}
*/
const attributes = {}; // counts added or removed new attributes for retain
/**
* @type {string|object}
*/
let insert = '';
let retain = 0;
let deleteLen = 0;
const addOp = () => {
if (action !== null) {
/**
* @type {any}
*/
let op;
switch (action) {
case 'delete':
op = { delete: deleteLen };
deleteLen = 0;
break
case 'insert':
op = { insert };
if (currentAttributes.size > 0) {
op.attributes = {};
for (const [key, value] of currentAttributes) {
if (value !== null) {
op.attributes[key] = value;
}
}
}
insert = '';
break
case 'retain':
op = { retain };
if (Object.keys(attributes).length > 0) {
op.attributes = {};
for (const key in attributes) {
op.attributes[key] = attributes[key];
}
}
retain = 0;
break
}
delta.push(op);
action = null;
}
};
while (item !== null) {
switch (item.content.constructor) {
case ContentEmbed:
if (this.adds(item)) {
if (!this.deletes(item)) {
addOp();
action = 'insert';
insert = /** @type {ContentEmbed} */ (item.content).embed;
addOp();
}
} else if (this.deletes(item)) {
if (action !== 'delete') {
addOp();
action = 'delete';
}
deleteLen += 1;
} else if (!item.deleted) {
if (action !== 'retain') {
addOp();
action = 'retain';
}
retain += 1;
}
break
case ContentString:
if (this.adds(item)) {
if (!this.deletes(item)) {
if (action !== 'insert') {
addOp();
action = 'insert';
}
insert += /** @type {ContentString} */ (item.content).str;
}
} else if (this.deletes(item)) {
if (action !== 'delete') {
addOp();
action = 'delete';
}
deleteLen += item.length;
} else if (!item.deleted) {
if (action !== 'retain') {
addOp();
action = 'retain';
}
retain += item.length;
}
break
case ContentFormat: {
const { key, value } = /** @type {ContentFormat} */ (item.content);
if (this.adds(item)) {
if (!this.deletes(item)) {
const curVal = currentAttributes.get(key) || null;
if (!equalAttrs(curVal, value)) {
if (action === 'retain') {
addOp();
}
if (equalAttrs(value, (oldAttributes.get(key) || null))) {
delete attributes[key];
} else {
attributes[key] = value;
}
} else {
item.delete(transaction);
}
}
} else if (this.deletes(item)) {
oldAttributes.set(key, value);
const curVal = currentAttributes.get(key) || null;
if (!equalAttrs(curVal, value)) {
if (action === 'retain') {
addOp();
}
attributes[key] = curVal;
}
} else if (!item.deleted) {
oldAttributes.set(key, value);
const attr = attributes[key];
if (attr !== undefined) {
if (!equalAttrs(attr, value)) {
if (action === 'retain') {
addOp();
}
if (value === null) {
attributes[key] = value;
} else {
delete attributes[key];
}
} else {
item.delete(transaction);
}
}
}
if (!item.deleted) {
if (action === 'insert') {
addOp();
}
updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (item.content));
}
break
}
}
item = item.right;
}
addOp();
while (delta.length > 0) {
const lastOp = delta[delta.length - 1];
if (lastOp.retain !== undefined && lastOp.attributes === undefined) {
// retain delta's if they don't assign attributes
delta.pop();
} else {
break
}
}
});
}
return this._delta
}
} |
JavaScript | class YText extends AbstractType {
/**
* @param {String} [string] The initial value of the YText.
*/
constructor (string) {
super();
/**
* Array of pending operations on this type
* @type {Array<function():void>?}
*/
this._pending = string !== undefined ? [() => this.insert(0, string)] : [];
}
/**
* Number of characters of this text type.
*
* @type {number}
*/
get length () {
return this._length
}
/**
* @param {Doc} y
* @param {Item} item
*/
_integrate (y, item) {
super._integrate(y, item);
try {
/** @type {Array<function>} */ (this._pending).forEach(f => f());
} catch (e) {
console.error(e);
}
this._pending = null;
}
_copy () {
return new YText()
}
/**
* Creates YTextEvent and calls observers.
*
* @param {Transaction} transaction
* @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
*/
_callObserver (transaction, parentSubs) {
const event = new YTextEvent(this, transaction);
const doc = transaction.doc;
// If a remote change happened, we try to cleanup potential formatting duplicates.
if (!transaction.local) {
// check if another formatting item was inserted
let foundFormattingItem = false;
for (const [client, afterClock] of transaction.afterState) {
const clock = transaction.beforeState.get(client) || 0;
if (afterClock === clock) {
continue
}
iterateStructs(transaction, /** @type {Array<Item|GC>} */ (doc.store.clients.get(client)), clock, afterClock, item => {
// @ts-ignore
if (!item.deleted && item.content.constructor === ContentFormat) {
foundFormattingItem = true;
}
});
if (foundFormattingItem) {
break
}
}
transact(doc, t => {
if (foundFormattingItem) {
// If a formatting item was inserted, we simply clean the whole type.
// We need to compute currentAttributes for the current position anyway.
cleanupYTextFormatting(this);
} else {
// If no formatting attribute was inserted, we can make due with contextless
// formatting cleanups.
// Contextless: it is not necessary to compute currentAttributes for the affected position.
iterateDeletedStructs(t, transaction.deleteSet, item => {
if (item instanceof GC) {
return
}
if (item.parent === this) {
cleanupContextlessFormattingGap(t, item);
}
});
}
});
}
callTypeObservers(this, transaction, event);
}
/**
* Returns the unformatted string representation of this YText type.
*
* @public
*/
toString () {
let str = '';
/**
* @type {Item|null}
*/
let n = this._start;
while (n !== null) {
if (!n.deleted && n.countable && n.content.constructor === ContentString) {
str += /** @type {ContentString} */ (n.content).str;
}
n = n.right;
}
return str
}
/**
* Returns the unformatted string representation of this YText type.
*
* @return {string}
* @public
*/
toJSON () {
return this.toString()
}
/**
* Apply a {@link Delta} on this shared YText type.
*
* @param {any} delta The changes to apply on this element.
* @param {object} [opts]
* @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true.
*
*
* @public
*/
applyDelta (delta, { sanitize = true } = {}) {
if (this.doc !== null) {
transact(this.doc, transaction => {
/**
* @type {ItemListPosition}
*/
const currPos = new ItemListPosition(null, this._start);
const currentAttributes = new Map();
for (let i = 0; i < delta.length; i++) {
const op = delta[i];
if (op.insert !== undefined) {
// Quill assumes that the content starts with an empty paragraph.
// Yjs/Y.Text assumes that it starts empty. We always hide that
// there is a newline at the end of the content.
// If we omit this step, clients will see a different number of
// paragraphs, but nothing bad will happen.
const ins = (!sanitize && typeof op.insert === 'string' && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === '\n') ? op.insert.slice(0, -1) : op.insert;
if (typeof ins !== 'string' || ins.length > 0) {
insertText(transaction, this, currPos, currentAttributes, ins, op.attributes || {});
}
} else if (op.retain !== undefined) {
formatText(transaction, this, currPos, currentAttributes, op.retain, op.attributes || {});
} else if (op.delete !== undefined) {
deleteText(transaction, currPos, currentAttributes, op.delete);
}
}
});
} else {
/** @type {Array<function>} */ (this._pending).push(() => this.applyDelta(delta));
}
}
/**
* Returns the Delta representation of this YText type.
*
* @param {Snapshot} [snapshot]
* @param {Snapshot} [prevSnapshot]
* @param {function('removed' | 'added', ID):any} [computeYChange]
* @return {any} The Delta representation of this type.
*
* @public
*/
toDelta (snapshot, prevSnapshot, computeYChange) {
/**
* @type{Array<any>}
*/
const ops = [];
const currentAttributes = new Map();
const doc = /** @type {Doc} */ (this.doc);
let str = '';
let n = this._start;
function packStr () {
if (str.length > 0) {
// pack str with attributes to ops
/**
* @type {Object<string,any>}
*/
const attributes = {};
let addAttributes = false;
for (const [key, value] of currentAttributes) {
addAttributes = true;
attributes[key] = value;
}
/**
* @type {Object<string,any>}
*/
const op = { insert: str };
if (addAttributes) {
op.attributes = attributes;
}
ops.push(op);
str = '';
}
}
// snapshots are merged again after the transaction, so we need to keep the
// transalive until we are done
transact(doc, transaction => {
if (snapshot) {
splitSnapshotAffectedStructs(transaction, snapshot);
}
if (prevSnapshot) {
splitSnapshotAffectedStructs(transaction, prevSnapshot);
}
while (n !== null) {
if (isVisible(n, snapshot) || (prevSnapshot !== undefined && isVisible(n, prevSnapshot))) {
switch (n.content.constructor) {
case ContentString: {
const cur = currentAttributes.get('ychange');
if (snapshot !== undefined && !isVisible(n, snapshot)) {
if (cur === undefined || cur.user !== n.id.client || cur.state !== 'removed') {
packStr();
currentAttributes.set('ychange', computeYChange ? computeYChange('removed', n.id) : { type: 'removed' });
}
} else if (prevSnapshot !== undefined && !isVisible(n, prevSnapshot)) {
if (cur === undefined || cur.user !== n.id.client || cur.state !== 'added') {
packStr();
currentAttributes.set('ychange', computeYChange ? computeYChange('added', n.id) : { type: 'added' });
}
} else if (cur !== undefined) {
packStr();
currentAttributes.delete('ychange');
}
str += /** @type {ContentString} */ (n.content).str;
break
}
case ContentEmbed: {
packStr();
/**
* @type {Object<string,any>}
*/
const op = {
insert: /** @type {ContentEmbed} */ (n.content).embed
};
if (currentAttributes.size > 0) {
const attrs = /** @type {Object<string,any>} */ ({});
op.attributes = attrs;
for (const [key, value] of currentAttributes) {
attrs[key] = value;
}
}
ops.push(op);
break
}
case ContentFormat:
if (isVisible(n, snapshot)) {
packStr();
updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (n.content));
}
break
}
}
n = n.right;
}
packStr();
}, splitSnapshotAffectedStructs);
return ops
}
/**
* Insert text at a given index.
*
* @param {number} index The index at which to start inserting.
* @param {String} text The text to insert at the specified position.
* @param {TextAttributes} [attributes] Optionally define some formatting
* information to apply on the inserted
* Text.
* @public
*/
insert (index, text, attributes) {
if (text.length <= 0) {
return
}
const y = this.doc;
if (y !== null) {
transact(y, transaction => {
const { left, right, currentAttributes } = findPosition(transaction, this, index);
if (!attributes) {
attributes = {};
// @ts-ignore
currentAttributes.forEach((v, k) => { attributes[k] = v; });
}
insertText(transaction, this, new ItemListPosition(left, right), currentAttributes, text, attributes);
});
} else {
/** @type {Array<function>} */ (this._pending).push(() => this.insert(index, text, attributes));
}
}
/**
* Inserts an embed at a index.
*
* @param {number} index The index to insert the embed at.
* @param {Object} embed The Object that represents the embed.
* @param {TextAttributes} attributes Attribute information to apply on the
* embed
*
* @public
*/
insertEmbed (index, embed, attributes = {}) {
if (embed.constructor !== Object) {
throw new Error('Embed must be an Object')
}
const y = this.doc;
if (y !== null) {
transact(y, transaction => {
const { left, right, currentAttributes } = findPosition(transaction, this, index);
insertText(transaction, this, new ItemListPosition(left, right), currentAttributes, embed, attributes);
});
} else {
/** @type {Array<function>} */ (this._pending).push(() => this.insertEmbed(index, embed, attributes));
}
}
/**
* Deletes text starting from an index.
*
* @param {number} index Index at which to start deleting.
* @param {number} length The number of characters to remove. Defaults to 1.
*
* @public
*/
delete (index, length) {
if (length === 0) {
return
}
const y = this.doc;
if (y !== null) {
transact(y, transaction => {
const { left, right, currentAttributes } = findPosition(transaction, this, index);
deleteText(transaction, new ItemListPosition(left, right), currentAttributes, length);
});
} else {
/** @type {Array<function>} */ (this._pending).push(() => this.delete(index, length));
}
}
/**
* Assigns properties to a range of text.
*
* @param {number} index The position where to start formatting.
* @param {number} length The amount of characters to assign properties to.
* @param {TextAttributes} attributes Attribute information to apply on the
* text.
*
* @public
*/
format (index, length, attributes) {
if (length === 0) {
return
}
const y = this.doc;
if (y !== null) {
transact(y, transaction => {
const { left, right, currentAttributes } = findPosition(transaction, this, index);
if (right === null) {
return
}
formatText(transaction, this, new ItemListPosition(left, right), currentAttributes, length, attributes);
});
} else {
/** @type {Array<function>} */ (this._pending).push(() => this.format(index, length, attributes));
}
}
/**
* @param {encoding.Encoder} encoder
*/
_write (encoder) {
writeVarUint(encoder, YTextRefID);
}
} |
JavaScript | class YXmlTreeWalker {
/**
* @param {YXmlFragment | YXmlElement} root
* @param {function(AbstractType<any>):boolean} [f]
*/
constructor (root, f = () => true) {
this._filter = f;
this._root = root;
/**
* @type {Item}
*/
this._currentNode = /** @type {Item} */ (root._start);
this._firstCall = true;
}
[Symbol.iterator] () {
return this
}
/**
* Get the next node.
*
* @return {IteratorResult<YXmlElement|YXmlText|YXmlHook>} The next node.
*
* @public
*/
next () {
/**
* @type {Item|null}
*/
let n = this._currentNode;
let type = /** @type {any} */ (n.content).type;
if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { // if first call, we check if we can use the first item
do {
type = /** @type {any} */ (n.content).type;
if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) {
// walk down in the tree
n = type._start;
} else {
// walk right or up in the tree
while (n !== null) {
if (n.right !== null) {
n = n.right;
break
} else if (n.parent === this._root) {
n = null;
} else {
n = /** @type {AbstractType<any>} */ (n.parent)._item;
}
}
}
} while (n !== null && (n.deleted || !this._filter(/** @type {ContentType} */ (n.content).type)))
}
this._firstCall = false;
if (n === null) {
// @ts-ignore
return { value: undefined, done: true }
}
this._currentNode = n;
return { value: /** @type {any} */ (n.content).type, done: false }
}
} |
JavaScript | class YXmlFragment extends AbstractType {
constructor () {
super();
/**
* @type {Array<any>|null}
*/
this._prelimContent = [];
}
/**
* Integrate this type into the Yjs instance.
*
* * Save this struct in the os
* * This type is sent to other client
* * Observer functions are fired
*
* @param {Doc} y The Yjs instance
* @param {Item} item
*/
_integrate (y, item) {
super._integrate(y, item);
this.insert(0, /** @type {Array<any>} */ (this._prelimContent));
this._prelimContent = null;
}
_copy () {
return new YXmlFragment()
}
get length () {
return this._prelimContent === null ? this._length : this._prelimContent.length
}
/**
* Create a subtree of childNodes.
*
* @example
* const walker = elem.createTreeWalker(dom => dom.nodeName === 'div')
* for (let node in walker) {
* // `node` is a div node
* nop(node)
* }
*
* @param {function(AbstractType<any>):boolean} filter Function that is called on each child element and
* returns a Boolean indicating whether the child
* is to be included in the subtree.
* @return {YXmlTreeWalker} A subtree and a position within it.
*
* @public
*/
createTreeWalker (filter) {
return new YXmlTreeWalker(this, filter)
}
/**
* Returns the first YXmlElement that matches the query.
* Similar to DOM's {@link querySelector}.
*
* Query support:
* - tagname
* TODO:
* - id
* - attribute
*
* @param {CSS_Selector} query The query on the children.
* @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null.
*
* @public
*/
querySelector (query) {
query = query.toUpperCase();
// @ts-ignore
const iterator = new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query);
const next = iterator.next();
if (next.done) {
return null
} else {
return next.value
}
}
/**
* Returns all YXmlElements that match the query.
* Similar to Dom's {@link querySelectorAll}.
*
* @todo Does not yet support all queries. Currently only query by tagName.
*
* @param {CSS_Selector} query The query on the children
* @return {Array<YXmlElement|YXmlText|YXmlHook|null>} The elements that match this query.
*
* @public
*/
querySelectorAll (query) {
query = query.toUpperCase();
// @ts-ignore
return Array.from(new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query))
}
/**
* Creates YXmlEvent and calls observers.
*
* @param {Transaction} transaction
* @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
*/
_callObserver (transaction, parentSubs) {
callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction));
}
/**
* Get the string representation of all the children of this YXmlFragment.
*
* @return {string} The string representation of all children.
*/
toString () {
return typeListMap(this, xml => xml.toString()).join('')
}
/**
* @return {string}
*/
toJSON () {
return this.toString()
}
/**
* Creates a Dom Element that mirrors this YXmlElement.
*
* @param {Document} [_document=document] The document object (you must define
* this when calling this method in
* nodejs)
* @param {Object<string, any>} [hooks={}] Optional property to customize how hooks
* are presented in the DOM
* @param {any} [binding] You should not set this property. This is
* used if DomBinding wants to create a
* association to the created DOM type.
* @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
*
* @public
*/
toDOM (_document = document, hooks = {}, binding) {
const fragment = _document.createDocumentFragment();
if (binding !== undefined) {
binding._createAssociation(fragment, this);
}
typeListForEach(this, xmlType => {
fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null);
});
return fragment
}
/**
* Inserts new content at an index.
*
* @example
* // Insert character 'a' at position 0
* xml.insert(0, [new Y.XmlText('text')])
*
* @param {number} index The index to insert content at
* @param {Array<YXmlElement|YXmlText>} content The array of content
*/
insert (index, content) {
if (this.doc !== null) {
transact(this.doc, transaction => {
typeListInsertGenerics(transaction, this, index, content);
});
} else {
// @ts-ignore _prelimContent is defined because this is not yet integrated
this._prelimContent.splice(index, 0, ...content);
}
}
/**
* Deletes elements starting from an index.
*
* @param {number} index Index at which to start deleting elements
* @param {number} [length=1] The number of elements to remove. Defaults to 1.
*/
delete (index, length = 1) {
if (this.doc !== null) {
transact(this.doc, transaction => {
typeListDelete(transaction, this, index, length);
});
} else {
// @ts-ignore _prelimContent is defined because this is not yet integrated
this._prelimContent.splice(index, length);
}
}
/**
* Transforms this YArray to a JavaScript Array.
*
* @return {Array<YXmlElement|YXmlText|YXmlHook>}
*/
toArray () {
return typeListToArray(this)
}
/**
* Transform the properties of this type to binary and write it to an
* BinaryEncoder.
*
* This is called when this Item is sent to a remote peer.
*
* @param {encoding.Encoder} encoder The encoder to write data to.
*/
_write (encoder) {
writeVarUint(encoder, YXmlFragmentRefID);
}
} |
JavaScript | class YXmlElement extends YXmlFragment {
constructor (nodeName = 'UNDEFINED') {
super();
this.nodeName = nodeName;
/**
* @type {Map<string, any>|null}
*/
this._prelimAttrs = new Map();
}
/**
* Integrate this type into the Yjs instance.
*
* * Save this struct in the os
* * This type is sent to other client
* * Observer functions are fired
*
* @param {Doc} y The Yjs instance
* @param {Item} item
*/
_integrate (y, item) {
super._integrate(y, item)
;(/** @type {Map<string, any>} */ (this._prelimAttrs)).forEach((value, key) => {
this.setAttribute(key, value);
});
this._prelimAttrs = null;
}
/**
* Creates an Item with the same effect as this Item (without position effect)
*
* @return {YXmlElement}
*/
_copy () {
return new YXmlElement(this.nodeName)
}
/**
* Returns the XML serialization of this YXmlElement.
* The attributes are ordered by attribute-name, so you can easily use this
* method to compare YXmlElements
*
* @return {string} The string representation of this type.
*
* @public
*/
toString () {
const attrs = this.getAttributes();
const stringBuilder = [];
const keys = [];
for (const key in attrs) {
keys.push(key);
}
keys.sort();
const keysLen = keys.length;
for (let i = 0; i < keysLen; i++) {
const key = keys[i];
stringBuilder.push(key + '="' + attrs[key] + '"');
}
const nodeName = this.nodeName.toLocaleLowerCase();
const attrsString = stringBuilder.length > 0 ? ' ' + stringBuilder.join(' ') : '';
return `<${nodeName}${attrsString}>${super.toString()}</${nodeName}>`
}
/**
* Removes an attribute from this YXmlElement.
*
* @param {String} attributeName The attribute name that is to be removed.
*
* @public
*/
removeAttribute (attributeName) {
if (this.doc !== null) {
transact(this.doc, transaction => {
typeMapDelete(transaction, this, attributeName);
});
} else {
/** @type {Map<string,any>} */ (this._prelimAttrs).delete(attributeName);
}
}
/**
* Sets or updates an attribute.
*
* @param {String} attributeName The attribute name that is to be set.
* @param {String} attributeValue The attribute value that is to be set.
*
* @public
*/
setAttribute (attributeName, attributeValue) {
if (this.doc !== null) {
transact(this.doc, transaction => {
typeMapSet(transaction, this, attributeName, attributeValue);
});
} else {
/** @type {Map<string, any>} */ (this._prelimAttrs).set(attributeName, attributeValue);
}
}
/**
* Returns an attribute value that belongs to the attribute name.
*
* @param {String} attributeName The attribute name that identifies the
* queried value.
* @return {String} The queried attribute value.
*
* @public
*/
getAttribute (attributeName) {
return /** @type {any} */ (typeMapGet(this, attributeName))
}
/**
* Returns all attribute name/value pairs in a JSON Object.
*
* @param {Snapshot} [snapshot]
* @return {Object<string, any>} A JSON Object that describes the attributes.
*
* @public
*/
getAttributes (snapshot) {
return typeMapGetAll(this)
}
/**
* Creates a Dom Element that mirrors this YXmlElement.
*
* @param {Document} [_document=document] The document object (you must define
* this when calling this method in
* nodejs)
* @param {Object<string, any>} [hooks={}] Optional property to customize how hooks
* are presented in the DOM
* @param {any} [binding] You should not set this property. This is
* used if DomBinding wants to create a
* association to the created DOM type.
* @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
*
* @public
*/
toDOM (_document = document, hooks = {}, binding) {
const dom = _document.createElement(this.nodeName);
const attrs = this.getAttributes();
for (const key in attrs) {
dom.setAttribute(key, attrs[key]);
}
typeListForEach(this, yxml => {
dom.appendChild(yxml.toDOM(_document, hooks, binding));
});
if (binding !== undefined) {
binding._createAssociation(dom, this);
}
return dom
}
/**
* Transform the properties of this type to binary and write it to an
* BinaryEncoder.
*
* This is called when this Item is sent to a remote peer.
*
* @param {encoding.Encoder} encoder The encoder to write data to.
*/
_write (encoder) {
writeVarUint(encoder, YXmlElementRefID);
writeVarString(encoder, this.nodeName);
}
} |
JavaScript | class YXmlEvent extends YEvent {
/**
* @param {YXmlElement|YXmlFragment} target The target on which the event is created.
* @param {Set<string|null>} subs The set of changed attributes. `null` is included if the
* child list changed.
* @param {Transaction} transaction The transaction instance with wich the
* change was created.
*/
constructor (target, subs, transaction) {
super(target, transaction);
/**
* Whether the children changed.
* @type {Boolean}
* @private
*/
this.childListChanged = false;
/**
* Set of all changed attributes.
* @type {Set<string|null>}
*/
this.attributesChanged = new Set();
subs.forEach((sub) => {
if (sub === null) {
this.childListChanged = true;
} else {
this.attributesChanged.add(sub);
}
});
}
} |
JavaScript | class YXmlHook extends YMap {
/**
* @param {string} hookName nodeName of the Dom Node.
*/
constructor (hookName) {
super();
/**
* @type {string}
*/
this.hookName = hookName;
}
/**
* Creates an Item with the same effect as this Item (without position effect)
*/
_copy () {
return new YXmlHook(this.hookName)
}
/**
* Creates a Dom Element that mirrors this YXmlElement.
*
* @param {Document} [_document=document] The document object (you must define
* this when calling this method in
* nodejs)
* @param {Object.<string, any>} [hooks] Optional property to customize how hooks
* are presented in the DOM
* @param {any} [binding] You should not set this property. This is
* used if DomBinding wants to create a
* association to the created DOM type
* @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
*
* @public
*/
toDOM (_document = document, hooks = {}, binding) {
const hook = hooks[this.hookName];
let dom;
if (hook !== undefined) {
dom = hook.createDom(this);
} else {
dom = document.createElement(this.hookName);
}
dom.setAttribute('data-yjs-hook', this.hookName);
if (binding !== undefined) {
binding._createAssociation(dom, this);
}
return dom
}
/**
* Transform the properties of this type to binary and write it to an
* BinaryEncoder.
*
* This is called when this Item is sent to a remote peer.
*
* @param {encoding.Encoder} encoder The encoder to write data to.
*/
_write (encoder) {
super._write(encoder);
writeVarUint(encoder, YXmlHookRefID);
writeVarString(encoder, this.hookName);
}
} |
JavaScript | class YXmlText extends YText {
_copy () {
return new YXmlText()
}
/**
* Creates a Dom Element that mirrors this YXmlText.
*
* @param {Document} [_document=document] The document object (you must define
* this when calling this method in
* nodejs)
* @param {Object<string, any>} [hooks] Optional property to customize how hooks
* are presented in the DOM
* @param {any} [binding] You should not set this property. This is
* used if DomBinding wants to create a
* association to the created DOM type.
* @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
*
* @public
*/
toDOM (_document = document, hooks, binding) {
const dom = _document.createTextNode(this.toString());
if (binding !== undefined) {
binding._createAssociation(dom, this);
}
return dom
}
toString () {
// @ts-ignore
return this.toDelta().map(delta => {
const nestedNodes = [];
for (const nodeName in delta.attributes) {
const attrs = [];
for (const key in delta.attributes[nodeName]) {
attrs.push({ key, value: delta.attributes[nodeName][key] });
}
// sort attributes to get a unique order
attrs.sort((a, b) => a.key < b.key ? -1 : 1);
nestedNodes.push({ nodeName, attrs });
}
// sort node order to get a unique order
nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1);
// now convert to dom string
let str = '';
for (let i = 0; i < nestedNodes.length; i++) {
const node = nestedNodes[i];
str += `<${node.nodeName}`;
for (let j = 0; j < node.attrs.length; j++) {
const attr = node.attrs[j];
str += ` ${attr.key}="${attr.value}"`;
}
str += '>';
}
str += delta.insert;
for (let i = nestedNodes.length - 1; i >= 0; i--) {
str += `</${nestedNodes[i].nodeName}>`;
}
return str
}).join('')
}
/**
* @return {string}
*/
toJSON () {
return this.toString()
}
/**
* @param {encoding.Encoder} encoder
*/
_write (encoder) {
writeVarUint(encoder, YXmlTextRefID);
}
} |
JavaScript | class Item$1 extends AbstractStruct {
/**
* @param {ID} id
* @param {Item | null} left
* @param {ID | null} origin
* @param {Item | null} right
* @param {ID | null} rightOrigin
* @param {AbstractType<any>|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it.
* @param {string | null} parentSub
* @param {AbstractContent} content
*/
constructor (id, left, origin, right, rightOrigin, parent, parentSub, content) {
super(id, content.getLength());
/**
* The item that was originally to the left of this item.
* @type {ID | null}
*/
this.origin = origin;
/**
* The item that is currently to the left of this item.
* @type {Item | null}
*/
this.left = left;
/**
* The item that is currently to the right of this item.
* @type {Item | null}
*/
this.right = right;
/**
* The item that was originally to the right of this item.
* @type {ID | null}
*/
this.rightOrigin = rightOrigin;
/**
* @type {AbstractType<any>|ID|null}
*/
this.parent = parent;
/**
* If the parent refers to this item with some kind of key (e.g. YMap, the
* key is specified here. The key is then used to refer to the list in which
* to insert this item. If `parentSub = null` type._start is the list in
* which to insert to. Otherwise it is `parent._map`.
* @type {String | null}
*/
this.parentSub = parentSub;
/**
* Whether this item was deleted or not.
* @type {Boolean}
*/
this.deleted = false;
/**
* If this type's effect is reundone this type refers to the type that undid
* this operation.
* @type {ID | null}
*/
this.redone = null;
/**
* @type {AbstractContent}
*/
this.content = content;
/**
* If true, do not garbage collect this Item.
*/
this.keep = false;
}
get countable () {
return this.content.isCountable()
}
/**
* Return missing ids, or define missing items and return null.
*
* @param {Transaction} transaction
* @param {StructStore} store
* @return {null | ID}
*/
getMissing (transaction, store) {
const origin = this.origin;
const rightOrigin = this.rightOrigin;
const parent = /** @type {ID} */ (this.parent);
if (origin && origin.clock >= getState(store, origin.client)) {
return this.origin
}
if (rightOrigin && rightOrigin.clock >= getState(store, rightOrigin.client)) {
return this.rightOrigin
}
if (parent && parent.constructor === ID && parent.clock >= getState(store, parent.client)) {
return parent
}
// We have all missing ids, now find the items
if (origin) {
this.left = getItemCleanEnd(transaction, store, origin);
this.origin = this.left.lastId;
}
if (rightOrigin) {
this.right = getItemCleanStart(transaction, rightOrigin);
this.rightOrigin = this.right.id;
}
if (parent && parent.constructor === ID) {
if (parent.clock < getState(store, parent.client)) {
const parentItem = getItem(store, parent);
if (parentItem.constructor === GC) {
this.parent = null;
} else {
this.parent = /** @type {ContentType} */ (parentItem.content).type;
}
} else {
return parent
}
}
// only set item if this shouldn't be garbage collected
if (!this.parent) {
if (this.left && this.left.constructor === Item$1) {
this.parent = this.left.parent;
this.parentSub = this.left.parentSub;
}
if (this.right && this.right.constructor === Item$1) {
this.parent = this.right.parent;
this.parentSub = this.right.parentSub;
}
}
return null
}
/**
* @param {Transaction} transaction
* @param {number} offset
*/
integrate (transaction, offset) {
const store = transaction.doc.store;
if (offset > 0) {
this.id.clock += offset;
this.left = getItemCleanEnd(transaction, store, createID(this.id.client, this.id.clock - 1));
this.origin = this.left.lastId;
this.content = this.content.splice(offset);
this.length -= offset;
}
const parentSub = this.parentSub;
const length = this.length;
const parent = /** @type {AbstractType<any>|null} */ (this.parent);
if (parent) {
/**
* @type {Item|null}
*/
let left = this.left;
/**
* @type {Item|null}
*/
let o;
// set o to the first conflicting item
if (left !== null) {
o = left.right;
} else if (parentSub !== null) {
o = parent._map.get(parentSub) || null;
while (o !== null && o.left !== null) {
o = o.left;
}
} else {
o = parent._start;
}
// TODO: use something like DeleteSet here (a tree implementation would be best)
// @todo use global set definitions
/**
* @type {Set<Item>}
*/
const conflictingItems = new Set();
/**
* @type {Set<Item>}
*/
const itemsBeforeOrigin = new Set();
// Let c in conflictingItems, b in itemsBeforeOrigin
// ***{origin}bbbb{this}{c,b}{c,b}{o}***
// Note that conflictingItems is a subset of itemsBeforeOrigin
while (o !== null && o !== this.right) {
itemsBeforeOrigin.add(o);
conflictingItems.add(o);
if (compareIDs(this.origin, o.origin)) {
// case 1
if (o.id.client < this.id.client) {
left = o;
conflictingItems.clear();
}
} else if (o.origin !== null && itemsBeforeOrigin.has(getItem(store, o.origin))) {
// case 2
if (o.origin === null || !conflictingItems.has(getItem(store, o.origin))) {
left = o;
conflictingItems.clear();
}
} else {
break
}
o = o.right;
}
this.left = left;
// reconnect left/right + update parent map/start if necessary
if (left !== null) {
const right = left.right;
this.right = right;
left.right = this;
} else {
let r;
if (parentSub !== null) {
r = parent._map.get(parentSub) || null;
while (r !== null && r.left !== null) {
r = r.left;
}
} else {
r = parent._start;
parent._start = this;
}
this.right = r;
}
if (this.right !== null) {
this.right.left = this;
} else if (parentSub !== null) {
// set as current parent value if right === null and this is parentSub
parent._map.set(parentSub, this);
if (left !== null) {
// this is the current attribute value of parent. delete right
left.delete(transaction);
}
}
// adjust length of parent
if (parentSub === null && this.countable && !this.deleted) {
parent._length += length;
}
addStruct(store, this);
this.content.integrate(transaction, this);
// add parent to transaction.changed
addChangedTypeToTransaction(transaction, parent, parentSub);
if ((parent._item !== null && parent._item.deleted) || (this.right !== null && parentSub !== null)) {
// delete if parent is deleted or if this is not the current attribute value of parent
this.delete(transaction);
}
} else {
// parent is not defined. Integrate GC struct instead
new GC(this.id, this.length).integrate(transaction, 0);
}
}
/**
* Returns the next non-deleted item
*/
get next () {
let n = this.right;
while (n !== null && n.deleted) {
n = n.right;
}
return n
}
/**
* Returns the previous non-deleted item
*/
get prev () {
let n = this.left;
while (n !== null && n.deleted) {
n = n.left;
}
return n
}
/**
* Computes the last content address of this Item.
*/
get lastId () {
// allocating ids is pretty costly because of the amount of ids created, so we try to reuse whenever possible
return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1)
}
/**
* Try to merge two items
*
* @param {Item} right
* @return {boolean}
*/
mergeWith (right) {
if (
compareIDs(right.origin, this.lastId) &&
this.right === right &&
compareIDs(this.rightOrigin, right.rightOrigin) &&
this.id.client === right.id.client &&
this.id.clock + this.length === right.id.clock &&
this.deleted === right.deleted &&
this.redone === null &&
right.redone === null &&
this.content.constructor === right.content.constructor &&
this.content.mergeWith(right.content)
) {
if (right.keep) {
this.keep = true;
}
this.right = right.right;
if (this.right !== null) {
this.right.left = this;
}
this.length += right.length;
return true
}
return false
}
/**
* Mark this Item as deleted.
*
* @param {Transaction} transaction
*/
delete (transaction) {
if (!this.deleted) {
const parent = /** @type {AbstractType<any>} */ (this.parent);
// adjust the length of parent
if (this.countable && this.parentSub === null) {
parent._length -= this.length;
}
this.deleted = true;
addToDeleteSet(transaction.deleteSet, this.id, this.length);
setIfUndefined(transaction.changed, parent, create$1).add(this.parentSub);
this.content.delete(transaction);
}
}
/**
* @param {StructStore} store
* @param {boolean} parentGCd
*/
gc (store, parentGCd) {
if (!this.deleted) {
throw unexpectedCase()
}
this.content.gc(store);
if (parentGCd) {
replaceStruct(store, this, new GC(this.id, this.length));
} else {
this.content = new ContentDeleted(this.length);
}
}
/**
* Transform the properties of this type to binary and write it to an
* BinaryEncoder.
*
* This is called when this Item is sent to a remote peer.
*
* @param {encoding.Encoder} encoder The encoder to write data to.
* @param {number} offset
*/
write (encoder, offset) {
const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin;
const rightOrigin = this.rightOrigin;
const parentSub = this.parentSub;
const info = (this.content.getRef() & BITS5) |
(origin === null ? 0 : BIT8) | // origin is defined
(rightOrigin === null ? 0 : BIT7) | // right origin is defined
(parentSub === null ? 0 : BIT6); // parentSub is non-null
writeUint8(encoder, info);
if (origin !== null) {
writeID(encoder, origin);
}
if (rightOrigin !== null) {
writeID(encoder, rightOrigin);
}
if (origin === null && rightOrigin === null) {
const parent = /** @type {AbstractType<any>} */ (this.parent);
const parentItem = parent._item;
if (parentItem === null) {
// parent type on y._map
// find the correct key
const ykey = findRootTypeKey(parent);
writeVarUint(encoder, 1); // write parentYKey
writeVarString(encoder, ykey);
} else {
writeVarUint(encoder, 0); // write parent id
writeID(encoder, parentItem.id);
}
if (parentSub !== null) {
writeVarString(encoder, parentSub);
}
}
this.content.write(encoder, offset);
}
} |
JavaScript | class Xorshift32 {
/**
* @param {number} seed Unsigned 32 bit number
*/
constructor (seed) {
this.seed = seed;
/**
* @type {number}
*/
this._state = seed;
}
/**
* Generate a random signed integer.
*
* @return {Number} A 32 bit signed integer.
*/
next () {
let x = this._state;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
this._state = x;
return (x >>> 0) / (BITS32 + 1)
}
} |
JavaScript | class Xoroshiro128plus {
/**
* @param {number} seed Unsigned 32 bit number
*/
constructor (seed) {
this.seed = seed;
// This is a variant of Xoroshiro128plus to fill the initial state
const xorshift32 = new Xorshift32(seed);
this.state = new Uint32Array(4);
for (let i = 0; i < 4; i++) {
this.state[i] = xorshift32.next() * BITS32;
}
this._fresh = true;
}
/**
* @return {number} Float/Double in [0,1)
*/
next () {
const state = this.state;
if (this._fresh) {
this._fresh = false;
return ((state[0] + state[2]) >>> 0) / (BITS32 + 1)
} else {
this._fresh = true;
const s0 = state[0];
const s1 = state[1];
const s2 = state[2] ^ s0;
const s3 = state[3] ^ s1;
// function js_rotl (x, k) {
// k = k - 32
// const x1 = x[0]
// const x2 = x[1]
// x[0] = x2 << k | x1 >>> (32 - k)
// x[1] = x1 << k | x2 >>> (32 - k)
// }
// rotl(s0, 55) // k = 23 = 55 - 32; j = 9 = 32 - 23
state[0] = (s1 << 23 | s0 >>> 9) ^ s2 ^ (s2 << 14 | s3 >>> 18);
state[1] = (s0 << 23 | s1 >>> 9) ^ s3 ^ (s3 << 14);
// rol(s1, 36) // k = 4 = 36 - 32; j = 23 = 32 - 9
state[2] = s3 << 4 | s2 >>> 28;
state[3] = s2 << 4 | s3 >>> 28;
return (((state[1] + state[3]) >>> 0) / (BITS32 + 1))
}
}
} |
JavaScript | class ServiceBase {
/**
* @param {string} token The token/key for the service
*/
constructor(token) {
/**
* The token that will be used for the service.
* @type {string}
* @private
*/
this.token = token;
}
/**
* The base URL of the service's API.
* @type {string}
* @readonly
*/
static get baseURL() {
return '';
}
/**
* Gets a service from a key.
* @param {string} key The name of the service to get
* @param {Array<CustomService>} [extras] An array of {@link CustomService}s to include
* @returns {?ServiceBase}
*/
static get(key, extras = []) {
if (!key || typeof key !== 'string')
return null;
const services = [
...Object.values(serviceClasses),
...extras
];
for (let i = 0, len = services.length; i < len; i++) {
const service = services[i];
if (!service || !service.aliases || !service.post)
continue;
if (service.aliases.includes(key.toLowerCase()))
return service;
}
return null;
}
/**
* Gets every loaded service.
* @returns {Object<string, ServiceBase>}
*/
static getAll() {
return serviceClasses;
}
/**
* Posts statistics to this service.
* Internally, this is supposed to be used in extended classes.
* @param {RequestForm} form The request form
* @param {boolean} [appendBaseURL] Whether to append the service's base API url
* @private
* @returns {Promise<AxiosResponse>}
*/
static _post(form, appendBaseURL = true) {
if (this.name === 'ServiceBase')
return Promise.reject(new Error('CALLED_FROM_BASE'));
if (this.baseURL && appendBaseURL)
form.url = this.baseURL + form.url;
return FormatRequest(form);
}
/**
* Sends a request for the service interface.
* @param {RequestForm} form The request form
* @param {Object} options The options of this request
* @param {boolean} [options.requiresToken] Whether the request requires a token
* @param {boolean} [options.appendBaseURL] Whether to prepend the service's base API url
* @private
* @returns {Promise<AxiosResponse>}
*/
_request(form, { requiresToken = false, appendBaseURL = true } = {}) {
if (requiresToken && !this.token)
return Promise.reject(new Error('REQUIRES_TOKEN'));
if (this.constructor.baseURL && appendBaseURL)
form.url = this.constructor.baseURL + form.url;
return FormatRequest(form);
}
/**
* Appends query string to a URL.
* @param {string} url The URL to modify
* @param {Query} query The query to append
* @param {boolean} appendBaseURL Whether to prepend the service's base API url
* @returns {string} The modified URL
* @private
*/
_appendQuery(url, query, appendBaseURL = true) {
if (this.constructor.baseURL && appendBaseURL)
url = this.constructor.baseURL + url;
return buildURL(url, query);
}
/**
* The values that can be used to select the service.
* @type {Array<string>}
* @readonly
*/
static get aliases() {
return [];
}
/**
* The logo URL, used only for documentation.
* @type {string}
* @private
* @readonly
*/
static get logoURL() {
return '';
}
/**
* Service's name, used only for documentation.
* @type {string}
* @private
* @readonly
*/
static get name() {
return '';
}
/**
* The website URL, used only for documentation.
* @type {string}
* @private
* @readonly
*/
static get websiteURL() {
return '';
}
} |
JavaScript | class EOSIOClient {
constructor(contractAccount) {
const rpc = new JsonRpc(process.env.REACT_APP_EOSIO_HTTP_URL, { fetch });
const signatureProvider = new JsSignatureProvider([
process.env.REACT_APP_EOSIO_PRIVATE_KEY
]);
this.contractAccount = contractAccount;
this.eos = new Api({
rpc,
signatureProvider,
textDecoder: new TextDecoder(),
textEncoder: new TextEncoder()
});
}
transaction = (actor, action, data) => {
return this.eos.transact(
{
actions: [
{
account: this.contractAccount,
name: action,
authorization: [
{
actor,
permission: "active"
}
],
data: {
...data
}
}
]
},
{
blocksBehind: 3,
expireSeconds: 30
}
);
};
} |
JavaScript | class PostComment extends Component {
state = {
postForm: POST_FORM,
formIsValid: false
};
componentDidUpdate(prevProps, prevState) {
if (
this.props.editing &&
prevProps.editing !== this.props.editing &&
prevProps.selectedPost !== this.props.selectedPost
) {
const postForm = {
comment: {
...prevState.postForm.comment,
value: this.props.selectedPost.comment,
valid: true
}
};
this.setState({ postForm: postForm, formIsValid: true });
}
}
postInputChangeHandler = (input, value, files) => {
this.setState(prevState => {
let isValid = true;
for (const validator of prevState.postForm[input].validators) {
isValid = isValid && validator(value);
}
const updatedForm = {
...prevState.postForm,
[input]: {
...prevState.postForm[input],
valid: isValid,
value: files ? files[0] : value
}
};
let formIsValid = true;
for (const inputName in updatedForm) {
formIsValid = formIsValid && updatedForm[inputName].valid;
}
return {
postForm: updatedForm,
formIsValid: formIsValid
};
});
};
inputBlurHandler = input => {
this.setState(prevState => {
return {
postForm: {
...prevState.postForm,
[input]: {
...prevState.postForm[input],
touched: true
}
}
};
});
};
cancelPostChangeHandler = () => {
this.setState({
postForm: POST_FORM,
formIsValid: false
});
this.props.onCancelEdit();
};
acceptPostChangeHandler = () => {
const post = {
comment: this.state.postForm.comment.value
};
this.props.onFinishEdit(post);
this.setState({
postForm: POST_FORM,
formIsValid: false
});
};
render() {
let modalTitle = 'Comment';
return this.props.editing ? (
<Fragment>
<Backdrop onClick={this.cancelPostChangeHandler} />
<Modal
title={modalTitle}
acceptEnabled={this.state.formIsValid}
onCancelModal={this.cancelPostChangeHandler}
onAcceptModal={this.acceptPostChangeHandler}
isLoading={this.props.loading}
>
<form>
<Input
id="comment"
label="Comment"
control="textarea"
rows="5"
onChange={this.postInputChangeHandler}
onBlur={this.inputBlurHandler.bind(this, 'comment')}
valid={this.state.postForm['comment'].valid}
touched={this.state.postForm['comment'].touched}
value={this.state.postForm['comment'].value}
/>
</form>
</Modal>
</Fragment>
) : null;
}
} |
JavaScript | class DataConnector {
/**
* Retrieve the list of items available from the data connector.
*
* @param query - The optional query filter to apply to the connector request.
*
* @returns A promise that always rejects with an error.
*
* #### Notes
* Subclasses should reimplement if they support a back-end that can list.
*/
async list(query) {
throw new Error('DataConnector#list method has not been implemented.');
}
/**
* Remove a value using the data connector.
*
* @param id - The identifier for the data being removed.
*
* @returns A promise that always rejects with an error.
*
* #### Notes
* Subclasses should reimplement if they support a back-end that can remove.
*/
async remove(id) {
throw new Error('DataConnector#remove method has not been implemented.');
}
/**
* Save a value using the data connector.
*
* @param id - The identifier for the data being saved.
*
* @param value - The data being saved.
*
* @returns A promise that always rejects with an error.
*
* #### Notes
* Subclasses should reimplement if they support a back-end that can save.
*/
async save(id, value) {
throw new Error('DataConnector#save method has not been implemented.');
}
} |
JavaScript | class ViewProfile extends Component {
constructor() {
super()
this.state = {
file: null,
fileURL : '',
data:[],
first_name:'',
last_name: '',
gender: '',
email: '',
// password: '',
joining: '',
address: '',
status: '',
role: '',
mobile: '',
isInEditMode: false,
errors: {}
}
this.onChange = this.onChange.bind(this)
this.onUpdate = this.onUpdate.bind(this)
this.onFormSubmit = this.onFormSubmit.bind(this);
this.onFormChange = this.onFormChange.bind(this);
}
changeEditMode=()=>{
this.setState({
isInEditMode: !this.state.isInEditMode
})
}
onFormSubmit(e){
e.preventDefault();
const formData = new FormData();
console.log("File onFormChange, file changed to = ");
console.log(this.state.file);
formData.append('myImage',this.state.file);
updateProfilePic(formData);
}
onFormChange(e) {
console.log(URL.createObjectURL(e.target.files[0]));
this.setState({file:e.target.files[0]});
this.setState({fileURL: URL.createObjectURL(e.target.files[0])});
console.log("1234567890")
console.log(URL.createObjectURL(e.target.files[0]));
}
onChange(e){
this.setState({[e.target.name] : e.target.value})
}
onUpdate(e){
e.preventDefault()
this.changeEditMode()
const updatedUser = {
firstname: this.state.first_name,
lastname: this.state.last_name,
email: this.state.email,
// password: this.state.password,
Joining_Date: this.state.joining,
address: this.state.address,
status: this.state.status,
role: this.state.role,
mobileno: this.state.mobile
}
update(updatedUser).then(res => {
// this.props.history.push(`/profile`)
console.log("Profile Updated Successful!")
})
}
componentDidMount() {
// const token = localStorage.usertoken
const token = localStorage.getItem('token')
fetchUserDetails(token, this.fetchedUser)
// console.log("token check... = "+token);
fetchUserPic(token, this.fetchedUserPic)
}
fetchedUser = (res, err) => {
console.log("Component did mount me fetchUser")
if(err) { this.props.history.push(`/login`) }
else {
// console.log("res.teamid = ")
// console.log(res);
this.setState({
first_name: res.firstname,
last_name: res.lastname,
email: res.email,
joining: res.Joining_Date,
address: res.address,
status: res.status,
role: res.role,
mobile: res.mobileno
})
}
}
fetchedUserPic = (res, err) => {
console.log("Component did mount -> fetchUserPic")
if(err) { this.props.history.push(`/login`) }
else {
// console.log("res.teamid = ")
// console.log(res);
this.setState({
file:res.files[0],
fileURL: URL.createObjectURL(res.files[0])
// first_name: res.firstname
})
}
}
renderDefaultView=()=>{
return (
<div className="animated fadeIn">
<Row>
<Col xs="12" sm="3">
<FormGroup row>
<div className="team-player">
<img
className="rounded-circle img-fluid img-raised"
src={(this.state.fileURL==='' ? require('./avtar.jpg') : this.state.fileURL)}
style={{height:"200px", width:"200px"}}
></img>
</div>
{/* <Col xs="12" md="9" style={{paddingTop: "40px"}}>
<Input type="file" id="fmyImage" name="myImage" onChange= {this.onFormChange} /> <br/>
<button type="submit" onClick={this.onFormSubmit}>Upload</button>
</Col> */}
</FormGroup>
</Col>
<Col xs="12" sm="6">
<Card>
<CardHeader>
<strong>Profile</strong>
</CardHeader>
<CardBody>
<FormGroup>
<Label htmlFor="firstname">First Name</Label>
<Input type="text" name="first_name" value={this.state.first_name} disabled={true} defaultValue={this.state.first_name}/>
</FormGroup>
<FormGroup>
<Label htmlFor="lastname">Last Name</Label>
<Input type="text" name="last_name" value={this.state.last_name} disabled={true} defaultValue={this.state.last_name}/>
</FormGroup>
<FormGroup>
<Label htmlFor="email">Email</Label>
<Input type="text" name="email" value={this.state.email} disabled={true} defaultValue={this.state.email}/>
</FormGroup>
<FormGroup>
<Label htmlFor="mobile">Mobile No</Label>
<Input type="text" name="mobile" value={this.state.mobile} disabled={true} defaultValue={this.state.mobile}/>
</FormGroup>
<FormGroup row className="my-0">
<Col xs="8">
<FormGroup>
<Label htmlFor="joining">Joining Date</Label>
<Input type="text" name="joining" value={this.state.joining} disabled={true} defaultValue={this.state.joining}/>
</FormGroup>
</Col>
<Col xs="4">
<FormGroup>
<Label htmlFor="role">Role</Label>
<Input type="text" name="role" value={this.state.role} disabled={true} defaultValue={this.state.role}/>
</FormGroup>
</Col>
</FormGroup>
<FormGroup row className="my-0">
<Col xs="8">
<FormGroup>
<Label htmlFor="address">Address</Label>
<Input type="text" name="address" value={this.state.address} disabled={true} defaultValue={this.state.address}/>
</FormGroup>
</Col>
<Col xs="4">
<FormGroup>
<Label htmlFor="status">Status</Label>
<Input type="text" name="status" value={this.state.status} disabled={true} defaultValue={this.state.status}/>
</FormGroup>
</Col>
</FormGroup>
<button
onClick={this.changeEditMode}
className="btn btn-outline-primary"
>
Update Profile
</button>
</CardBody>
</Card>
</Col>
<Col xs="12" sm="3"></Col>
</Row>
</div>
)
}
renderEditView=()=>{
return (
<div className="animated fadeIn">
<Row>
<Col xs="12" sm="3">
<FormGroup row>
<div className="team-player">
<img
className="rounded-circle img-fluid img-raised"
src={(this.state.fileURL==='' ? require('./avtar.jpg') : this.state.fileURL)}
style={{height:"200px", width:"200px"}}
></img>
</div>
<Col xs="12" md="9" style={{paddingTop: "5px" }}>
<Input type="file" id="fmyImage" name="myImage" onChange= {this.onFormChange} /> <br/>
<button type="submit" onClick={this.onFormSubmit}>Upload</button>
</Col>
</FormGroup>
</Col>
<Col xs="12" sm="6">
<Card>
<CardHeader>
<strong>Update Profile</strong>
{/* <small> Form</small> */}
</CardHeader>
<CardBody>
<FormGroup>
<Label htmlFor="firstname">First Name</Label>
<Input type="text" name="first_name" value={this.state.first_name} onChange={this.onChange} defaultValue={this.state.first_name}/>
</FormGroup>
<FormGroup>
<Label htmlFor="lastname">Last Name</Label>
<Input type="text" name="last_name" value={this.state.last_name} onChange={this.onChange} defaultValue={this.state.last_name}/>
</FormGroup>
<FormGroup>
<Label htmlFor="email">Email</Label>
<Input type="text" name="email" value={this.state.email} disabled={true} defaultValue={this.state.email}/>
</FormGroup>
<FormGroup>
<Label htmlFor="mobile">Mobile No</Label>
<Input type="text" name="mobile" value={this.state.mobile} onChange={this.onChange} defaultValue={this.state.mobile}/>
</FormGroup>
<FormGroup row className="my-0">
<Col xs="8">
<FormGroup>
<Label htmlFor="joining">Joining Date</Label>
<Input type="text" name="joining" value={this.state.joining} disabled={true} defaultValue={this.state.joining}/>
</FormGroup>
</Col>
<Col xs="4">
<FormGroup>
<Label htmlFor="role">Role</Label>
<Input type="text" name="role" value={this.state.role} disabled={true} defaultValue={this.state.role}/>
</FormGroup>
</Col>
</FormGroup>
<FormGroup row className="my-0">
<Col xs="8">
<FormGroup>
<Label htmlFor="address">Address</Label>
<Input type="text" name="address" value={this.state.address} onChange={this.onChange} defaultValue={this.state.address}/>
</FormGroup>
</Col>
<Col xs="4">
<FormGroup>
<Label htmlFor="status">Status</Label>
<Input type="text" name="status" value={this.state.status} disabled={true} defaultValue={this.state.status}/>
</FormGroup>
</Col>
</FormGroup>
<button
className="btn btn-outline-primary"
style={{justifyContent:"center", display:"flex"}}
onClick={this.onUpdate}
>
UPDATE
</button>
</CardBody>
</Card>
</Col>
<Col xs="12" sm="3"></Col>
</Row>
</div>
)
}
render() {
return this.state.isInEditMode?
this.renderEditView() :
this.renderDefaultView()
}
} |
JavaScript | class IssuesAndJQLQueries {
/**
* Constructs a new <code>IssuesAndJQLQueries</code>.
* List of issues and JQL queries.
* @alias module:model/IssuesAndJQLQueries
* @param issueIds {Array.<Number>} A list of issue IDs.
* @param jqls {Array.<String>} A list of JQL queries.
*/
constructor(issueIds, jqls) {
IssuesAndJQLQueries.initialize(this, issueIds, jqls);
}
/**
* 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, issueIds, jqls) {
obj['issueIds'] = issueIds;
obj['jqls'] = jqls;
}
/**
* Constructs a <code>IssuesAndJQLQueries</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/IssuesAndJQLQueries} obj Optional instance to populate.
* @return {module:model/IssuesAndJQLQueries} The populated <code>IssuesAndJQLQueries</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new IssuesAndJQLQueries();
if (data.hasOwnProperty('issueIds')) {
obj['issueIds'] = ApiClient.convertToType(data['issueIds'], ['Number']);
}
if (data.hasOwnProperty('jqls')) {
obj['jqls'] = ApiClient.convertToType(data['jqls'], ['String']);
}
}
return obj;
}
} |
JavaScript | class NWPResources extends Resources {
constructor() {
let collections = new Set();
['models', 'runs', 'regions', 'fields', 'levels', 'accumulations', 'thresholds']
.forEach(id => collections.add(new VariableCollection({ id })));
let nodes = {};
for (let collection of collections)
nodes[collection.id] = new Node(collection);
// build hierarchy
nodes.models.appendChild(nodes.runs);
nodes.runs.appendChild(nodes.regions);
nodes.regions.appendChild(nodes.fields);
nodes.fields.appendChild(nodes.levels, nodes.accumulations);
nodes.accumulations.appendChild(nodes.thresholds);
super({
topNode: nodes.models,
timesVariableCollections: new Set([nodes.models.variableCollection, nodes.runs.variableCollection])
});
}
/**
* Creates a Variable-Object and adds it to the VariableCollection.
*
* @param {module:meteoJS/modelviewer/variableCollection.VariableCollection}
* variableCollection - VariableCollection.
* @param {Object} [options] - Variable options.
* @param {mixed} [options.id] - Variable id.
* @param {string} [options.name] - Default name.
* @param {Object.<string,string>} [options.names] - Names.
* @param {string[]} [options.langSortation] - Priority of language codes.
* @param {Date|undefined} [option.sdatetime] - Datetime.
* @returns {module:meteoJS/modelviewer/nwpResources.NWPResources} This.
*/
addVariable(variableCollection,
{ id,
name = undefined,
names = {},
langSortation = [],
datetime = undefined } = {}) {
let variable =
(datetime === undefined)
? new Variable({
id,
name,
names,
langSortation
})
: new TimeVariable({
id,
name,
names,
langSortation,
datetime
});
variableCollection.append(variable);
return this;
}
/**
* Collection of all defined models.
*
* @type module:meteoJS/modelviewer/variableCollection.VariableCollection
* @readonly
*/
get models() {
return this.getNodeByVariableCollectionId('models').variableCollection;
}
/**
* Collection of all defined runs.
*
* @type module:meteoJS/modelviewer/variableCollection.VariableCollection
* @readonly
*/
get runs() {
return this.getNodeByVariableCollectionId('runs').variableCollection;
}
/**
* Collection of all defined regions.
*
* @type module:meteoJS/modelviewer/variableCollection.VariableCollection
* @readonly
*/
get regions() {
return this.getNodeByVariableCollectionId('regions').variableCollection;
}
/**
* Collection of all defined fields.
*
* @type module:meteoJS/modelviewer/variableCollection.VariableCollection
* @readonly
*/
get fields() {
return this.getNodeByVariableCollectionId('fields').variableCollection;
}
/**
* Collection of all defined levels.
*
* @type module:meteoJS/modelviewer/variableCollection.VariableCollection
* @readonly
*/
get levels() {
return this.getNodeByVariableCollectionId('levels').variableCollection;
}
/**
* Collection of all defined accumulations.
*
* @type module:meteoJS/modelviewer/variableCollection.VariableCollection
* @readonly
*/
get accumulations() {
return this.getNodeByVariableCollectionId('accumulations').variableCollection;
}
/**
* Collection of all defined thresholds.
*
* @type module:meteoJS/modelviewer/variableCollection.VariableCollection
* @readonly
*/
get thresholds() {
return this.getNodeByVariableCollectionId('thresholds').variableCollection;
}
} |
JavaScript | class SaratogaShips {
/**
* @param {SaratogaStore} store The updater instance that generated this instance
*/
constructor(store) {
Object.defineProperty(this, '_store', { value: store, writable: false });
}
get cache() {
if (!this._store._shipCache) return null;
return this._store._shipCache;
}
get rawCache() {
if (!this.cache) return null;
return this.cache.list;
}
/**
* Lists all the ships that matches a specific shjp class
* @param {string} shipClass class of the ship you want to search for (Case Sensitive)
* @memberof SaratogaShips
* @returns {Array<Ship> | null}
*/
getAllByClass(shipClass) {
if (!this.rawCache) return null;
return this.rawCache.filter(d => d.class === shipClass);
}
/**
* Lists all the ships that matches a specific ship nationality
* @param {string} nationality nationality of the ship you want to search for (Case Sensitive)
* @memberof SaratogaShips
* @returns {Array<Ship> | null}
*/
getAllByNationality(nationality) {
if (!this.rawCache) return null;
return this.rawCache.filter(d => d.nationality === nationality);
}
/**
* Lists all the ships that matches a specific ship hull type
* @param {string} hullType hullType of the ship you want to search for (Case Sensitive)
* @memberof SaratogaShips
* @returns {Array<Ship> | null}
*/
getAllByHullType(hullType) {
if (!this.rawCache) return null;
return this.rawCache.filter(d => d.hullType === hullType);
}
/**
* Lists all the ship that matches a specific rarity
* @param {string} rarity rarity of the ship you want to search for (Case Sensitive)
* @memberof SaratogaShips
* @returns {Array<Ship> | null}
*/
getAllByRarity(rarity) {
if (!this.rawCache) return null;
return this.rawCache.filter(d => d.rarity === rarity);
}
/**
* Fetches a specific ship via its id
* @param {number} id id of the ship you want to fetch
* @memberof SaratogaShips
* @returns {Ship | null}
*/
getById(id) {
if (!this.rawCache) return null;
const ship = this.rawCache.find(d => d.id === id);
if (!ship.length) return null;
return ship;
}
/**
* Searches for a specific ship. (EN, CN, JP, KR names are supported)
* @param {string} name name of the ship you want to search for
* @param {number} [limit=10] limit of the search results
* @memberof SaratogaShips
* @returns {Ship | null}
*/
searchShipByName(name, limit = 10) {
if (!this.cache) return null;
const possibleShips = this.cache.search(name, { limit });
if (!possibleShips.length) return null;
return possibleShips;
}
} |
JavaScript | class ErrorBoundary extends Component {
constructor(props) {
super(props)
this.state = { hasError: false }
}
componentDidCatch(error, info) {
this.setState({ hasError: true })
if(info){
console.log(info)
}
//TODO: send to a service or message to a server / slack / etc.
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <Panel>Something went wrong.</Panel>
}
return this.props.children
}
} |
JavaScript | class Component extends TransformSpec {
toString() {
return `Component<${this.constructor.name}>`;
}
} |
JavaScript | class NavigationStart {
constructor(id, url) {
this.id = id;
this.url = url;
}
toString() { return `NavigationStart(id: ${this.id}, url: '${this.url}')`; }
} |
JavaScript | class NavigationEnd {
constructor(id, url, urlAfterRedirects) {
this.id = id;
this.url = url;
this.urlAfterRedirects = urlAfterRedirects;
}
toString() {
return `NavigationEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}')`;
}
} |
JavaScript | class NavigationCancel {
constructor(id, url) {
this.id = id;
this.url = url;
}
toString() { return `NavigationCancel(id: ${this.id}, url: '${this.url}')`; }
} |
JavaScript | class NavigationError {
constructor(id, url, error) {
this.id = id;
this.url = url;
this.error = error;
}
toString() {
return `NavigationError(id: ${this.id}, url: '${this.url}', error: ${this.error})`;
}
} |
JavaScript | class RoutesRecognized {
constructor(id, url, urlAfterRedirects, state) {
this.id = id;
this.url = url;
this.urlAfterRedirects = urlAfterRedirects;
this.state = state;
}
toString() {
return `RoutesRecognized(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
}
} |
JavaScript | class Router {
/**
* Creates the router service.
*/
constructor(rootComponentType, resolver, urlSerializer, outletMap, location, injector, loader, config) {
this.rootComponentType = rootComponentType;
this.resolver = resolver;
this.urlSerializer = urlSerializer;
this.outletMap = outletMap;
this.location = location;
this.injector = injector;
this.navigationId = 0;
/**
* Indicates if at least one navigation happened.
*
* @experimental
*/
this.navigated = false;
this.resetConfig(config);
this.routerEvents = new Subject();
this.currentUrlTree = createEmptyUrlTree();
this.configLoader = new RouterConfigLoader(loader);
this.currentRouterState = createEmptyState(this.currentUrlTree, this.rootComponentType);
}
/**
* Sets up the location change listener and performs the inital navigation
*/
initialNavigation() {
this.setUpLocationChangeListener();
this.navigateByUrl(this.location.path(true));
}
/**
* Returns the current route state.
*/
get routerState() { return this.currentRouterState; }
/**
* Returns the current url.
*/
get url() { return this.serializeUrl(this.currentUrlTree); }
/**
* Returns an observable of route events
*/
get events() { return this.routerEvents; }
/**
* Resets the configuration used for navigation and generating links.
*
* ### Usage
*
* ```
* router.resetConfig([
* { path: 'team/:id', component: TeamCmp, children: [
* { path: 'simple', component: SimpleCmp },
* { path: 'user/:name', component: UserCmp }
* ] }
* ]);
* ```
*/
resetConfig(config) {
validateConfig(config);
this.config = config;
}
ngOnDestroy() { this.dispose(); }
/**
* Disposes of the router.
*/
dispose() { this.locationSubscription.unsubscribe(); }
/**
* Applies an array of commands to the current url tree and creates
* a new url tree.
*
* When given an activate route, applies the given commands starting from the route.
* When not given a route, applies the given command starting from the root.
*
* ### Usage
*
* ```
* // create /team/33/user/11
* router.createUrlTree(['/team', 33, 'user', 11]);
*
* // create /team/33;expand=true/user/11
* router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]);
*
* // you can collapse static segments like this (this works only with the first passed-in value):
* router.createUrlTree(['/team/33/user', userId]);
*
* If the first segment can contain slashes, and you do not want the router to split it, you
* can do the following:
*
* router.createUrlTree([{segmentPath: '/one/two'}]);
*
* // create /team/33/(user/11//aux:chat)
* router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]);
*
* // remove the right secondary node
* router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]);
*
* // assuming the current url is `/team/33/user/11` and the route points to `user/11`
*
* // navigate to /team/33/user/11/details
* router.createUrlTree(['details'], {relativeTo: route});
*
* // navigate to /team/33/user/22
* router.createUrlTree(['../22'], {relativeTo: route});
*
* // navigate to /team/44/user/22
* router.createUrlTree(['../../team/44/user/22'], {relativeTo: route});
* ```
*/
createUrlTree(commands, { relativeTo, queryParams, fragment, preserveQueryParams, preserveFragment } = {}) {
const a = relativeTo ? relativeTo : this.routerState.root;
const q = preserveQueryParams ? this.currentUrlTree.queryParams : queryParams;
const f = preserveFragment ? this.currentUrlTree.fragment : fragment;
return createUrlTree(a, this.currentUrlTree, commands, q, f);
}
/**
* Navigate based on the provided url. This navigation is always absolute.
*
* Returns a promise that:
* - is resolved with 'true' when navigation succeeds
* - is resolved with 'false' when navigation fails
* - is rejected when an error happens
*
* ### Usage
*
* ```
* router.navigateByUrl("/team/33/user/11");
*
* // Navigate without updating the URL
* router.navigateByUrl("/team/33/user/11", { skipLocationChange: true });
* ```
*
* In opposite to `navigate`, `navigateByUrl` takes a whole URL
* and does not apply any delta to the current one.
*/
navigateByUrl(url, extras = { skipLocationChange: false }) {
if (url instanceof UrlTree) {
return this.scheduleNavigation(url, extras);
}
else {
const urlTree = this.urlSerializer.parse(url);
return this.scheduleNavigation(urlTree, extras);
}
}
/**
* Navigate based on the provided array of commands and a starting point.
* If no starting route is provided, the navigation is absolute.
*
* Returns a promise that:
* - is resolved with 'true' when navigation succeeds
* - is resolved with 'false' when navigation fails
* - is rejected when an error happens
*
* ### Usage
*
* ```
* router.navigate(['team', 33, 'team', '11], {relativeTo: route});
*
* // Navigate without updating the URL
* router.navigate(['team', 33, 'team', '11], {relativeTo: route, skipLocationChange: true });
* ```
*
* In opposite to `navigateByUrl`, `navigate` always takes a delta
* that is applied to the current URL.
*/
navigate(commands, extras = { skipLocationChange: false }) {
return this.scheduleNavigation(this.createUrlTree(commands, extras), extras);
}
/**
* Serializes a {@link UrlTree} into a string.
*/
serializeUrl(url) { return this.urlSerializer.serialize(url); }
/**
* Parse a string into a {@link UrlTree}.
*/
parseUrl(url) { return this.urlSerializer.parse(url); }
/**
* Returns if the url is activated or not.
*/
isActive(url, exact) {
if (url instanceof UrlTree) {
return containsTree(this.currentUrlTree, url, exact);
}
else {
const urlTree = this.urlSerializer.parse(url);
return containsTree(this.currentUrlTree, urlTree, exact);
}
}
scheduleNavigation(url, extras) {
const id = ++this.navigationId;
this.routerEvents.next(new NavigationStart(id, this.serializeUrl(url)));
return Promise.resolve().then((_) => this.runNavigate(url, extras.skipLocationChange, id));
}
setUpLocationChangeListener() {
// Zone.current.wrap is needed because of the issue with RxJS scheduler,
// which does not work properly with zone.js in IE and Safari
this.locationSubscription = this.location.subscribe(Zone.current.wrap((change) => {
const tree = this.urlSerializer.parse(change['url']);
// we fire multiple events for a single URL change
// we should navigate only once
return this.currentUrlTree.toString() !== tree.toString() ?
this.scheduleNavigation(tree, change['pop']) :
null;
}));
}
runNavigate(url, preventPushState, id) {
if (id !== this.navigationId) {
this.location.go(this.urlSerializer.serialize(this.currentUrlTree));
this.routerEvents.next(new NavigationCancel(id, this.serializeUrl(url)));
return Promise.resolve(false);
}
return new Promise((resolvePromise, rejectPromise) => {
let state;
let navigationIsSuccessful;
let preActivation;
let appliedUrl;
const storedState = this.currentRouterState;
const storedUrl = this.currentUrlTree;
applyRedirects(this.injector, this.configLoader, url, this.config)
.mergeMap(u => {
appliedUrl = u;
return recognize(this.rootComponentType, this.config, appliedUrl, this.serializeUrl(appliedUrl));
})
.mergeMap((newRouterStateSnapshot) => {
this.routerEvents.next(new RoutesRecognized(id, this.serializeUrl(url), this.serializeUrl(appliedUrl), newRouterStateSnapshot));
return resolve(this.resolver, newRouterStateSnapshot);
})
.map((routerStateSnapshot) => {
return createRouterState(routerStateSnapshot, this.currentRouterState);
})
.map((newState) => {
state = newState;
preActivation =
new PreActivation(state.snapshot, this.currentRouterState.snapshot, this.injector);
preActivation.traverse(this.outletMap);
})
.mergeMap(_ => {
return preActivation.checkGuards();
})
.mergeMap(shouldActivate => {
if (shouldActivate) {
return preActivation.resolveData().map(() => shouldActivate);
}
else {
return of(shouldActivate);
}
})
.forEach((shouldActivate) => {
if (!shouldActivate || id !== this.navigationId) {
this.routerEvents.next(new NavigationCancel(id, this.serializeUrl(url)));
navigationIsSuccessful = false;
return;
}
this.currentUrlTree = appliedUrl;
this.currentRouterState = state;
new ActivateRoutes(state, storedState).activate(this.outletMap);
if (!preventPushState) {
let path = this.urlSerializer.serialize(appliedUrl);
if (this.location.isCurrentPathEqualTo(path)) {
this.location.replaceState(path);
}
else {
this.location.go(path);
}
}
navigationIsSuccessful = true;
})
.then(() => {
this.navigated = true;
this.routerEvents.next(new NavigationEnd(id, this.serializeUrl(url), this.serializeUrl(appliedUrl)));
resolvePromise(navigationIsSuccessful);
}, e => {
this.currentRouterState = storedState;
this.currentUrlTree = storedUrl;
this.routerEvents.next(new NavigationError(id, this.serializeUrl(url), e));
rejectPromise(e);
});
});
}
} |
JavaScript | class FilterInstances extends Component {
constructor(props) {
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
}
/**
* This function is called everytime an input is given
* (IE key pressed by the user) in the filter text field
*/
handleInputChange(value) {
this.props.onInputChange(value);
}
render() {
return (
<div>
<TextField
onChange={this.handleInputChange}
placeholder="Enter a name..."
label="Search for a room"
id="1" // required by react-md
/>
</div>
);
}
} |
JavaScript | class Arith {
/**
* Returns one of the values passed in, either _value if within _min and _max or the boundary being exceeded by _value
*/
static clamp(_value, _min, _max, _isSmaller = (_value1, _value2) => { return _value1 < _value2; }) {
if (_isSmaller(_value, _min))
return _min;
if (_isSmaller(_max, _value))
return _max;
return _value;
}
} |
JavaScript | class ArithBisection {
/**
* Creates a new Solver
* @param _function A function that takes an argument of the generic type <Parameter> and returns a boolean value.
* @param _divide A function splitting the interval to find a parameter for the next iteration, may simply be the arithmetic mean
* @param _isSmaller A function that determines a difference between the borders of the current interval and compares this to the given precision
*/
constructor(_function, _divide, _isSmaller) {
this.function = _function;
this.divide = _divide;
this.isSmaller = _isSmaller;
}
/**
* Finds a solution with the given precision in the given interval using the functions this Solver was constructed with.
* After the method returns, find the data in this objects properties.
* @param _left The parameter on one side of the interval.
* @param _right The parameter on the other side, may be "smaller" than [[_left]].
* @param _epsilon The desired precision of the solution.
* @param _leftValue The value on the left side of the interval, omit if yet unknown or pass in if known for better performance.
* @param _rightValue The value on the right side of the interval, omit if yet unknown or pass in if known for better performance.
* @throws Error if both sides of the interval return the same value.
*/
solve(_left, _right, _epsilon, _leftValue = undefined, _rightValue = undefined) {
this.left = _left;
this.leftValue = _leftValue || this.function(_left);
this.right = _right;
this.rightValue = _rightValue || this.function(_right);
if (this.isSmaller(_left, _right, _epsilon))
return;
if (this.leftValue == this.rightValue)
throw (new Error("Interval solver can't operate with identical function values on both sides of the interval"));
let between = this.divide(_left, _right);
let betweenValue = this.function(between);
if (betweenValue == this.leftValue)
this.solve(between, this.right, _epsilon, betweenValue, this.rightValue);
else
this.solve(this.left, between, _epsilon, this.leftValue, betweenValue);
}
toString() {
let out = "";
out += `left: ${this.left.toString()} -> ${this.leftValue}`;
out += "\n";
out += `right: ${this.right.toString()} -> ${this.rightValue}`;
return out;
}
} |
JavaScript | class Canvas {
static create(_fillParent = true, _imageRendering = IMAGE_RENDERING.AUTO, _width = 800, _height = 600) {
let canvas = document.createElement("canvas");
canvas.id = "FUDGE";
let style = canvas.style;
style.imageRendering = _imageRendering;
style.width = _width + "px";
style.height = _height + "px";
style.marginBottom = "-0.25em";
if (_fillParent) {
style.width = "100%";
style.height = "100%";
}
return canvas;
}
} |
JavaScript | class NodeSprite extends ƒ.Node {
constructor(_name) {
super(_name);
this.framerate = 12; // animation frames per second, single frames can be shorter or longer based on their timescale
this.frameCurrent = 0;
this.direction = 1;
/**
* Show the next frame of the sequence or start anew when the end or the start was reached, according to the direction of playing
*/
this.showFrameNext = (_event) => {
this.frameCurrent = (this.frameCurrent + this.direction + this.animation.frames.length) % this.animation.frames.length;
this.showFrame(this.frameCurrent);
};
this.cmpMesh = new ƒ.ComponentMesh(NodeSprite.mesh);
// Define coat from the SpriteSheet to use when rendering
this.cmpMaterial = new ƒ.ComponentMaterial(new ƒ.Material(_name, ƒ.ShaderTexture, null));
this.addComponent(this.cmpMesh);
this.addComponent(this.cmpMaterial);
}
static createInternalResource() {
let mesh = new ƒ.MeshSprite("Sprite");
ƒ.Project.deregister(mesh);
return mesh;
}
setAnimation(_animation) {
this.animation = _animation;
if (this.timer)
ƒ.Time.game.deleteTimer(this.timer);
this.showFrame(0);
}
/**
* Show a specific frame of the sequence
*/
showFrame(_index) {
let spriteFrame = this.animation.frames[_index];
this.cmpMesh.mtxPivot = spriteFrame.mtxPivot;
this.cmpMaterial.mtxPivot = spriteFrame.mtxTexture;
this.cmpMaterial.material.setCoat(this.animation.spritesheet);
this.frameCurrent = _index;
this.timer = ƒ.Time.game.setTimer(spriteFrame.timeScale * 1000 / this.framerate, 1, this.showFrameNext);
}
/**
* Sets the direction for animation playback, negativ numbers make it play backwards.
*/
setFrameDirection(_direction) {
this.direction = Math.floor(_direction);
}
} |
JavaScript | class StateMachine {
transit(_next) {
this.instructions.transit(this.stateCurrent, _next, this);
}
act() {
this.instructions.act(this.stateCurrent, this);
}
} |
JavaScript | class StateMachineInstructions extends Map {
/** Define dedicated transition method to transit from one state to another*/
setTransition(_current, _next, _transition) {
let active = this.getStateMethods(_current);
active.transitions.set(_next, _transition);
}
/** Define dedicated action method for a state */
setAction(_current, _action) {
let active = this.getStateMethods(_current);
active.action = _action;
}
/** Default transition method to invoke if no dedicated transition exists, should be overriden in subclass */
transitDefault(_machine) {
//
}
/** Default action method to invoke if no dedicated action exists, should be overriden in subclass */
actDefault(_machine) {
//
}
/** Invoke a dedicated transition method if found for the current and the next state, or the default method */
transit(_current, _next, _machine) {
_machine.stateNext = _next;
try {
let active = this.get(_current);
let transition = active.transitions.get(_next);
transition(_machine);
}
catch (_error) {
// console.info(_error.message);
this.transitDefault(_machine);
}
finally {
_machine.stateCurrent = _next;
_machine.stateNext = undefined;
}
}
/** Invoke the dedicated action method if found for the current state, or the default method */
act(_current, _machine) {
try {
let active = this.get(_current);
active.action(_machine);
}
catch (_error) {
// console.info(_error.message);
this.actDefault(_machine);
}
}
/** Find the instructions dedicated for the current state or create an empty set for it */
getStateMethods(_current) {
let active = this.get(_current);
if (!active) {
active = { action: null, transitions: new Map() };
this.set(_current, active);
}
return active;
}
} |
JavaScript | class AutoYear {
constructor() {
this.yearField = document.querySelector("select[name='transaction.ccexpire']:not(#en__field_transaction_ccexpire)");
this.years = 20;
this.yearLength = 2;
if (this.yearField) {
this.clearFieldOptions();
for (let i = 0; i < this.years; i++) {
const year = new Date().getFullYear() + i;
const newOption = document.createElement("option");
const optionText = document.createTextNode(year.toString());
newOption.appendChild(optionText);
newOption.value =
this.yearLength == 2 ? year.toString().substr(-2) : year.toString();
this.yearField.appendChild(newOption);
}
}
}
clearFieldOptions() {
if (this.yearField) {
this.yearLength =
this.yearField.options[this.yearField.options.length - 1].value.length;
while (this.yearField.options.length > 1) {
this.yearField.remove(1);
}
}
}
} |
JavaScript | class InViewport extends Service {
init() {
super.init(...arguments);
set(this, 'registry', new WeakMap());
let options = assign({
viewportUseRAF: canUseRAF()
}, this._buildOptions());
// set viewportUseIntersectionObserver after merging users config to avoid errors in browsers that lack support (https://github.com/DockYard/ember-in-viewport/issues/146)
options = assign(options, {
viewportUseIntersectionObserver: canUseIntersectionObserver(),
});
setProperties(this, options);
}
startIntersectionObserver() {
this.observerAdmin = new ObserverAdmin();
}
startRAF() {
this.rafAdmin = new RAFAdmin();
}
/** Any strategy **/
/**
* @method watchElement
* @param HTMLElement element
* @param Object configOptions
* @param Function enterCallback - support mixin approach
* @param Function exitCallback - support mixin approach
* @void
*/
watchElement(element, configOptions = {}, enterCallback, exitCallback) {
if (this.viewportUseIntersectionObserver) {
if (!this.observerAdmin) {
this.startIntersectionObserver();
}
const observerOptions = this.buildObserverOptions(configOptions);
schedule('afterRender', this, this.setupIntersectionObserver, element, observerOptions, enterCallback, exitCallback);
} else {
if (!this.rafAdmin) {
this.startRAF();
}
schedule('afterRender', this, this._startRaf, element, configOptions, enterCallback, exitCallback);
}
return {
onEnter: this.addEnterCallback.bind(this, element),
onExit: this.addExitCallback.bind(this, element)
};
}
/**
* @method addEnterCallback
* @void
*/
addEnterCallback(element, enterCallback) {
if (this.viewportUseIntersectionObserver) {
this.observerAdmin.addEnterCallback(element, enterCallback);
} else {
this.rafAdmin.addEnterCallback(element, enterCallback);
}
}
/**
* @method addExitCallback
* @void
*/
addExitCallback(element, exitCallback) {
if (this.viewportUseIntersectionObserver) {
this.observerAdmin.addExitCallback(element, exitCallback);
} else {
this.rafAdmin.addExitCallback(element, exitCallback);
}
}
/** IntersectionObserver **/
/**
* In order to track elements and the state that comes with them, we need to keep track
* of elements in order to get at them at a later time, specifically to unobserve
*
* @method addToRegistry
* @void
*/
addToRegistry(element, observerOptions) {
if (this.registry) {
this.registry.set(element, { observerOptions });
} else {
warn('in-viewport Service has already been destroyed');
}
}
/**
* @method setupIntersectionObserver
* @param HTMLElement element
* @param Object observerOptions
* @param Function enterCallback
* @param Function exitCallback
* @void
*/
setupIntersectionObserver(element, observerOptions, enterCallback, exitCallback) {
if (this.isDestroyed || this.isDestroying) {
return;
}
this.addToRegistry(element, observerOptions);
this.observerAdmin.add(
element,
observerOptions,
enterCallback,
exitCallback
);
}
buildObserverOptions({ intersectionThreshold = 0, scrollableArea = null, viewportTolerance = {} }) {
const domScrollableArea =
typeof scrollableArea === 'string' ? document.querySelector(scrollableArea)
: scrollableArea instanceof HTMLElement ? scrollableArea
: undefined;
// https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
// IntersectionObserver takes either a Document Element or null for `root`
const { top = 0, left = 0, bottom = 0, right = 0 } = viewportTolerance;
return {
root: domScrollableArea,
rootMargin: `${top}px ${right}px ${bottom}px ${left}px`,
threshold: intersectionThreshold
};
}
unobserveIntersectionObserver(target) {
if (!target) {
return;
}
const registeredTarget = this.registry.get(target);
if (typeof registeredTarget === 'object') {
this.observerAdmin.unobserve(
target,
registeredTarget.observerOptions
);
}
}
/** RAF **/
addRAF(elementId, fn) {
this.rafAdmin.add(elementId, fn);
}
removeRAF(elementId) {
if (this.rafAdmin) {
this.rafAdmin.remove(elementId);
}
}
isInViewport(...args) {
return isInViewport(...args);
}
/** other **/
stopWatching(target) {
if (this.observerAdmin) {
this.unobserveIntersectionObserver(target);
}
if (this.rafAdmin) {
this.removeRAF(target);
}
}
willDestroy() {
set(this, 'registry', null);
if (this.observerAdmin) {
this.observerAdmin.destroy();
set(this, 'observerAdmin', null);
}
if (this.rafAdmin) {
this.rafAdmin.reset();
set(this, 'rafAdmin', null);
}
}
_buildOptions(defaultOptions = {}) {
const owner = getOwner(this);
if (owner) {
return assign(defaultOptions, owner.lookup('config:in-viewport'));
}
}
_startRaf(element, configOptions, enterCallback, exitCallback) {
if (this.isDestroyed || this.isDestroying) {
return;
}
enterCallback = enterCallback || noop;
exitCallback = exitCallback || noop;
// this isn't using the same functions as the mixin case, but that is b/c it is a bit harder to unwind.
// So just rewrote it with pure functions for now
startRAF(
element,
configOptions,
enterCallback,
exitCallback,
this.addRAF.bind(this, element.id),
this.removeRAF.bind(this, element.id)
);
}
} |
JavaScript | class ApeClient extends AbstractClient {
constructor(credential, region, profile) {
super("ape.tencentcloudapi.com", "2020-05-13", credential, region, profile);
}
/**
* 分页查询授权人列表
* @param {DescribeAuthUsersRequest} req
* @param {function(string, DescribeAuthUsersResponse):void} cb
* @public
*/
DescribeAuthUsers(req, cb) {
let resp = new DescribeAuthUsersResponse();
this.request("DescribeAuthUsers", req, resp, cb);
}
/**
* 批量获取授权书下载地址
* @param {BatchDescribeOrderCertificateRequest} req
* @param {function(string, BatchDescribeOrderCertificateResponse):void} cb
* @public
*/
BatchDescribeOrderCertificate(req, cb) {
let resp = new BatchDescribeOrderCertificateResponse();
this.request("BatchDescribeOrderCertificate", req, resp, cb);
}
/**
* 根据关键字搜索图片列表
* @param {DescribeImagesRequest} req
* @param {function(string, DescribeImagesResponse):void} cb
* @public
*/
DescribeImages(req, cb) {
let resp = new DescribeImagesResponse();
this.request("DescribeImages", req, resp, cb);
}
/**
* 根据ID查询一张图片的详细信息
* @param {DescribeImageRequest} req
* @param {function(string, DescribeImageResponse):void} cb
* @public
*/
DescribeImage(req, cb) {
let resp = new DescribeImageResponse();
this.request("DescribeImage", req, resp, cb);
}
/**
* 购买一张图片并且支付
* @param {CreateOrderAndPayRequest} req
* @param {function(string, CreateOrderAndPayResponse):void} cb
* @public
*/
CreateOrderAndPay(req, cb) {
let resp = new CreateOrderAndPayResponse();
this.request("CreateOrderAndPay", req, resp, cb);
}
/**
* 批量获取图片下载地址
* @param {BatchDescribeOrderImageRequest} req
* @param {function(string, BatchDescribeOrderImageResponse):void} cb
* @public
*/
BatchDescribeOrderImage(req, cb) {
let resp = new BatchDescribeOrderImageResponse();
this.request("BatchDescribeOrderImage", req, resp, cb);
}
} |
JavaScript | class EnumArrayProperty extends ValueArrayProperty {
/**
* @param {Object} in_params - the parameters
* @param {Number=} [in_params.length=0] the length of the array, if applicable
* @param {Object} in_params._enumDictionary the value<->enum dictonary needed to convert the values
* @constructor
* @protected
* @extends property-properties.ValueArrayProperty
* @alias property-properties.EnumArrayProperty
* @category Arrays
*/
constructor(in_params) {
super({ typeid: 'Enum', ...in_params });
// whenever an EnumProperty is created by the PropertyFactory, we get a
// dictonary [value->enum] and [enum->value] to efficiently lookup
// values/enums for the property.
this._enumDictionary = in_params._enumDictionary;
};
/**
* Since an enum can be identified by its value and its enum string,
* we have to check/convert the type here. We also check if a value
* is suitable for this enum type.
* @param {number|string} in_value value to be checked/converted
* @return {number} internal value for this enum type
*/
_convertEnumToInternalValue(in_value) {
// check if we've got a string
if (_.isString(in_value)) {
var internalEnum = this._enumDictionary.enumEntriesById[in_value];
if (!internalEnum) {
throw new Error(MSG.UNKNOWN_ENUM + in_value);
}
return internalEnum.value;
} else {
if (!this._enumDictionary.enumEntriesByValue[in_value]) {
throw new Error(MSG.UNKNOWN_ENUM + in_value);
} else {
return in_value;
}
}
};
/**
* inserts the content of a given array into the array property
* @param {number} in_offset target index
* @param {Array<*>} in_array the array to be inserted
* @throws if in_array is not an array
* @throws if in_position is not a number
* @throws if a value to be inserted is an instance of BaseProperty
* @throws if tyring to modify a referenced property.
*/
insertRange(in_offset, in_array) {
if (!_.isNumber(in_offset)) {
throw new Error(MSG.NOT_NUMBER + 'in_offset, method: EnumArray.insertRange or .insert');
}
if (!_.isArray(in_array)) {
throw new Error(MSG.IN_ARRAY_NOT_ARRAY + 'EnumArrayProperty.insertRange');
}
var internalValueArray = [];
var that = this;
_.each(in_array, function (element) {
internalValueArray.push(that._convertEnumToInternalValue(element));
});
ValueArrayProperty.prototype.insertRange.call(this, in_offset, internalValueArray);
};
/**
* Sets the content of an enum in an enum array
* @param {number} in_index target index
* @param {*} in_value the value to set
* @throws if in_value is not a string or number
* @throws if in_index is either smaller than zero, larger than the length of the array or not a number.
*/
set(in_index, in_value) {
if (!_.isNumber(in_value) && !_.isString(in_value)) {
throw new Error(MSG.VALUE_STRING_OR_NUMBER + in_value);
}
this.setRange(in_index, [in_value]);
};
/**
* Sets the content of an enum in an enum array. Alternative syntax to .set()
* @param {number} in_index target index
* @param {*} in_value the value to set
* @throws if in_value is not a string or number
* @throws if in_index is either smaller than zero, larger than the length of the array or not a number.
*/
setEnumByString(in_index, in_value) {
this.set(in_index, in_value);
};
/**
* sets the array properties elements to the content of the given array
* all changed elements must already exist
* @param {number} in_offset target start index
* @param {Array<*>} in_array contains the elements to be set
* @throws if in_offset is not a number
* @throws if in_array is not an array
*
*/
setRange(in_offset, in_array) {
if (!_.isNumber(in_offset)) {
throw new Error(MSG.NOT_NUMBER + 'in_offset, method: EnumArray.setRange or .set');
}
if (!_.isArray(in_array)) {
throw new Error(MSG.IN_ARRAY_NOT_ARRAY + 'EnumArrayProperty.setRange');
}
var internalValueArray = [];
var that = this;
_.each(in_array, function (element) {
internalValueArray.push(that._convertEnumToInternalValue(element));
});
ValueArrayProperty.prototype.setRange.call(this, in_offset, internalValueArray);
};
/**
* get the array element at a given index
* @param {number} in_position the target index
* @throws if no entry exists at in_position
* @return {string} the enum string at that index
*/
getEnumString(in_position) {
var internalValue = this._dataArrayRef.getValue(in_position);
var resultEntry = this._enumDictionary.enumEntriesByValue[internalValue];
if (!resultEntry) {
throw new Error(MSG.UNKNOWN_ENUM + internalValue);
} else {
return resultEntry.id;
}
};
/**
* get an array of the enum strings starting at a given index
* @param {number} in_offset the start index
* @param {number} in_length how many should be read
* @throws if in_offset or in_length are not numbers
* @throws if no entry exists at one of the positions
* @return {Array<string>} the enum strings we asked for
*/
getEnumStrings(in_offset, in_length) {
if (!_.isNumber(in_offset)) {
throw new Error(MSG.NOT_NUMBER + 'in_offset, method: EnumArray.getEnumStrings');
}
if (!_.isNumber(in_length)) {
throw new Error(MSG.NOT_NUMBER + 'in_length, method: EnumArray.getEnumStrings');
}
var result = [];
for (var i = 0; i < in_length; i++) {
result.push(this.getEnumString(i + in_offset));
}
return result;
};
/**
* Returns the full property type identifier for the ChangeSet including the enum type id
* @param {boolean} [in_hideCollection=false] - if true the collection type (if applicable) will be omitted
* @return {string} The typeid
*/
getFullTypeid(in_hideCollection = false) {
if (in_hideCollection) {
return TypeIdHelper.createSerializationTypeId(this._typeid, '', true);
} else {
return TypeIdHelper.createSerializationTypeId(this._typeid, 'array', true);
}
};
/**
* @inheritdoc
*/
getValues() {
var result = [];
for (var i = 0; i < this._dataArrayRef.length; i++) {
var child = this._dataArrayRef.getValue(i);
result.push(child);
}
return result;
};
/**
* Creates and initializes the data array
* @param {Number} in_length the initial length of the array
*/
_dataArrayCreate(in_length) {
this._dataArrayRef = new BaseDataArray(Int32Array, in_length);
};
/**
* let the user to query all valid entries of an enum array property
* @return {{}} all valid (string) entries and their (int) values
*/
getValidEnumList() {
return this._enumDictionary.enumEntriesById;
};
} |
JavaScript | class TwingNodeBlockReference extends node_1.TwingNode {
constructor(name, lineno, columnno, tag = null) {
super(new Map(), new Map([['name', name]]), lineno, columnno, tag);
this.type = node_1.TwingNodeType.BLOCK_REFERENCE;
this.TwingNodeOutputInterfaceImpl = this;
}
compile(compiler) {
compiler
.write(`await this.traceableDisplayBlock(${this.getTemplateLine()}, this.getSourceContext())('${this.getAttribute('name')}', context.clone(), blocks);\n`);
}
} |
JavaScript | class ContractAttributeEnum extends AbstractEnum {
static getNiceLabel(key) {
return super.getNiceLabel(`core:enums.ContractAttributeEnum.${key}`);
}
static getHelpBlockLabel(key) {
return super.getNiceLabel(`core:enums.ContractAttributeEnum.helpBlock.${key}`);
}
static findKeyBySymbol(sym) {
return super.findKeyBySymbol(this, sym);
}
static findSymbolByKey(key) {
return super.findSymbolByKey(this, key);
}
static getField(key) {
if (!key) {
return null;
}
const sym = super.findSymbolByKey(this, key);
switch (sym) {
case this.IDENTITY: {
return 'identity';
}
case this.VALID_FROM: {
return 'validFrom';
}
case this.VALID_TILL: {
return 'validTill';
}
case this.WORK_POSITION: {
return 'workPosition';
}
case this.POSITION: {
return 'position';
}
case this.EXTERNE: {
return 'externe';
}
case this.MAIN: {
return 'main';
}
case this.DESCRIPTION: {
return 'description';
}
case this.GUARANTEES: {
return 'guarantees';
}
case this.POSITIONS: {
return 'positions';
}
case this.STATE: {
return 'state';
}
default: {
return null;
}
}
}
static getEnum(field) {
if (!field) {
return null;
}
switch (field) {
case 'identity': {
return this.IDENTITY;
}
case 'validFrom': {
return this.VALID_FROM;
}
case 'validTill': {
return this.VALID_TILL;
}
case 'workPosition': {
return this.WORK_POSITION;
}
case 'position': {
return this.POSITION;
}
case 'externe': {
return this.EXTERNE;
}
case 'main': {
return this.MAIN;
}
case 'description': {
return this.DESCRIPTION;
}
case 'disabled': {
return this.DISABLED;
}
case 'guarantees': {
return this.GUARANTEES;
}
case 'positions': {
return this.POSITIONS;
}
case 'state': {
return this.STATE;
}
default: {
return null;
}
}
}
static getLevel(key) {
if (!key) {
return null;
}
const sym = super.findSymbolByKey(this, key);
switch (sym) {
default: {
return 'default';
}
}
}
} |
JavaScript | class AdapterForceTouch extends Adapter {
constructor(el, block, options) {
super(el, block, options);
}
bindEvents() {
this.add('webkitmouseforcewillbegin', this._startPress.bind(this));
this.add('mousedown', this.support.bind(this));
this.add('webkitmouseforcechanged', this.change.bind(this));
this.add('webkitmouseforcedown', this._startDeepPress.bind(this));
this.add('webkitmouseforceup', this._endDeepPress.bind(this));
this.add('mouseleave', this._endPress.bind(this));
this.add('mouseup', this._endPress.bind(this));
}
support(event) {
if(this.isPressed() === false) {
this.fail(event, this.runKey);
}
}
change(event) {
if(this.isPressed() && event.webkitForce > 0) {
this._changePress(this.normalizeForce(event.webkitForce), event);
}
}
// make the force the standard 0 to 1 scale and not the 1 to 3 scale
normalizeForce(force) {
return this.reachOne(map(force, 1, 3, 0, 1));
}
// if the force value is above 0.995 set the force to 1
reachOne(force) {
return force > 0.995 ? 1 : force;
}
} |
JavaScript | class Budge {
constructor() {
this.budgetUser = Number(budgetUser);
this.remaining = Number(budgetUser);
this.expenditure = Number(accumulatedExpense);
}
bundgetRemaining(quantity = 0) {
this.BundgetExpense(quantity);
return (this.remaining -= Number(quantity));
}
BundgetExpense() {
return (this.accumulatedExpense =
Number(this.budgetUser) - Number(this.reimaining));
}
} |
JavaScript | class Interfase {
insertBudget(quantity) {
const budgetUi = document.querySelector("span#total");
const remainingUi = document.querySelector("span#restante");
const accumulatedExpenses = document.querySelector("span#Expense");
//insertHtml
quantity = quantity.toFixed(2);
budgetUi.innerHTML = `$${quantity}`;
remainingUi.innerHTML = `$${quantity}`;
accumulatedExpenses.innerHTML = `$${accumulatedExpense}`;
}
printMessage(message, type) {
const divMessage = document.createElement("div");
divMessage.classList.add("text-center", "alert");
if (type === "error") {
divMessage.classList.add("alert-danger");
} else {
divMessage.classList.add("alert-success");
}
divMessage.appendChild(document.createTextNode(message));
//insetDOM
document.querySelector(".primario").insertBefore(divMessage, form);
//timer Out message
setTimeout(() => {
document.querySelector(".primario .alert").remove();
form.reset();
}, 3000);
}
//inset spending in Html
addSpending(day, hours = "10:00PM", name, quantity) {
const listSpending = document.querySelector("#dayOne");
const cardEmpty = document.querySelector(".empty").remove();
//create element
const div = document.createElement("div");
div.classList = "spending shadowBox card p-3 mt-0";
div.innerHTML = `
<div class="info">
<h3>${name}</h3>
<span class="badge badge-pill badge-primary">$${quantity}</span>
</div>
<div class="text-right hour">
<span>${hours}</span>
</div>
`;
listSpending.appendChild(div);
}
//update remaining
remainingBudget(quantity) {
const reimaining = document.querySelector("span#restante");
const expenditure = document.querySelector("span#Expense");
//update remaining ub logic
const reimainingUi = QuantityBudget.bundgetRemaining(quantity);
const expenditureUi = QuantityBudget.BundgetExpense();
//update html
reimaining.innerHTML = `${reimainingUi}`;
expenditure.innerHTML = `${expenditureUi}`;
//this.checkBundget();
}
//change color remaining
checkBundget() {
const bundgetTotal = QuantityBudget.budgetUser;
const bundgetRemaining = QuantityBudget.remaining;
const remainingUi = document.querySelector(".restante");
let quarter = bundgetTotal / 4;
let half = bundgetTotal / 2;
//25%
if (quarter > bundgetRemaining) {
remainingUi.classList.remove("alert-success", "alert-warning");
remainingUi.classList.add("alert-danger");
} else if (half > bundgetRemaining) {
remainingUi.classList.remove("alert-success");
remainingUi.classList.add("alert-warning");
}
}
} |
JavaScript | class Surface {
/**
* Static config method. Object returned defines the default properties of the class. This
* also defines the properties that may be passed to the class constructor.
*
* @returns {{id: string, xmlns: string, xmlnsEv: string, xmlnsXlink: string, zoomAndPan: string, coorWidth: string, coorHeight: string, hook: HTMLElement, autoBind: boolean, children: Array}}
*/
config() {
return {
id: 'surface1',
xmlns: Util.xmlNamespaces().xmlns,
xmlnsEv: Util.xmlNamespaces().xmlnsEv,
xmlnsXlink: Util.xmlNamespaces().xmlnsXLink,
zoomAndPan: "disabled",
width: '100%',
height: '500px',
hook: window.document.body,
autoBind: false,
children: [],
onLoad: null
};
}
/**
* Class constructor.
*
* @param config
*/
constructor(config) {
this._id = config && config.hasOwnProperty('id') ? config.id : this.config().id;
this._xmlns = config && config.hasOwnProperty('xmlns') ? config.xmlns : this.config().xmlns;
this._xmlnsXlink = config && config.hasOwnProperty('xmlnsXlink') ? config.xmlnsXlink : this.config().xmlnsXlink;
this._xmlnsEv = config && config.hasOwnProperty('xmlnsEv') ? config.xmlnsEv : this.config().xmlnsEv;
this._hook = config && config.hasOwnProperty('hook') ? config.hook : this.config().hook;
this._autoBind = config && config.hasOwnProperty('autoBind') ? config.autoBind : this.config().autoBind;
this._zoomAndPan = config && config.hasOwnProperty('zoomAndPan') ? config.zoomAndPan : this.config().zoomAndPan;
this._coorWidth = config && config.hasOwnProperty('width') ? config.width : this.config().width;
this._coorHeight = config && config.hasOwnProperty('height') ? config.height : this.config().height;
this._onLoad = config && config.hasOwnProperty('onLoad') ? config.onLoad : this.config().onLoad;
this._children = config && config.hasOwnProperty('children') ? config.children : this.config().children;
this.init();
}
/**
* Horizontal length in the svg coordinate system.
*
* See `MDN > Web technology for developers > SVG > SVG Attribute reference > `
* [width](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/width).
*
* @returns {string}
*/
get coorWidth() {
return this._coorWidth;
}
/**
* Vertical length in the user coordinate system.
*
* See `MDN > Web technology for developers > SVG > SVG Attribute reference > `
* [height](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/height).
*
* @returns {string|*}
*/
get coorHeight() {
return this._coorHeight;
}
/**
* The namespace uri attribute of the svg doc element.
*
* See [http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/glossary.html#dt-namespaceURI].
*
* @returns {string}
*/
get xmlns() {
return this._xmlns;
}
get xmlnsXlink() {
return this._xmlnsXlink;
}
get xmlnsEv() {
return this._xmlnsEv;
}
get docElementNS() {
return this._docElementNS;
}
get hook() {
return this._hook;
}
get autoBind() {
return this._autoBind;
}
get zoomAndPan() {
return this._zoomAndPan;
}
get onLoad() {
return this._onLoad;
}
get group() {
return this._group;
}
/**
* Getter for children collection.
* @returns {*}
*/
get children() {
return this._children;
}
/**
* Method used to append the docElement to configured hook element.
*/
bind() {
if (this.hook) {
this.hook.appendChild(this.docElementNS);
}
}
/**
* Method called by the constructor to create and assign docElement based
* on the properties exposed by the class.
*
* Note - if the autoBind flag is true, then it ends by invoking bind method.
*/
init() {
var me = this,
svg = document.createElementNS(this.xmlns, 'svg');
svg.setAttribute('id', 'surface1');
svg.setAttribute('width', this.coorWidth);
svg.setAttribute('height', this.coorHeight);
svg.setAttribute('zoomAndPan', this.zoomAndPan);
if (this.onload) {
svg.setAttribute('onload', this.onLoad);
}
me._docElementNS = svg;
if (this.children.length > 0) {
for (var i=0; i < this.children.length; i++) {
var child = this.children[i];
if (child.docElementNS) {
this.docElementNS.appendChild(child.docElementNS);
}
}
}
if (me.autoBind) {
me.bind();
}
}
} |
JavaScript | class ListNode {
constructor (val) {
this.val = val;
this.next = null;
}
} |
JavaScript | class ExampleApp extends KraGL.app.Application {
/**
* @inheritdoc
*/
constructor(opts) {
super(opts);
// TODO
}
/**
* @inheritdoc
*/
clean() {
// TODO
return Promise.resolve()
.then(() => {
this.shaderLib.clean();
});
}
/**
* @inheritdoc
*/
initResources() {
return Promise.resolve();
}
/**
* @inheritdoc
*/
initWebGLResources() {
return Promise.resolve()
.then(() => {
return this.shaderLib.createPrograms({
'simple': {
shaders: {
frag: {
urls: ['./shaders/frag.glsl']
},
vert: {
urls: ['./shaders/vert.glsl']
}
},
attributeGetters: {
position: 'xyz'
}
}
})
.then(() => {
this.shaderLib.enable('simple');
});
})
.then(() => {
this.meshLib.add('tri1', new Mesh({
vertices: [
{ xyz: [0, 0, 0] },
{ xyz: [1, 0, 0] },
{ xyz: [0, 1, 0] }
],
indices: [0, 1, 2]
}));
});
}
/**
* @inheritdoc
*/
render() {
// Clear black by default.
Canvas.clear(this.gl);
this.shaderLib.enable('simple');
// Draw a white triangle.
this.meshLib.get('tri1').render(this);
}
/**
* @inheritdoc
*/
update() {
// Nothing too interesting here. Just write the current framerate to the
// console.
console.log(this.fps.toFixed(1));
}
} |
JavaScript | class JsonParser{
// functional json parse
// @param str string to parse
// @param callback callback function (err:Error, json:Object):void
static parse(str, callback){
// prepare to store json
let json;
// attempt json parse
try{
json = JSON.parse(str);
}
catch(err){
// parse error - callback
callback(err, null);
return;
}
// got json - callback
callback(null, json);
}
// functional json stringify
// @param object json object to stringify
// @param callback callback function (err:Error, str:String):void
// @param pretty boolean for pretty json output
static stringify(object, callback, pretty=false){
// prepare to store string
let str;
// attempt to serialize json to string
try{
str = pretty ? JSON.stringify(object, null, 4) : JSON.stringify(object);
}
catch(err){
// parse error - callback
callback(err, null);
return;
}
// got string - callback
callback(null, str);
}
// function json stringify with pretty output (4 space tabs)
// @param object json object to stringify
// @param callback callback function
static stringifyPretty(object, callback){
return this.stringify(object, callback, true);
}
} |
JavaScript | class MessagingPlan extends models['TrackedResource'] {
/**
* Create a MessagingPlan.
* @property {number} [sku] Sku type
* @property {number} [selectedEventHubUnit] Selected event hub unit
* @property {date} [updatedAt] The exact time the messaging plan was
* updated.
* @property {number} [revision] revision number
*/
constructor() {
super();
}
/**
* Defines the metadata of MessagingPlan
*
* @returns {object} metadata of MessagingPlan
*
*/
mapper() {
return {
required: false,
serializedName: 'MessagingPlan',
type: {
name: 'Composite',
className: 'MessagingPlan',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
location: {
required: false,
serializedName: 'location',
type: {
name: 'String'
}
},
tags: {
required: false,
serializedName: 'tags',
type: {
name: 'Dictionary',
value: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
sku: {
required: false,
readOnly: true,
serializedName: 'properties.sku',
type: {
name: 'Number'
}
},
selectedEventHubUnit: {
required: false,
readOnly: true,
serializedName: 'properties.selectedEventHubUnit',
type: {
name: 'Number'
}
},
updatedAt: {
required: false,
readOnly: true,
serializedName: 'properties.updatedAt',
type: {
name: 'DateTime'
}
},
revision: {
required: false,
readOnly: true,
serializedName: 'properties.revision',
type: {
name: 'Number'
}
}
}
}
};
}
} |
JavaScript | class ErrorBuffer {
constructor() {
this.errors = [];
}
/**
* Adds the given error(s) (or other objects, which are converted to errors).
*/
add(...errors) {
for (let error of errors) {
if (error instanceof verror_1.MultiError)
this.add(...error.errors());
else {
if (!(error instanceof Error))
error = new Error(String(error));
else if (this.errors.indexOf(error) !== -1) {
/* Deduplicate errors.
*
* Consider this scenario:
* 1. Promise A is started.
* 2. Promise B is started. It awaits the result of A.
* 3. Promise C is started. It also awaits the result of A.
* 4. PromiseEach is called, to collect the results of promises B and C.
* 5. Promise A rejects with error E.
* 6. Promise B, previously waiting on A, rejects with E.
* 7. Promise C, previously waiting on A, also rejects with E.
* 8. PromiseEach collects the results of [B, C]. They are { B: rejection(E), C: rejection(E) }.
* 9. PromiseEach finds that B rejected with E, so it adds E to its ErrorBuffer.
* 10. PromiseEach finds that C rejected with E, so it adds E to its ErrorBuffer.
* 11. PromiseEach rejects with [E, E].
*
* But, if ErrorBuffer deduplicates the errors it receives, then step 10 has no effect, because E is already in the ErrorBuffer. As a result, in step 11, PromiseEach rejects with E instead of [E, E].
*
* Note that this deduplication only applies to instances of Error. When other values are passed in, they are converted to a new instance of Error each time, so there is no chance to deduplicate them.
*/
continue;
}
this.errors.push(error);
}
}
}
/**
* Adds the given error, then throws it. If other errors have been added already, throws a `MultiError` instead.
*/
throw(error) {
const throwSingle = !this.errors.length;
this.add(error);
throw throwSingle ? error : format_verror_1.PrettyVError.errorFromList(this.errors);
}
/**
* Catches errors thrown from the given function, adding them to the array of accumulated errors.
*/
catching(fun) {
try {
return fun();
}
catch (e) {
this.add(e);
}
}
/**
* Catches errors thrown from the given async function or promise, adding them to the array of accumulated errors.
*/
async catchingAsync(fun) {
try {
if (typeof fun === "function")
return await fun();
else
return await fun;
}
catch (e) {
this.add(e);
}
}
/**
* Throws any accumulated errors.
*/
check() {
const error = format_verror_1.PrettyVError.errorFromList(this.errors);
if (error)
throw error;
}
get isEmpty() {
return !this.errors.length;
}
} |
JavaScript | class TableColumnResize extends Plugin {
/**
* @inheritDoc
*/
static get requires() {
return [ TableColumnResizeEditing ];
}
/**
* @inheritDoc
*/
static get pluginName() {
return 'TableColumnResize';
}
} |
JavaScript | class Box2dworld {
constructor() {
this.stepCount = 0;
this.world = undefined;
}
async init() {
//此处Box2dFactory必须要先运行才能调用Box2D.b2Vec2
//window 对象表示当前窗口
window.Box2D = await Box2DFactory();
const gravity = new Box2D.b2Vec2(0, 10);
this.world = new Box2D.b2World(gravity);
}
step(deltaTime, vIter, pIter) {
const current = Date.now();
this.world.Step(deltaTime, vIter, pIter)
const stepCalcTime = (Date.now() - current);
this.stepCount++;
if (this.stepCount % 90 === 0) {
console.log(`t: ${stepCalcTime}, n: ${this.world.GetBodyCount()}`)
}
}
getworld() {
return this.world;
}
} |
JavaScript | class WxCrossScale {
/**
* @constructor
* @param {WxScale} xScale - x-Axis instance
* @param {WxScale} yScale - y-Axis instance
* @param {Object} [config]
*/
constructor(xScale, yScale, config) {
if (!xScale instanceof WxScale && !yScale instanceof WxScale) {
throw new Error('Should be an WxScale instance');
}
let me = this;
me.xScale = xScale;
me.yScale = yScale;
me.config = extend(true, {}, WX_CROSSSCALE_CONFIG, config);
}
/**
* Draw a cross scale
*/
draw(area, xScaleDatasets, yScaleDatasets) {
let me = this, {xMargin, xFirstPointSpace} = me.config;
me.yScale.init(yScaleDatasets);
let yBox = me.yScale.calculateBox(area, yScaleDatasets);
me.xScale.init(xScaleDatasets);
let xBox = me.xScale.calculateBox(area, xScaleDatasets);
// Y-Base
let yMHeight = xBox.outerHeight - xBox.marginTB - me.xScale.lineSpace;
//yBox.y = yBox.y + yMHeight*2;
me.yScale.config.fixPadding = yMHeight * 2;
// Adjust X-BOX
let xMWidth = yBox.outerWidth - yBox.marginLR - me.yScale.lineSpace;
let xOffset = xMWidth - me.xScale.fixPadding / 2;
let xlineWidth = me.xScale.config.ticks.lineWidth || 1;
let xExtendLeft;
if (xFirstPointSpace === 'auto') {
yScaleDatasets[yScaleDatasets.length - 1].text = '';
xExtendLeft = me.xScale.config.extendLeft || Math.min(xBox.width / 10, me.xScale.calculateTickWidth(xScaleDatasets, xBox) / xScaleDatasets.length);
} else if (xFirstPointSpace === 0) {
// Zero y-space; The first point of Y will overlap the last point of X, so remove the last point of X
yScaleDatasets[yScaleDatasets.length - 1].text = '';
xExtendLeft = 0;
} else if (is.Function(xFirstPointSpace)) {
xExtendLeft = xFirstPointSpace(xBox, yBox, area, me.xScale, me.yScale, xScaleDatasets, yScaleDatasets);
} else {
xExtendLeft = parseFloat(xFirstPointSpace);
}
if (xExtendLeft) {
xOffset -= xlineWidth *2;
} else {
xOffset -= xlineWidth;
}
xOffset += xExtendLeft;
let xAxisXPoint = area.x + xOffset;
if (is.Function(xMargin)) {
xMargin = xMargin(xBox, yBox, area, me.xScale, me.yScale, xScaleDatasets, yScaleDatasets);
} else if (!xMargin || !is.Number(xMargin)) {
xMargin = 0;
}
let calXbox = new BoxInstance(xBox.position, xAxisXPoint, xBox.y, xBox.width - xOffset - xMargin, xBox.height, xBox.outerWidth - xOffset, xBox.outerHeight);
me.yScale.setBox(yBox, false);
me.yScale.update(yScaleDatasets);
me.xScale.setBox(calXbox, false);
me.xScale.config.extendLeft = xExtendLeft;
me.xScale.update(xScaleDatasets);
me.xBox = calXbox;
me.yBox = yBox;
return {xBox: calXbox, yBox: yBox};
}
} |
JavaScript | class Connection extends ConnectionBase {
constructor() {
super();
this._internal = ConnectionInternal(this.getMarketState(), this._getInstance());
}
_connect(webSocketAdapterFactory) {
this._internal.connect(this.getServer(), this.getUsername(), this.getPassword(), webSocketAdapterFactory === null ? new WebSocketAdapterFactoryForBrowsers() : webSocketAdapterFactory);
}
_disconnect() {
this._internal.disconnect();
}
_pause() {
this._internal.pause();
}
_resume() {
this._internal.resume();
}
_on() {
this._internal.on.apply(this._internal, arguments);
}
_off() {
this._internal.off.apply(this._internal, arguments);
}
_getActiveSymbolCount() {
return this._internal.getProducerSymbolCount();
}
_onPollingFrequencyChanged(pollingFrequency) {
return this._internal.setPollingFrequency(pollingFrequency);
}
_handleProfileRequest(symbol) {
this._internal.handleProfileRequest(symbol);
}
toString() {
return `[Connection (instance=${this._getInstance()})]`;
}
} |
JavaScript | class ConnectionBase {
constructor() {
this._server = null;
this._username = null;
this._password = null;
this._marketState = new MarketState(symbol => this._handleProfileRequest(symbol));
this._pollingFrequency = null;
this._instance = ++instanceCounter;
}
/**
* Connects to the given server with username and password.
*
* @public
* @param {string} server
* @param {string} username
* @param {string} password
* @param {WebSocketAdapterFactory=} webSocketAdapterFactory
*/
connect(server, username, password, webSocketAdapterFactory) {
this._server = server;
this._username = username;
this._password = password;
this._connect(webSocketAdapterFactory || null);
}
/**
* @protected
* @param {WebSocketAdapterFactory=} webSocketAdapterFactory
* @ignore
*/
_connect(webSocketAdapterFactory) {
return;
}
/**
* Forces a disconnect from the server.
*
* @public
*/
disconnect() {
this._server = null;
this._username = null;
this._password = null;
this._disconnect();
}
/**
* @protected
* @ignore
*/
_disconnect() {
return;
}
/**
* Causes the market state to stop updating. All subscriptions are maintained.
*
* @public
*/
pause() {
this._pause();
}
/**
* @protected
* @ignore
*/
_pause() {
return;
}
/**
* Causes the market state to begin updating again (after {@link ConnectionBase#pause} has been called).
*
* @public
*/
resume() {
this._resume();
}
/**
* @protected
* @ignore
*/
_resume() {
return;
}
/**
* Initiates a subscription to an {@link Subscription.EventType} and
* registers the callback for notifications.
*
* @public
* @param {Subscription.EventType} eventType
* @param {function} callback - notified each time the event occurs
* @param {String=} symbol - A symbol, if applicable, to the given {@link Subscription.EventType}
*/
on() {
this._on.apply(this, arguments);
}
/**
* @protected
* @ignore
*/
_on() {
return;
}
/**
* Stops notification of the callback for the {@link Subscription.EventType}.
* See {@link ConnectionBase#on}.
*
* @public
* @param {Subscription.EventType} eventType - the {@link Subscription.EventType} which was passed to {@link ConnectionBase#on}
* @param {function} callback - the callback which was passed to {@link ConnectionBase#on}
* @param {String=} symbol - A symbol, if applicable, to the given {@link Subscription.EventType}
*/
off() {
this._off.apply(this, arguments);
}
/**
* @protected
* @ignore
*/
_off() {
return;
}
getActiveSymbolCount() {
return this._getActiveSymbolCount();
}
_getActiveSymbolCount() {
return null;
}
/**
* The frequency, in milliseconds, used to poll for changes to {@link Quote}
* objects. A null value indicates streaming updates (default).
*
* @public
* @returns {number|null}
*/
getPollingFrequency() {
return this._pollingFrequency;
}
/**
* Sets the polling frequency, in milliseconds. A null value indicates
* streaming market updates (where polling is not used).
*
* @public
* @param {number|null} pollingFrequency
*/
setPollingFrequency(pollingFrequency) {
if (this._pollingFrequency !== pollingFrequency) {
if (pollingFrequency && pollingFrequency > 0) {
this._pollingFrequency = pollingFrequency;
} else {
this._pollingFrequency = null;
}
this._onPollingFrequencyChanged(this._pollingFrequency);
}
}
/**
* @protected
* @ignore
*/
_onPollingFrequencyChanged(pollingFrequency) {
return;
}
/**
* @protected
* @ignore
*/
_handleProfileRequest(symbol) {
return;
}
/**
* Returns the {@link MarketState} singleton, used to access {@link Quote},
* {@link Profile}, and {@link CumulativeVolume} objects.
*
* @returns {MarketState}
*/
getMarketState() {
return this._marketState;
}
/**
* @public
* @returns {null|string}
*/
getServer() {
return this._server;
}
/**
* @public
* @returns {null|string}
*/
getPassword() {
return this._password;
}
/**
* @public
* @returns {null|string}
*/
getUsername() {
return this._username;
}
/**
* Get an unique identifier for the current instance.
*
* @protected
* @returns {Number}
*/
_getInstance() {
return this._instance;
}
toString() {
return `[ConnectionBase (instance=${this._instance}]`;
}
} |
JavaScript | class WebSocketAdapter {
constructor(host) {}
get CONNECTING() {
return null;
}
get OPEN() {
return null;
}
get CLOSING() {
return null;
}
get CLOSED() {
return null;
}
get binaryType() {
return null;
}
set binaryType(value) {
return;
}
get readyState() {
return null;
}
set readyState(value) {
return;
}
get onopen() {
return null;
}
set onopen(callback) {
return;
}
get onclose() {
return null;
}
set onclose(callback) {
return;
}
get onmessage() {
return null;
}
set onmessage(callback) {
return;
}
send(message) {
return;
}
close() {
return;
}
getDecoder() {
return null;
}
toString() {
return '[WebSocketAdapter]';
}
} |
JavaScript | class WebSocketAdapterFactory {
constructor() {}
/**
* Returns a new {@link WebSocketAdapter} instance.
*
* @public
* @param {String} host
* @returns {null}
*/
build(host) {
return null;
}
toString() {
return '[WebSocketAdapterFactory]';
}
} |
JavaScript | class WebSocketAdapterFactoryForBrowsers extends WebSocketAdapterFactory {
constructor() {
super();
this._logger = LoggerFactory.getLogger('@barchart/marketdata-api-js');
}
build(host) {
if (!__window || !__window.WebSocket) {
this._logger.warn('Connection: Unable to connect, WebSockets are not supported.');
return;
}
return new WebSocketAdapterForBrowsers(host);
}
toString() {
return '[WebSocketAdapterFactoryForBrowsers]';
}
} |
JavaScript | class WebSocketAdapterForBrowsers extends WebSocketAdapter {
constructor(host) {
super(host);
this._socket = new WebSocket(host);
}
get CONNECTING() {
return WebSocket.CONNECTING;
}
get OPEN() {
return WebSocket.OPEN;
}
get CLOSING() {
return WebSocket.CLOSING;
}
get CLOSED() {
return WebSocket.CLOSED;
}
get binaryType() {
return this._socket.binaryType;
}
set binaryType(value) {
this._socket.binaryType = value;
}
get readyState() {
return this._socket.readyState;
}
set readyState(value) {
this._socket.readyState = value;
}
get onopen() {
return this._socket.onopen;
}
set onopen(callback) {
this._socket.onopen = callback;
}
get onclose() {
return this._socket.onclose;
}
set onclose(callback) {
this._socket.onclose = callback;
}
get onmessage() {
return this._socket.onmessage;
}
set onmessage(callback) {
this._socket.onmessage = callback;
}
send(message) {
this._socket.send(message);
}
close() {
this._socket.close();
}
getDecoder() {
let decoder;
if (__window) {
decoder = new __window.TextDecoder();
} else {
decoder = {
decode: data => String.fromCharCode.apply(null, new Uint8Array(data))
};
}
return decoder;
}
toString() {
return '[WebSocketAdapterForBrowsers]';
}
} |
JavaScript | class Logger {
constructor() {}
/**
* Writes a log message.
*
* @public
*/
log() {
return;
}
/**
* Writes a log message, at "trace" level.
*
* @public
*/
trace() {
return;
}
/**
* Writes a log message, at "debug" level.
*
* @public
*/
debug() {
return;
}
/**
* Writes a log message, at "info" level.
*
* @public
*/
info() {
return;
}
/**
* Writes a log message, at "warn" level.
*
* @public
*/
warn() {
return;
}
/**
* Writes a log message, at "error" level.
*
* @public
*/
error() {
return;
}
toString() {
return '[Logger]';
}
} |
JavaScript | class LoggerFactory {
constructor() {}
/**
* Configures the library to write log messages to the console.
*
* @public
* @static
*/
static configureForConsole() {
LoggerFactory.configure(new ConsoleLoggerProvider());
}
/**
* Configures the mute all log messages.
*
* @public
* @static
*/
static configureForSilence() {
LoggerFactory.configure(new EmptyLoggerProvider());
}
/**
* Configures the library to delegate any log messages to a custom
* implementation of the {@link LoggerProvider} interface.
*
* @public
* @static
* @param {LoggerProvider} provider
*/
static configure(provider) {
if (__provider === null && provider instanceof LoggerProvider) {
__provider = provider;
}
}
/**
* Returns an instance of {@link Logger} for a specific category.
*
* @public
* @static
* @param {String} category
* @return {Logger}
*/
static getLogger(category) {
if (__provider === null) {
LoggerFactory.configureForConsole();
}
return __provider.getLogger(category);
}
toString() {
return '[LoggerFactory]';
}
} |
JavaScript | class LoggerProvider {
constructor() {}
/**
* Returns an instance of {@link Logger}.
*
* @public
* @param {String} category
* @returns {Logger}
*/
getLogger(category) {
return null;
}
toString() {
return '[LoggerProvider]';
}
} |
JavaScript | class CumulativeVolume {
constructor(symbol, tickIncrement) {
/**
* @property {string} symbol
*/
this.symbol = symbol;
this._tickIncrement = tickIncrement;
this._handlers = [];
this._priceLevels = {};
this._highPrice = null;
this._lowPrice = null;
if (__logger === null) {
__logger = LoggerFactory.getLogger('@barchart/marketdata-api-js');
}
}
/**
* Registers an event handler for a given event. The following events are
* supported:
*
* update -- when a new price level is added, or an existing price level mutates.
* reset -- when all price levels are cleared.
*
* @ignore
* @param {string} eventType
* @param {function} handler - callback notified each time the event occurs
*/
on(eventType, handler) {
if (eventType !== 'events') {
return;
}
const i = this._handlers.indexOf(handler);
if (i < 0) {
const copy = this._handlers.slice(0);
copy.push(handler);
this._handlers = copy;
this.toArray().forEach(priceLevel => {
sendPriceVolumeUpdate(this, handler, priceLevel);
});
}
}
/**
* Unregisters an event handler for a given event. See {@link CumulativeVolume#on}.
*
* @ignore
* @param {string} eventType - the event which was passed to {@link CumulativeVolume#on}
* @param {function} handler - the callback which was passed to {@link CumulativeVolume#on}
*/
off(eventType, handler) {
if (eventType !== 'events') {
return;
}
const i = this._handlers.indexOf(handler);
if (!(i < 0)) {
const copy = this._handlers.slice(0);
copy.splice(i, 1);
this._handlers = copy;
}
}
/**
* @ignore
*/
getTickIncrement() {
return this._tickIncrement;
}
/**
* Given a numeric price, returns the volume traded at that price level.
*
* @public
* @param {number} price
* @returns {number}
*/
getVolume(price) {
const priceString = price.toString();
const priceLevel = this._priceLevels[priceString];
if (priceLevel) {
return priceLevel.volume;
} else {
return 0;
}
}
/**
* Increments the volume at a given price level. Used primarily
* when a trade occurs.
*
* @ignore
* @param {number} price
* @param {number} volume - amount to add to existing cumulative volume
*/
incrementVolume(price, volume) {
if (this._highPrice && this._lowPrice) {
if (price > this._highPrice) {
for (let p = this._highPrice + this._tickIncrement; p < price; p += this._tickIncrement) {
broadcastPriceVolumeUpdate(this, this._handlers, addPriceVolume(this._priceLevels, p.toString(), p));
}
this._highPrice = price;
} else if (price < this._lowPrice) {
for (let p = this._lowPrice - this._tickIncrement; p > price; p -= this._tickIncrement) {
broadcastPriceVolumeUpdate(this, this._handlers, addPriceVolume(this._priceLevels, p.toString(), p));
}
this._lowPrice = price;
}
} else {
this._lowPrice = this._highPrice = price;
}
let priceString = price.toString();
let priceLevel = this._priceLevels[priceString];
if (!priceLevel) {
priceLevel = addPriceVolume(this._priceLevels, priceString, price);
}
priceLevel.volume += volume;
broadcastPriceVolumeUpdate(this, this._handlers, priceLevel);
}
/**
* Clears the data structure. Used primarily when a "reset" message
* is received.
*
* @ignore
*/
reset() {
this._priceLevels = {};
this._highPrice = null;
this._lowPrice = null;
this._handlers.forEach(handler => {
handler({
container: this,
event: events.reset
});
});
}
/**
* Returns an array of all price levels. This is an expensive operation. Observing
* an ongoing subscription is preferred (see {@link Connection#on}).
*
* @return {PriceLevel[]}
*/
toArray() {
const array = object.keys(this._priceLevels).map(p => {
const priceLevel = this._priceLevels[p];
return {
price: priceLevel.price,
volume: priceLevel.volume
};
});
array.sort((a, b) => {
return a.price - b.price;
});
return array;
}
dispose() {
this._priceLevels = {};
this._highPrice = null;
this._lowPrice = null;
this._handlers = [];
}
/**
* Copies the price levels from one {@link CumulativeVolume} instance to
* a newly {@link CumulativeVolume} created instance.
*
* @ignore
* @param {string} symbol - The symbol to assign to the cloned instance.
* @param {CumulativeVolume} source - The instance to copy.
* @return {CumulativeVolume}
*/
static clone(symbol, source) {
const clone = new CumulativeVolume(symbol, source.getTickIncrement());
source.toArray().forEach(priceLevel => {
clone.incrementVolume(priceLevel.price, priceLevel.volume);
});
return clone;
}
toString() {
return `[CumulativeVolume (symbol=${this.symbol})]`;
}
} |
JavaScript | class Exchange {
constructor(id, name, timezoneDdf, timezoneExchange) {
/**
* @property {string} id - the code used to identify the exchange
*/
this.id = id;
/**
* @property {string} name - the name of the exchange
*/
this.name = name;
/**
* @property {string|null} timezoneDdf - the timezone used by DDF for this exchange (should conform to a TZ database name)
*/
this.timezoneDdf = null;
/**
* @property {number|null} offsetDdf - the UTC offset, in milliseconds, for DDF purposes.
*/
this.offsetDdf = null;
/**
* @property {string} timezoneLocal - the actual timezone of the exchange (should conform to a TZ database name)
*/
this.timezoneExchange = null;
/**
* @property {number} offsetExchange -- the UTC offset, in milliseconds, of the exchange's local time.
*/
this.offsetExchange = null;
const tzDdf = Timezones.parse(timezoneDdf);
const txExchange = Timezones.parse(timezoneExchange);
if (tzDdf !== null) {
this.timezoneDdf = tzDdf.code;
this.offsetDdf = tzDdf.getUtcOffset(null, true);
}
if (txExchange !== null) {
this.timezoneExchange = txExchange.code;
this.offsetExchange = txExchange.getUtcOffset(null, true);
}
}
toString() {
return `[Exchange (id=${this.id})]`;
}
} |
JavaScript | class MarketState {
constructor(handleProfileRequest) {
this._internal = MarketStateInternal(handleProfileRequest, ++instanceCounter);
}
/**
* @public
* @param {string} symbol
* @param {function=} callback - invoked when the {@link Profile} instance becomes available
* @returns {Promise<Profile>} The {@link Profile} instance, as a promise.
*/
getProfile(symbol, callback) {
return this._internal.getProfile(symbol, callback);
}
/**
* @public
* @param {string} symbol
* @returns {Quote}
*/
getQuote(symbol) {
return this._internal.getQuote(symbol);
}
/**
* @public
* @param {string} symbol
* @returns {Book}
*/
getBook(symbol) {
return this._internal.getBook(symbol);
}
/**
* @public
* @param {string} symbol
* @param {function=} callback - invoked when the {@link CumulativeVolume} instance becomes available
* @returns {Promise<CumulativeVolume>} The {@link CumulativeVolume} instance, as a promise
*/
getCumulativeVolume(symbol, callback) {
return this._internal.getCumulativeVolume(symbol, callback);
}
/**
* Returns the time the most recent market data message was received.
*
* @public
* @returns {Date}
*/
getTimestamp() {
return this._internal.getTimestamp();
}
/**
* @ignore
*/
processMessage(message) {
return this._internal.processMessage(message);
}
/**
* @ignore
*/
processExchangeMetadata(id, description, timezoneDdf, timezoneExchange) {
return this._internal.processExchangeMetadata(id, description, timezoneDdf, timezoneExchange);
}
/**
* @ignore
*/
static get CumulativeVolume() {
return CumulativeVolume;
}
/**
* @ignore
*/
static get Profile() {
return Profile;
}
/**
* @ignore
*/
static get Quote() {
return Quote;
}
toString() {
return '[MarketState]';
}
} |
JavaScript | class Profile {
constructor(symbol, name, exchangeId, unitCode, pointValue, tickIncrement, exchange, additional) {
/**
* @property {string} symbol - the symbol of the instrument.
*/
this.symbol = symbol;
/**
* @property {string} name - the name of the instrument.
*/
this.name = name;
/**
* @property {string} exchange - code of the listing exchange.
*/
this.exchange = exchangeId;
/**
* @property {string} unitCode - code indicating how a prices for the instrument should be formatted.
*/
this.unitCode = unitCode;
/**
* @property {string} pointValue - the change in value for a one point change in price.
*/
this.pointValue = pointValue;
/**
* @property {number} tickIncrement - the minimum price movement.
*/
this.tickIncrement = tickIncrement;
/**
* @property {Exchange|null} exchangeRef
*/
this.exchangeRef = exchange || null;
const info = SymbolParser.parseInstrumentType(this.symbol);
if (info) {
if (info.type === 'future') {
/**
* @property {undefined|string} root - the root symbol, if a future; otherwise undefined.
*/
this.root = info.root;
/**
* @property {undefined|string} month - the month code, if a future; otherwise undefined.
*/
this.month = info.month;
/**
* @property {undefined|number} year - the expiration year, if a future; otherwise undefined.
*/
this.year = info.year;
}
}
if (typeof additional === 'object' && additional !== null) {
for (let p in additional) {
this[p] = additional[p];
}
}
profiles[symbol] = this;
}
/**
* Given a numeric price, returns a human-readable price.
*
* @public
* @param {number} price
* @returns {string}
*/
formatPrice(price) {
return formatter(price, this.unitCode);
}
/**
* Configures the logic used to format all prices using the {@link Profile#formatPrice} instance function.
*
* @public
* @param {string} fractionSeparator - usually a dash or a period
* @param {boolean} specialFractions - usually true
* @param {string=} thousandsSeparator - usually a comma
*/
static setPriceFormatter(fractionSeparator, specialFractions, thousandsSeparator) {
formatter = buildPriceFormatter(fractionSeparator, specialFractions, thousandsSeparator);
}
/**
* Alias for {@link Profile.setPriceFormatter} function.
*
* @deprecated
* @public
* @see {@link Profile.setPriceFormatter}
*/
static PriceFormatter(fractionSeparator, specialFractions, thousandsSeparator) {
Profile.setPriceFormatter(fractionSeparator, specialFractions, thousandsSeparator);
}
/**
* @protected
* @ignore
*/
static get Profiles() {
return profiles;
}
toString() {
return `[Profile (symbol=${this.symbol})]`;
}
} |
JavaScript | class Quote {
constructor(symbol) {
/**
* @property {string} symbol - the symbol of the quoted instrument.
*/
this.symbol = symbol || null;
/**
* @property {string} message - last DDF message that caused a mutation to this instance.
*/
this.message = null;
/**
* @property {string} flag - market status, will have one of three values: p, s, or undefined.
*/
this.flag = null;
this.mode = null;
/**
* @property {string} day - one character code that indicates day of the month of the current trading session.
*/
this.day = null;
/**
* @property {number} dayNum - day of the month of the current trading session.
*/
this.dayNum = 0;
this.session = null;
/**
* @property {Date|null} lastUpdate - the most recent refresh. this date instance stores the hours and minutes for the exchange time (without proper timezone adjustment). use caution.
*/
this.lastUpdate = null;
this.lastUpdateUtc = null;
/**
* @property {number} bidPrice - top-of-book price on the buy side.
*/
this.bidPrice = null;
/**
* @property {number} bidSize - top-of-book quantity on the buy side.
*/
this.bidSize = null;
/**
* @property {number} askPrice - top-of-book price on the sell side.
*/
this.askPrice = null;
/**
* @property {number} askSize - top-of-book quantity on the sell side.
*/
this.askSize = null;
/**
* @property {number} lastPrice - most recent price (not necessarily a trade).
*/
this.lastPrice = null;
/**
* @property {number} tradePrice - most recent trade price.
*/
this.tradePrice = null;
/**
* @property {number} tradeSize - most recent trade quantity.
*/
this.tradeSize = null;
this.numberOfTrades = null;
this.vwap1 = null; // Exchange Provided
this.vwap2 = null; // Calculated
/**
* @property {number} blockTrade - most recent block trade price.
*/
this.blockTrade = null;
/**
* @property {number} settlementPrice
*/
this.settlementPrice = null;
this.openPrice = null;
this.highPrice = null;
this.lowPrice = null;
this.volume = null;
this.openInterest = null;
/**
* @property {number} previousPrice - price from the previous session.
*/
this.previousPrice = null;
/**
* @property {Date|null} time - the most recent trade, quote, or refresh. this date instance stores the hours and minutes for the exchange time (without proper timezone adjustment). use caution.
*/
this.time = null;
this.timeUtc = null;
/**
* @property {Profile|null} profile - metadata regarding the quoted instrument.
*/
this.profile = null;
this.ticks = [];
}
static clone(symbol, source) {
const clone = Object.assign({}, source);
clone.symbol = symbol;
return clone;
}
toString() {
return `[Quote (symbol=${this.symbol})]`;
}
} |
JavaScript | class SymbolParser {
constructor() {}
/**
* Returns a simple instrument definition with the terms that can be
* gleaned from a symbol. If no specifics can be determined from the
* symbol, a null value is returned.
*
* @public
* @static
* @param {String} symbol
* @returns {Object|null}
*/
static parseInstrumentType(symbol) {
if (!is.string(symbol)) {
return null;
}
let definition = null;
for (let i = 0; i < parsers.length && definition === null; i++) {
const parser = parsers[i];
definition = parser(symbol);
}
return definition;
}
/**
* Translates a symbol into a form suitable for use with JERQ (i.e. the quote "producer").
*
* @public
* @static
* @param {String} symbol
* @return {String|null}
*/
static getProducerSymbol(symbol) {
if (!is.string(symbol)) {
return null;
}
let converted = null;
for (let i = 0; i < converters.length && converted === null; i++) {
const converter = converters[i];
converted = converter(symbol);
}
return converted;
}
/**
* Attempts to convert database format of futures options to pipeline format
* (e.g. ZLF320Q -> ZLF9|320C)
*
* @public
* @static
* @param {String} symbol
* @returns {String|null}
*/
static getFuturesOptionPipelineFormat(symbol) {
const definition = SymbolParser.parseInstrumentType(symbol);
let formatted = null;
if (definition.type === 'future_option') {
const putCallCharacter = getPutCallCharacter(definition.option_type);
formatted = `${definition.root}${definition.month}${getYearDigits(definition.year, 1)}|${definition.strike}${putCallCharacter}`;
}
return formatted;
}
/**
* Returns true if the symbol is not an alias to another symbol; otherwise
* false.
*
* @public
* @static
* @param {String} symbol
* @returns {Boolean}
*/
static getIsConcrete(symbol) {
return is.string(symbol) && !types.futures.alias.test(symbol);
}
/**
* Returns true if the symbol is an alias for another symbol; false otherwise.
*
* @public
* @static
* @param {String} symbol
* @returns {Boolean}
*/
static getIsReference(symbol) {
return is.string(symbol) && types.futures.alias.test(symbol);
}
/**
* Returns true if the symbol represents futures contract; false otherwise.
*
* @public
* @static
* @param {String} symbol
* @returns {Boolean}
*/
static getIsFuture(symbol) {
return is.string(symbol) && (types.futures.concrete.test(symbol) || types.futures.alias.test(symbol));
}
/**
* Returns true if the symbol represents futures spread; false otherwise.
*
* @public
* @public
* @param {String} symbol
* @returns {Boolean}
*/
static getIsFutureSpread(symbol) {
return is.string(symbol) && types.futures.spread.test(symbol);
}
/**
* Returns true if the symbol represents an option on a futures contract; false
* otherwise.
*
* @public
* @static
* @param {String} symbol
* @returns {Boolean}
*/
static getIsFutureOption(symbol) {
return is.string(symbol) && (types.futures.options.short.test(symbol) || types.futures.options.long.test(symbol) || types.futures.options.historical.test(symbol));
}
/**
* Returns true if the symbol represents a foreign exchange currency pair;
* false otherwise.
*
* @public
* @static
* @param {String} symbol
* @returns {Boolean}
*/
static getIsForex(symbol) {
return is.string(symbol) && types.forex.test(symbol);
}
/**
* Returns true if the symbol represents an external index (e.g. Dow Jones
* Industrials); false otherwise.
*
* @public
* @static
* @param {String} symbol
* @returns {Boolean}
*/
static getIsIndex(symbol) {
return is.string(symbol) && types.indicies.external.test(symbol);
}
/**
* Returns true if the symbol represents an internally-calculated sector
* index; false otherwise.
*
* @public
* @static
* @param {String} symbol
* @returns {Boolean}
*/
static getIsSector(symbol) {
return is.string(symbol) && types.indicies.sector.test(symbol);
}
/**
* Returns true if the symbol represents an internally-calculated, cmdty-branded
* index; false otherwise.
*
* @public
* @static
* @param {String} symbol
* @returns {Boolean}
*/
static getIsCmdty(symbol) {
return is.string(symbol) && types.indicies.cmdty.test(symbol);
}
/**
* Returns true if the symbol is listed on the BATS exchange; false otherwise.
*
* @public
* @static
* @param {String} symbol
* @returns {Boolean}
*/
static getIsBats(symbol) {
return is.string(symbol) && predicates.bats.test(symbol);
}
/**
* Returns true if the symbol has an expiration and the symbol appears
* to be expired (e.g. a future for a past year).
*
* @public
* @static
* @param {String} symbol
* @returns {Boolean}
*/
static getIsExpired(symbol) {
const definition = SymbolParser.parseInstrumentType(symbol);
let returnVal = false;
if (definition !== null && definition.year && definition.month) {
const currentYear = getCurrentYear();
if (definition.year < currentYear) {
returnVal = true;
} else if (definition.year === currentYear && futuresMonthNumbers.hasOwnProperty(definition.month)) {
const currentMonth = getCurrentMonth();
const futuresMonth = futuresMonthNumbers[definition.month];
if (currentMonth > futuresMonth) {
returnVal = true;
}
}
}
return returnVal;
}
/**
* Returns true if prices for the symbol should be represented as a percentage; false
* otherwise.
*
* @public
* @static
* @param {String} symbol
* @returns {Boolean}
*/
static displayUsingPercent(symbol) {
return is.string(symbol) && predicates.percent.test(symbol);
}
toString() {
return '[SymbolParser]';
}
} |
JavaScript | class Enum {
constructor(code, description) {
assert.argumentIsRequired(code, 'code', String);
assert.argumentIsRequired(description, 'description', String);
this._code = code;
this._description = description;
const c = this.constructor;
if (!types.has(c)) {
types.set(c, []);
}
const existing = Enum.fromCode(c, code);
if (existing === null) {
types.get(c).push(this);
}
}
/**
* The unique code.
*
* @public
* @returns {String}
*/
get code() {
return this._code;
}
/**
* The description.
*
* @public
* @returns {String}
*/
get description() {
return this._description;
}
/**
* Returns true if the provided {@link Enum} argument is equal
* to the instance.
*
* @public
* @param {Enum} other
* @returns {boolean}
*/
equals(other) {
return other === this || other instanceof Enum && other.constructor === this.constructor && other.code === this.code;
}
/**
* Returns the JSON representation.
*
* @public
* @returns {String}
*/
toJSON() {
return this.code;
}
/**
* Looks up a enumeration item; given the enumeration type and the enumeration
* item's value. If no matching item can be found, a null value is returned.
*
* @public
* @param {Function} type - The enumeration type.
* @param {String} code - The enumeration item's code.
* @returns {*|null}
*/
static fromCode(type, code) {
return Enum.getItems(type).find(x => x.code === code) || null;
}
/**
* Returns all of the enumeration's items (given an enumeration type).
*
* @public
* @param {Function} type - The enumeration to list.
* @returns {Array}
*/
static getItems(type) {
return types.get(type) || [];
}
toString() {
return '[Enum]';
}
} |
JavaScript | class Timezones extends Enum {
constructor(code) {
super(code, code);
}
/**
* Calculates and returns the timezone's offset from UTC.
*
* @public
* @param {Number=} timestamp - The moment at which the offset is calculated, otherwise now.
* @param {Boolean=} milliseconds - If true, the offset is returned in milliseconds; otherwise minutes.
* @returns {Number}
*/
getUtcOffset(timestamp, milliseconds) {
let timestampToUse;
if (is.number(timestamp)) {
timestampToUse = timestamp;
} else {
timestampToUse = new Date().getTime();
}
let multiplier;
if (is.boolean(milliseconds) && milliseconds) {
multiplier = 60 * 1000;
} else {
multiplier = 1;
}
const offset = moment.tz.zone(this.code).utcOffset(timestampToUse) * multiplier;
if (offset !== 0) {
return offset * -1;
} else {
return 0;
}
}
/**
*
* Given a code, returns the enumeration item.
*
* @public
* @param {String} code
* @returns {Timezones|null}
*/
static parse(code) {
return Enum.fromCode(Timezones, code);
}
/**
* UTC
*
* @public
* @static
* @returns {Timezones}
*/
static get UTC() {
return utc;
}
/**
* America/Chicago
*
* @public
* @static
* @returns {Timezones}
*/
static get AMERICA_CHICAGO() {
return america_chicago;
}
/**
* America/New_York
*
* @public
* @static
* @returns {Timezones}
*/
static get AMERICA_NEW_YORK() {
return america_new_york;
}
toString() {
return `[Timezone (name=${this.code})]`;
}
} |
JavaScript | class ExplorerContainer extends React.Component {
constructor(props){
super();
const { grouping } = props;
const scheme_key = scheme.key;
const reducer = combineReducers({
root: root_reducer,
[scheme_key]: scheme.reducer,
});
const mapStateToProps = map_state_to_props_from_memoized_funcs(get_memoized_funcs([scheme]));
const mapDispatchToProps = dispatch => ({
...map_dispatch_to_root_props(dispatch),
...scheme.dispatch_to_props(dispatch),
});
const initialState = {
root: { ...initial_root_state, scheme_key },
[scheme_key]: {
grouping,
should_show_orgs_without_data: true,
},
};
const connecter = connect(mapStateToProps, mapDispatchToProps);
const Container = connecter(ExplorerForIgoc);
const store = createStore(reducer,initialState);
this.state = {
store,
Container,
};
}
static getDerivedStateFromProps(nextProps, prevState){
const { grouping } = nextProps;
prevState.store.dispatch({
type: 'set_grouping',
payload: grouping,
});
return null;
}
render(){
const { store, Container } = this.state;
return (
<Provider store={store}>
<Container />
</Provider>
);
}
} |
JavaScript | class KittySan {
constructor() {
this.elements = {
popularMovies: document.querySelector('#popular .movie-cards'),
popularShows: document.querySelector('#popular .show-cards'),
moviesPage: document.getElementById('movies-page'),
tvPage: document.getElementById('tv-page')
};
}
async meow() {
this.paintPopularMovies();
this.paintPopularShows();
}
async paintPopularMovies() {
if (this.elements.popularMovies.children.length > 0) return;
BunnyChan.category = 'movie';
const data = await BunnyChan.fetchTrendingData();
const cards = data.results;
cards.sort((a, b) => b.vote_average - a.vote_average);
for (const card of cards) {
// Create movie poster element
const listElement = document.createElement('li');
const moviePoster = document.createElement('media-poster');
const shadow = moviePoster.shadowRoot;
// Update source URLs
const cardImage = shadow.querySelector('.card-image');
cardImage.setAttribute('src', cardImage.getAttribute('src') + card.poster_path);
const sources = shadow.querySelectorAll('.js-picture-source');
for (const source of sources) {
source.setAttribute('srcset', source.getAttribute('srcset') + card.poster_path);
}
// Update rating
shadow.querySelector('.card-rating').textContent = card.vote_average;
// Update episode count
shadow.querySelector('.card-episode-count').style.display = 'none';
// Update route path
shadow.querySelector('a').href = '#movies/' + card.id;
listElement.append(moviePoster);
listElement.ariaLabel = card.title;
// Append to the DOM
this.elements.popularMovies.append(listElement);
}
}
async paintPopularShows() {
if (this.elements.popularShows.children.length > 0) return;
BunnyChan.category = 'tv';
const data = await BunnyChan.fetchTrendingData();
const cards = data.results;
cards.sort((a, b) => b.vote_average - a.vote_average);
for (const card of cards) {
// Create movie poster element
const listElement = document.createElement('li');
const tvPoster = document.createElement('media-poster');
const shadow = tvPoster.shadowRoot;
// Update source URLs
const cardImage = shadow.querySelector('.card-image');
cardImage.setAttribute('src', cardImage.getAttribute('src') + card.poster_path);
const sources = shadow.querySelectorAll('.js-picture-source');
for (const source of sources) {
source.setAttribute('srcset', source.getAttribute('srcset') + card.poster_path);
}
// Update rating
shadow.querySelector('.card-rating').textContent = card.vote_average;
// Grab TV episode count
const details = await BunnyChan.fetchTVDetails(card.id);
// Update episode count
const cardEpisodeCount = shadow.querySelector('.card-episode-count');
cardEpisodeCount.textContent = `${details.number_of_episodes} EP`;
// Update route path
shadow.querySelector('a').href = '#tv/' + card.id;
listElement.append(tvPoster);
listElement.ariaLabel = card.name;
// Append to the DOM
this.elements.popularShows.append(listElement);
}
}
async paintMovieDetails(movieId) {
// Avoid duplication
removeAllChildNodes(this.elements.moviesPage);
console.log({ movieId });
const movieDetails = await BunnyChan.fetchMovieDetails(movieId);
console.log({ movieDetails });
const mediaCard = document.createElement('media-card');
const shadow = mediaCard.shadowRoot;
shadow.querySelector('.card-image').src += movieDetails.backdrop_path;
shadow.querySelector('.card-title').textContent = movieDetails.title;
shadow.querySelector('.card-year').textContent = movieDetails.release_date.split('-')[0];
shadow.querySelector('.card-rating').textContent = movieDetails.vote_average;
shadow.querySelector('.card-overview').textContent = movieDetails.overview;
const cardGenres = shadow.querySelector('.card-genres');
movieDetails.genres.forEach(genre => {
const listItem = document.createElement('li');
listItem.className = 'card-genre';
listItem.textContent = genre.name;
cardGenres.append(listItem);
});
this.elements.moviesPage.append(mediaCard);
}
async paintTVDetails(tvId) {
// Avoid duplication
removeAllChildNodes(this.elements.tvPage);
console.log({ tvId });
const tvDetails = await BunnyChan.fetchTVDetails(tvId);
console.log({ tvDetails });
const mediaCard = document.createElement('media-card');
const shadow = mediaCard.shadowRoot;
shadow.querySelector('.card-image').src += tvDetails.backdrop_path;
shadow.querySelector('.card-title').textContent = tvDetails.name;
shadow.querySelector('.card-year').textContent = tvDetails.first_air_date.split('-')[0];
shadow.querySelector('.card-rating').textContent = tvDetails.vote_average;
shadow.querySelector('.card-overview').textContent = tvDetails.overview;
const cardGenres = shadow.querySelector('.card-genres');
tvDetails.genres.forEach(genre => {
const listItem = document.createElement('li');
listItem.className = 'card-genre';
listItem.textContent = genre.name;
cardGenres.append(listItem);
});
this.elements.tvPage.append(mediaCard);
}
} |
JavaScript | class TwyrBaseFeature extends TwyrBaseModule {
// #region Constructor
constructor(parent, loader) {
super(parent, null);
const TwyrFeatureLoader = require('./twyr-feature-loader').TwyrFeatureLoader;
const actualLoader = (loader instanceof TwyrFeatureLoader) ? loader : new TwyrFeatureLoader(this);
this.$loader = actualLoader;
const inflection = require('inflection');
const Router = require('koa-router');
const inflectedName = inflection.transform(this.name, ['foreign_key', 'dasherize']).replace('-id', '');
this.$router = new Router({ 'prefix': `/${inflectedName}` });
// The RBAC Koa middleware
// this.$router.use(this._doesUserHavePermission.bind(this));
// The ABAC Koa middleware
// this.$router.use(this._canUserAccessThisResource.bind(this));
}
// #endregion
// #region Lifecycle hooks
/**
* @async
* @function
* @override
* @instance
* @memberof TwyrBaseFeature
* @name _setup
*
* @returns {undefined} Nothing.
*
* @summary Adds the Koa Router routes.
*/
async _setup() {
try {
await super._setup();
await this._addRoutes();
return null;
}
catch(err) {
throw new TwyrFeatureError(`${this.name}::_setup error`, err);
}
}
/**
* @async
* @function
* @override
* @instance
* @memberof TwyrBaseFeature
* @name _teardown
*
* @returns {undefined} Nothing.
*
* @summary Destroys the Koa Router routes.
*/
async _teardown() {
try {
await this._deleteRoutes();
await super._teardown();
return null;
}
catch(err) {
throw new TwyrFeatureError(`${this.name}::_teardown error`, err);
}
}
/**
* @async
* @function
* @instance
* @memberof TwyrBaseFeature
* @name _subModuleReconfigure
*
* @param {TwyrBaseModule} subModule - The sub-module that changed configuration.
*
* @returns {undefined} Nothing.
*
* @summary Lets the module know that one of its subModules changed configuration.
*/
async _subModuleReconfigure(subModule) {
await super._subModuleReconfigure(subModule);
const subModuleType = Object.getPrototypeOf(Object.getPrototypeOf(subModule)).name;
if((subModuleType !== 'TwyrBaseComponent') && (subModuleType !== 'TwyrBaseFeature'))
return null;
await this._deleteRoutes();
await this._addRoutes();
await this.$parent._subModuleReconfigure(this);
return null;
}
// #endregion
// #region API - to be overriden by derived classes, only if required
/**
* @async
* @function
* @instance
* @memberof TwyrBaseFeature
* @name getClientsideAssets
*
* @param {Object} ctxt - Koa context.
* @param {Object} tenantFeatures - Sub-features allowed for this Tenant.
*
* @returns {Object} Containing the compiled Ember.js client-side assets (specifically the route map, but could be others, as well).
*
* @summary Returns the route map that is used by the Ember.js Router on the browser.
*/
async getClientsideAssets(ctxt, tenantFeatures) {
const assets = this.EmberAssets;
if(!assets) return null;
const inflection = require('inflection');
const featureNames = Object.keys(tenantFeatures || {});
const clientsideAssets = {
'RouteMap': JSON.parse(JSON.stringify(assets['RouteMap']))
};
for(let idx = 0; idx < featureNames.length; idx++) {
const featureName = featureNames[idx];
const feature = this.$features[featureName];
const featureClientsideAssets = await feature.getClientsideAssets(ctxt, tenantFeatures[featureName]);
if(!featureClientsideAssets) continue;
Object.keys(featureClientsideAssets).forEach((featureClientsideAssetName) => {
if(featureClientsideAssetName === 'RouteMap') {
const inflectedFeatureName = inflection.transform(featureName, ['foreign_key', 'dasherize']).replace('-id', '');
clientsideAssets['RouteMap'][inflectedFeatureName] = {
'path': `/${inflectedFeatureName}`,
'routes': featureClientsideAssets['RouteMap']
};
return;
}
if(!clientsideAssets[featureClientsideAssetName]) clientsideAssets[featureClientsideAssetName] = [];
clientsideAssets[featureClientsideAssetName].push(featureClientsideAssets[featureClientsideAssetName]);
});
}
Object.keys(clientsideAssets).forEach((clientsideAssetName) => {
if(clientsideAssetName === 'RouteMap') return;
clientsideAssets[clientsideAssetName] = clientsideAssets[clientsideAssetName].join('\n');
});
return clientsideAssets;
}
// #endregion
// #region Protected methods - need to be overriden by derived classes
/**
* @async
* @function
* @instance
* @memberof TwyrBaseFeature
* @name getDashboardDisplayDetails
*
* @param {Object} ctxt - Koa context.
*
* @returns {Object} Dashboard display stuff for this Feature.
*
* @summary Derived classes should return details, or null - depending on whether the user has the required permission(s).
*/
async getDashboardDisplayDetails(ctxt) { // eslint-disable-line no-unused-vars
const inflection = require('inflection');
const id = await this.$dependencies.ConfigurationService.getModuleID(this);
const inflectedFeatureName = inflection.transform(this.name, ['foreign_key', 'dasherize']).replace('-id', '');
return {
'id': id,
'type': 'dashboard/feature',
'attributes': {
'name': inflection.transform(this.name, ['tableize', 'singularize', 'titleize']),
'type': 'feature',
'route': inflectedFeatureName,
'description': this.name,
// eslint-disable-next-line no-inline-comments
'icon_type': 'fa', // Other choices are paper, mdi, img, custom
'icon_path': 'laptop-code'
}
};
}
/**
* @function
* @instance
* @memberof TwyrBaseFeature
* @name _rbac
*
* @param {string} permission - The permission to check for.
*
* @returns {undefined} Koa middleware that can be injected into a route.
*
* @summary Derived classes should call next, or throw a {TwyrFeatureError} - depending on whether the user has the required permission(s).
*/
_rbac(permission) {
return async function(ctxt, next) {
// console.log(`Requested Permission: ${permission},\nUser Permissions: ${JSON.stringify(ctxt.state.user.permissions, null, '\t')}`);
if(ctxt.state.user && ctxt.state.user.permissions) {
if(permission === 'registered') {
if(next) await next();
return;
}
const doesUserHavePermission = ctxt.state.user.permissions.filter((userPerm) => {
return (userPerm.name === permission);
}).length;
if(doesUserHavePermission) {
if(next) await next();
return;
}
}
throw new TwyrFeatureError('User doesn\'t have the required permissions');
};
}
/**
* @async
* @function
* @instance
* @memberof TwyrBaseFeature
* @name _abac
*
* @param {Object} ctxt - Koa context.
* @param {callback} next - Callback to pass the request on to the next route in the chain.
*
* @returns {undefined} Nothing.
*
* @summary Derived classes should call next, or throw a {TwyrFeatureError} - depending on whether the user can access this particular resource.
*/
async _abac(ctxt, next) {
await next();
}
/**
* @async
* @function
* @instance
* @memberof TwyrBaseFeature
* @name _addRoutes
*
* @returns {undefined} Nothing.
*
* @summary Adds routes to the Koa Router.
*/
async _addRoutes() {
if(twyrEnv === 'development' || twyrEnv === 'test') console.log(`${this.name}::_addRoutes`);
// Add in the sub-components routes
Object.keys(this.$components || {}).forEach((componentName) => {
const componentRouter = this.$components[componentName].Router;
this.$router.use(componentRouter.routes());
});
// Add in the sub-features routes
Object.keys(this.$features || {}).forEach((featureName) => {
const featureRouter = this.$features[featureName].Router;
this.$router.use(featureRouter.routes());
});
return null;
}
/**
* @async
* @function
* @instance
* @memberof TwyrBaseFeature
* @name _deleteRoutes
*
* @returns {undefined} Nothing.
*
* @summary Removes all the routes from the Koa Router.
*/
async _deleteRoutes() {
if(twyrEnv === 'development' || twyrEnv === 'test') console.log(`${this.name}::_deleteRoutes`);
// NOTICE: Undocumented koa-router data structure.
// Be careful upgrading :-)
if(this.$router) this.$router.stack.length = 0;
return null;
}
// #endregion
// #region Properties
/**
* @member {Object} Router
* @instance
* @memberof TwyrBaseFeature
*
* @readonly
*/
get Router() {
return this.$router;
}
/**
* @member {Object} EmberAssets
* @instance
* @memberof TwyrBaseFeature
*
* @readonly
*/
get EmberAssets() {
// if(twyrEnv === 'development' || twyrEnv === 'test') console.log(`${this.name}::EmberAssets`);
return {
'RouteMap': {
'index': {
'path': '/',
'routes': {}
}
}
};
}
/**
* @override
*/
get dependencies() {
return ['*'].concat(super.dependencies);
}
/**
* @override
*/
get basePath() {
return __dirname;
}
// #endregion
} |
JavaScript | class Thumb extends PureComponent {
static propTypes = {
style: PropTypes.object,
className: PropTypes.string,
thumbLeft: PropTypes.string.isRequired,
on: PropTypes.bool,
off: PropTypes.bool,
active: PropTypes.bool,
disabled: PropTypes.bool,
dragging: PropTypes.bool,
discrete: PropTypes.bool,
};
render() {
const {
style,
className,
on,
off,
active,
disabled,
dragging,
thumbLeft,
discrete,
...props
} = this.props;
return (
<AccessibleFakeButton
disabled={disabled}
{...props}
style={Object.assign({}, style, { left: thumbLeft })}
className={cn('md-slider-thumb', className, {
'md-slider-thumb--active': active,
'md-slider-thumb--dragging': dragging,
'md-slider-thumb--disabled': disabled,
'md-slider-thumb--on': on,
'md-slider-thumb--continuous-off': !discrete && off,
'md-slider-thumb--discrete': discrete,
'md-slider-thumb--discrete-on': discrete && active && on,
'md-slider-thumb--discrete-off': discrete && !disabled && off,
'md-slider-thumb--discrete-active': discrete && active,
'md-slider-thumb--discrete-active-off': discrete && active && off,
})}
/>
);
}
} |
JavaScript | class ResourcePaths{
constructor(path) {
this.curr_dir = this.getBaseDirectory();
this.file_path = path;
}
// Gets base directory of WebCache
getBaseDirectory = () => {
return path.resolve(__dirname,'..');
}
// Gets resource directory
getResourceDir = () => {
return path.join(this.getBaseDirectory(),this.file_path) + '/';
}
// gets resource base
getResourceBase = () => {
return path.normalize(path.join(this.getBaseDirectory(), this.file_path) + '/../');
}
// Creates full path of resource with the index.html
getFullPath = () => {
if (!this.file_path.startsWith("app") && !this.file_path.startsWith("render") && !this.file_path.endsWith('html')){
this.file_path = path.join(this.file_path,"index.html");
}
return path.join(this.curr_dir,this.file_path);
}
// Creates full file thingy
getFilePath = () => {
return "file://" + this.getFullPath();
}
} |
JavaScript | class PrefixSha256 extends BaseSha256 {
constructor () {
super()
this.prefix = Buffer.alloc(0)
this.subcondition = null
this.maxMessageLength = 16384
}
/**
* Set the (unfulfilled) subcondition.
*
* Each prefix condition builds on an existing condition which is provided via
* this method.
*
* @param {Condition|String} subcondition Condition object or URI string
* representing the condition that will receive the prefixed message.
*/
setSubcondition (subcondition) {
if (typeof subcondition === 'string') {
subcondition = Condition.fromUri(subcondition)
} else if (!(subcondition instanceof Condition)) {
throw new Error('Subconditions must be URIs or objects of type Condition')
}
this.subcondition = subcondition
}
/**
* Set the (fulfilled) subcondition.
*
* When constructing a prefix fulfillment, this method allows you to pass in
* a fulfillment for the condition that will receive the prefixed message.
*
* Note that you only have to add either the subcondition or a subfulfillment,
* but not both.
*
* @param {Fulfillment|String} fulfillment Fulfillment object or URI string
* representing the fulfillment to use as the subcondition.
*/
setSubfulfillment (subfulfillment) {
if (typeof subfulfillment === 'string') {
subfulfillment = Fulfillment.fromUri(subfulfillment)
} else if (!(subfulfillment instanceof Fulfillment)) {
throw new Error('Subfulfillments must be objects of type Fulfillment')
}
this.subcondition = subfulfillment
}
/**
* Set the prefix.
*
* The prefix will be prepended to the message during validation before the
* message is passed on to the subcondition.
*
* @param {Buffer} prefix Prefix to apply to the message.
*/
setPrefix (prefix) {
if (!Buffer.isBuffer(prefix)) {
throw new TypeError('Prefix must be a Buffer, was: ' + prefix)
}
this.prefix = prefix
}
/**
* Set the threshold.
*
* Determines the threshold that is used to consider this condition fulfilled.
* If the number of valid subfulfillments is greater or equal to this number,
* the threshold condition is considered to be fulfilled.
*
* @param {Number} maxMessageLength Integer threshold
*/
setMaxMessageLength (maxMessageLength) {
if (!isInteger(maxMessageLength) || maxMessageLength < 0) {
throw new TypeError('Max message length must be an integer greater than or equal to zero, was: ' +
maxMessageLength)
}
this.maxMessageLength = maxMessageLength
}
/**
* Get types used in this condition.
*
* This is a type of condition that contains a subcondition. A complete
* set of subtypes must contain the set of types that must be supported in
* order to validate this fulfillment. Therefore, we need to join the type of
* this condition to the types used in the subcondition.
*
* @return {Set<String>} Complete type names for this fulfillment.
*/
getSubtypes () {
const subtypes = new Set([...this.subcondition.getSubtypes(), this.subcondition.getTypeName()])
// Never include our own type as a subtype. The reason is that we already
// know that the validating implementation knows how to interpret this type,
// otherwise it wouldn't be able to verify this fulfillment to begin with.
subtypes.delete(this.constructor.TYPE_NAME)
return subtypes
}
/**
* Produce the contents of the condition hash.
*
* This function is called internally by the `getCondition` method.
*
* @return {Buffer} Encoded contents of fingerprint hash.
*
* @private
*/
getFingerprintContents () {
if (!this.subcondition) {
throw new MissingDataError('Requires subcondition')
}
return Asn1PrefixFingerprintContents.encode({
prefix: this.prefix,
maxMessageLength: this.maxMessageLength,
subcondition: this.subcondition instanceof Condition
? this.subcondition.getAsn1Json()
: this.subcondition.getCondition().getAsn1Json()
})
}
getAsn1JsonPayload () {
return {
prefix: this.prefix,
maxMessageLength: this.maxMessageLength,
subfulfillment: this.subcondition.getAsn1Json()
}
}
parseJson (json) {
this.setPrefix(Buffer.from(json.prefix, 'base64'))
this.setMaxMessageLength(json.maxMessageLength)
this.setSubfulfillment(Fulfillment.fromJson(json.subfulfillment))
}
parseAsn1JsonPayload (json) {
this.setPrefix(Buffer.from(json.prefix, 'base64'))
this.setMaxMessageLength(json.maxMessageLength.toNumber())
this.setSubfulfillment(Fulfillment.fromAsn1Json(json.subfulfillment))
}
/**
* Calculate the cost of fulfilling this condition.
*
* The cost of the prefix condition equals (1 + l/256) * (16384 + s) where l
* is the prefix length in bytes and s is the subcondition cost.
*
* @return {Number} Expected maximum cost to fulfill this condition
* @private
*/
calculateCost () {
if (!this.prefix) {
throw new MissingDataError('Prefix must be specified')
}
if (!this.subcondition) {
throw new MissingDataError('Subcondition must be specified')
}
const subconditionCost = this.subcondition instanceof Condition
? this.subcondition.getCost()
: this.subcondition.getCondition().getCost()
return Number(this.prefix.length) + this.maxMessageLength + subconditionCost + 1024
}
/**
* Check whether this fulfillment meets all validation criteria.
*
* This will validate the subfulfillment. The message will be prepended with
* the prefix before being passed to the subfulfillment's validation routine.
*
* @param {Buffer} message Message to validate against.
* @return {Boolean} Whether this fulfillment is valid.
*/
validate (message) {
if (!(this.subcondition instanceof Fulfillment)) {
throw new Error('Subcondition is not a fulfillment')
}
if (!Buffer.isBuffer(message)) {
throw new Error('Message must be provided as a Buffer, was: ' + message)
}
// Ensure the subfulfillment is valid
return this.subcondition.validate(Buffer.concat([this.prefix, message]))
}
} |
JavaScript | class MarkdownFileCollector {
/**
* @param {string} baseDir
* @return {MarkdownFileItem[]}
*/
collect(baseDir) {
let result = [];
const fileCollector = new FileCollector();
fileCollector.collect(baseDir, markdownUtil.fileMatcher, markdownUtil.dirMatcher).forEach((path) => {
result.push({
path: this._encodePath(path),
notation: path,
title: this._stripBadge(this._getTitle(baseDir, path, 3)),
});
});
return result;
}
/**
* @param {string} path
* @return {string}
* @private
*/
_encodePath(path) {
return encodeURI('/' + path)
.replace(/\+/g, encodeURIComponent)
.replace(/#/g, encodeURIComponent)
.replace(/\?/g, encodeURIComponent);
}
/**
* @param {string} baseDir
* @param {string} path
* @param {number} searchLineLimit
* @return {string}
* @private
*/
_getTitle(baseDir, path, searchLineLimit) {
const liner = new LineByLine(baseDir + '/' + path);
const result = this._getTitleLine(liner, path, searchLineLimit);
if (typeof liner.fd === 'number') {
liner.close();
}
return result;
}
/**
* @param {LineByLine} liner
* @param {string} path
* @param {number} searchLineLimit
* @return {string}
* @private
*/
_getTitleLine(liner, path, searchLineLimit) {
let searchCount = 0;
/** @var {Buffer} */
let line;
/** @var {string} */
let text;
/** @var {(string[]|null)} */
let matched;
while ((searchCount < searchLineLimit) && (line = liner.next())) {
text = line.toString('utf8');
if ((matched = text.match(/^\s{0,3}#+\s*(.+)/))) {
return matched[1];
}
searchCount++;
}
return path;
}
/**
* Strip build badge.
*
* Badge notation example:
*
* - [](https://xxx)
* - [](https://xxx?branch=master)
* - [](https://xxx)
* - [](https://xxx?branch=master)
* - [![][xxx]][xxx]
* - [![xxx][xxx]][xxx]
*
* @param {string} text
* @return {string}
* @private
*/
_stripBadge(text) {
return text
.replace(/\[!\[[^\]]*]\([^)]+\)]\([^)]+\)/g, '')
.replace(/\[!\[[^\]]*]\[[^)]+]]\[[^)]+]/g, '');
}
} |
JavaScript | class cvar extends SimpleTable {
constructor(dict, dataview) {
const { p } = super(dict, dataview);
this.majorVersion = uint16;
this.minorVersion = uint16;
this.tupleVariationCount = uint16;
this.dataOffset = p.Offset32; // from the start of the table
// FIXME: this is only correct if we can properly read full Tuple Variation Header...
lazy(this`tupleVariationHeaders`, () =>
[...new Array(this.tupleVariationCount)].map(
(_) => new TupleVariationHeader(p)
)
);
}
} |
JavaScript | class Runtime {
/**
* Create and initialize an empty Runtime.
*/
constructor (brand) {
this.brand = brand
this.run = run // awkward because node.js doesn't support async-based class functions yet.
this.plugins = []
this.extensions = []
this.defaults = {}
this.defaultPlugin = null
this.events = {}
this.config = {}
this.addCoreExtensions()
}
/**
* Adds the core extensions. These provide the basic features
* available in gluegun, but follow the exact same method
* for extending the core as 3rd party extensions do.
*/
addCoreExtensions () {
this.addExtension('strings', addStringsExtension)
this.addExtension('print', addPrintExtension)
this.addExtension('template', addTemplateExtension)
this.addExtension('filesystem', addFilesystemExtension)
this.addExtension('system', addSystemExtension)
this.addExtension('http', addHttpExtension)
this.addExtension('prompt', addPromptExtension)
}
/**
* Adds an extension so it is available when commands run. They live
* as the given name on the context object passed to commands. The
* 2nd parameter is a function that, when called, creates that object.
*
* @param {string} name The context property name.
* @param {object} setup The setup function.
*/
addExtension (name, setup) {
this.extensions.push({ name, setup })
return this
}
/**
* Loads a plugin from a directory.
*
* @param {string} directory The directory to load from.
* @param {Object} options Additional loading options.
* @return {Plugin} A plugin.
*/
load (directory, options = {}) {
const {
brand,
extensionNameToken,
commandNameToken,
commandDescriptionToken,
commandHiddenToken,
commandAliasToken
} = this
const plugin = loadPluginFromDirectory(directory, {
extensionNameToken,
commandNameToken,
commandHiddenToken,
commandAliasToken,
commandDescriptionToken,
brand,
hidden: options['hidden']
})
this.plugins = append(plugin, this.plugins)
forEach(
extension => this.addExtension(extension.name, extension.setup),
plugin.extensions
)
return plugin
}
/**
* Loads a plugin from a directory and sets it as the default.
*
* @param {string} directory The directory to load from.
* @param {Object} options Additional loading options.
* @return {Plugin} A plugin.
*/
loadDefault (directory, options = {}) {
const plugin = this.load(directory, options)
this.defaultPlugin = plugin
return plugin
}
/**
* Loads a bunch of plugins from the immediate sub-directories of a directory.
*
* @param {string} directory The directory to grab from.
* @param {Object} options Addition loading options.
* @return {Plugin[]} A bunch of plugins
*/
loadAll (directory, options = {}) {
if (isBlank(directory) || !isDirectory(directory)) return []
return pipe(
dir => subdirectories(dir, false, options['matching']),
map(dir => this.load(dir, dissoc('matching', options)))
)(directory)
}
/**
* The list of commands registered.
*
* @return {[]} A list of [{plugin, command}]
*/
listCommands () {
const commands = []
const eachPlugin = plugin => {
const eachCommand = command => {
commands.push({ plugin, command })
}
forEach(eachCommand, plugin.commands)
}
forEach(eachPlugin, this.plugins)
return commands
}
/**
* Find the plugin for this name.
*
* @param {string} name The name to search through.
* @returns {*} A Plugin otherwise null.
*/
findPlugin (name) {
return findByProp('name', name || '', this.plugins)
}
/**
* Find the command for this pluginName & command.
*
* @param {Plugin} plugin The plugin in which the command lives.
* @param {string} rawCommand The command arguments to parse.
* @returns {*} A Command otherwise null.
*/
findCommand (plugin, rawCommand) {
if (isNil(plugin) || isBlank(rawCommand)) return null
if (isNilOrEmpty(plugin.commands)) return null
return find(
command =>
startsWith(command.name, rawCommand) || rawCommand === command.alias,
plugin.commands
)
}
} |
JavaScript | class XnorGate extends BaseControl {
/**
* Constructor for XorGate
* @param paper raphael paper object.
*/
constructor(paper) {
super(paper);
this.inputPin1Value = 0;
this.inputPin2Value = 0;
}
/**
* Draw the component surface
*/
draw() {
super.draw();
this.componentInputWire1 = this.paper.path('m 10.000001,11.23345 29.55419,0');
this.componentInputWire1.attr('stroke', DEFAULT_STROKE_COLOR);
this.componentInputWire1.attr('stroke-width', DEFAULT_STROKE_WIDTH);
this.componentInputWire2 = this.paper.path('m 10.000001,38.765752 29.55419,0');
this.componentInputWire2.attr('stroke', DEFAULT_STROKE_COLOR);
this.componentInputWire2.attr('stroke-width', DEFAULT_STROKE_WIDTH);
this.componentOutputWire = this.paper.path('m 98.90777,24.999601 19.55419,0');
this.componentOutputWire.attr('stroke', DEFAULT_STROKE_COLOR);
this.componentOutputWire.attr('stroke-width', DEFAULT_STROKE_WIDTH);
this.componentBodyShape = this.paper.path('M 35.564453 0.98242188 A 6.6318398 24.254708 0 0 1 41.328125 25 ' +
'A 6.6318398 24.254708 0 0 1 35.617188 48.992188 L 49.556641 48.992188 C 52.41131 48.897468 55.277154 ' +
'49.217449 58.121094 48.763672 C 58.273834 48.748362 58.428381 48.718372 58.582031 48.695312 ' +
'A 35.091661 36.015432 0 0 0 88.964844 24.984375 A 35.091661 36.015432 0 0 0 58.306641 1.2929688 ' +
'C 57.447411 1.1110448 56.588907 1.0052849 55.742188 0.98242188 C 49.016568 0.98219088 ' +
'42.290182 0.98245887 35.564453 0.98242188 z M 95.029297 19.449219 A 5.6206879 5.5509597 ' +
'0 0 0 89.410156 25 A 5.6206879 5.5509597 0 0 0 95.029297 30.550781 A 5.6206879 5.5509597 ' +
'0 0 0 100.65039 25 A 5.6206879 5.5509597 0 0 0 95.029297 19.449219 z');
this.componentBodyShape.attr('stroke', DEFAULT_STROKE_COLOR);
this.componentBodyShape.attr('stroke-width', DEFAULT_STROKE_WIDTH);
this.componentBodyShape.attr('stroke-linejoin', 'round');
this.componentBodyShape.attr('stroke-miterlimit', 4);
this.componentBodyFill = this.paper.path('m 37.87299,2.277085 c 5.9263,-2e-5 11.85325,-2.01e-4 ' +
'17.77917,0 0.80869,0.02174 1.63148,0.122346 2.45782,0.296874 a 0.84220924,1.1473134 0 0 0 ' +
'0.0866,0.01178 C 71.69394,3.510775 83.29957,12.46143 87.99642,25.132585 83.34535,37.726225 ' +
'71.86734,46.666401 58.46647,47.699068 a 0.84220924,1.1473134 0 0 0 -0.0447,0.004 ' +
'c -0.16808,0.02516 -0.31176,0.05104 -0.43009,0.06292 a 0.84220924,1.1473134 0 0 0 -0.0375,0.006 ' +
'c -2.74109,0.436292 -5.5866,0.125475 -8.50784,0.222173 l -11.5574,0 c 1.01449,-1.619408 ' +
'1.84058,-3.848117 2.49536,-6.592179 1.05682,-4.429001 1.67379,-10.108 1.67559,-16.255433 ' +
'C 42.05789,18.962613 41.43451,13.258377 40.36697,8.820355 39.71177,6.096526 38.88476,3.883369 ' +
'37.87306,2.277288 Z');
this.componentBodyFill.attr('stroke-width', 1);
this.componentBodyFill.attr('stroke', DEFAULT_FILL_COLOR);
this.componentBodyFill.attr('fill', DEFAULT_FILL_COLOR);
this.componentBodyGradient = this.paper.path('m 37.87299,1.918712 c 1.01467,1.606081 1.84411,3.819238 ' +
'2.50124,6.543067 0.99166,4.110495 1.59422,9.313563 1.68052,14.971596 2.19901,-1.148891 ' +
'4.57634,-2.065092 7.20409,-2.520499 3.49611,-0.413432 7.1643,0.669677 9.32608,2.819336 ' +
'2.18404,1.7211 3.99427,3.965511 7.05066,4.836524 2.63862,0.438497 5.39951,0.24912 ' +
'8.06534,0.03343 4.89897,-0.632573 9.64962,-1.772778 14.21711,-3.24991 0.0753,-0.192658 ' +
'0.15379,-0.383594 0.22581,-0.578015 C 83.43316,12.103076 71.7934,3.152422 58.25634,2.227384 ' +
'a 0.84468645,1.1473133 0 0 1 -0.0868,-0.01178 c -0.82877,-0.17453 -1.65398,-0.275132 ' +
'-2.46506,-0.296875 -5.94334,-2.01e-4 -11.88772,-2e-5 -17.83145,0 z');
this.componentBodyGradient.attr('stroke-width', 0);
this.componentBodyGradient.attr('fill', '90-#0066ff-#fff');
this.componentBodyShapeSmallCircleFill = this.paper.path('m 94.989561,20.447622 c 2.56339,1.77e-4 ' +
'4.61988,2.031151 4.62007,4.56276 -1.9e-4,2.531598 -2.05668,4.562572 -4.62007,4.562759 ' +
'-2.5634,-1.87e-4 -4.61989,-2.031161 -4.62008,-4.562759 1.9e-4,-2.531609 2.05668,-4.562583 ' +
'4.62008,-4.56276 z');
this.componentBodyShapeSmallCircleFill.attr('stroke-width', 1);
this.componentBodyShapeSmallCircleFill.attr('stroke', DEFAULT_FILL_COLOR);
this.componentBodyShapeSmallCircleFill.attr('fill', DEFAULT_FILL_COLOR);
this.componentBodyShapeSmallCircleGradient = this.paper.path('m 94.989561,20.447622 c -2.1263,1.48e-4 ' +
'-3.88416,1.406609 -4.42864,3.328018 3.39003,0.192324 6.60259,1.0941 8.83577,2.538937 ' +
'0.12507,-0.415575 0.2129,-0.846935 0.21294,-1.304195 -1.9e-4,-2.531609 -2.05668,-4.562583 ' +
'-4.62007,-4.56276 z');
this.componentBodyShapeSmallCircleGradient.attr('stroke-width', 0);
this.componentBodyShapeSmallCircleGradient.attr('fill', '90-#0066ff-#fff');
this.componentRearShape = this.paper.path('m 26.653817,0.95557543 a 6.1130418,24.293471 0 0 ' +
'1 5.312156,24.05583957 6.1130418,24.293471 0 0 1 -5.264382,24.03221 l 4.076678,0 ' +
'A 6.1130418,24.293471 0 0 0 36.04265,25.011415 6.1130418,24.293471 0 0 0 30.730495,0.95557543 ' +
'c -1.358901,1.311e-5 -2.717864,8.07e-6 -4.076678,0 z');
this.componentRearShape.attr('stroke', DEFAULT_STROKE_COLOR);
this.componentRearShape.attr('stroke-width', DEFAULT_STROKE_WIDTH);
this.componentRearShape.attr('stroke-linejoin', 'round');
this.componentRearShape.attr('stroke-miterlimit', 4);
this.componentRearShapeFill = this.paper.path('m 28.857204,2.3052176 c 0.556932,0 1.113836,4e-6 ' +
'1.670765,0 1.082614,0.63879 2.38004,3.2125883 3.286465,7.2683448 0.925257,4.1400216 ' +
'1.495739,9.6573496 1.497511,15.6394466 -0.0017,5.945897 -0.56635,11.435078 -1.482738,15.568555 ' +
'-0.902355,4.070176 -2.19838,6.65789 -3.283778,7.313636 l -1.673451,0 c 0.944063,-1.622027 ' +
'1.712818,-3.854298 2.322148,-6.602752 0.983473,-4.436074 1.557612,-10.122188 1.559292,-16.279439 ' +
'a 0.7837526,1.1491468 0 0 0 0,-0.002 C 32.751583,19.017153 32.171453,13.303808 ' +
'31.178009,8.858693 30.568285,6.1305068 29.798678,3.9138211 28.857204,2.3051702 Z');
this.componentRearShapeFill.attr('stroke-width', 1);
this.componentRearShapeFill.attr('stroke', DEFAULT_FILL_COLOR);
this.componentRearShapeFill.attr('fill', DEFAULT_FILL_COLOR);
this.componentRearShapeGradient = this.paper.path('m 28.890286,1.8988889 c 0.930247,1.6086509 ' +
'1.690677,3.8253367 2.293131,6.5535229 0.673964,3.0520142 1.149273,6.7098672 1.385433,10.7026442 ' +
'0.0074,-0.0045 0.02383,-0.01477 0.0292,-0.01772 0.306614,-0.162034 0.630581,-0.09389 ' +
'0.947509,-0.06892 0.236802,0.01865 0.149154,0.04507 0.30522,-0.03545 0.07131,-0.02228 ' +
'0.142888,-0.04113 0.213654,-0.06696 0.323177,-0.117963 0.166719,-0.110328 0.581245,-0.17526 ' +
'0.105111,-0.01647 0.210619,-0.0068 0.315837,-0.02166 0.03479,-0.0049 0.06848,-0.02299 ' +
'0.102182,-0.03742 C 34.823572,15.130848 34.382175,11.85609 33.788404,9.1672277 ' +
'32.892787,5.1114712 31.610832,2.5376719 30.541128,1.8988819 l -1.650842,0 z');
this.componentRearShapeGradient.attr('stroke-width', 0);
this.componentRearShapeGradient.attr('fill', '90-#0066ff-#fff');
}
initControl() {
super.initControl();
const inputPin1 = new ConnectionPin(this, 5, 11, 'in');
const inputPin2 = new ConnectionPin(this, 5, 39, 'in');
const outputPin = new ConnectionPin(this, 124, 25, 'out');
const _this = this;
inputPin1.addStateChangeListener(
function(newState) {
_this.inputPin1Value = newState;
outputPin.notifyStateChange(_this.getValue());
});
inputPin2.addStateChangeListener(
function(newState) {
_this.inputPin2Value = newState;
outputPin.notifyStateChange(_this.getValue());
});
this.setShapes([
this.componentBodyShape,
this.componentBodyFill,
this.componentBodyGradient,
this.componentInputWire1,
this.componentInputWire2,
this.componentOutputWire,
this.componentRearShape,
this.componentRearShapeFill,
this.componentRearShapeGradient,
this.componentBodyShapeSmallCircleFill,
this.componentBodyShapeSmallCircleGradient,
]);
this.addInputPins(inputPin1, inputPin2);
this.addOutputPins(outputPin);
}
/**
* An event fired when element is selected.
* @param event
*/
onSelect(event) {
super.onSelect(event);
this.glow = this.componentBodyShape.glow();
this.glow.toBack();
}
/**
* Return the value of calculated expression.
* @returns {boolean}
*/
getValue() {
return !((this.inputPin1Value + this.inputPin2Value) % 2);
}
} |
JavaScript | class Pico8Player extends Component {
/**
* @contructor
* @param {object} props
*/
constructor (props) {
super(props);
this.state = {};
}
/**
* Render
* @returns {node}
*/
render () {
const { cartridge } = this.props;
return (
<Fragment>
<div className={styles.mobile}>
<p>
You can play Sieur Lacassagne Dungeon on your mobile device by clicking on the folling link
<Link className={styles.text} to={'/pico8reader'}>
Sieur Lacassagne Dungeon
</Link>
</p>
</div>
<div className={styles.p8container}>
<Pico8GameShell cartridge={cartridge} />
</div>
</Fragment>
);
}
} |
JavaScript | class Material extends ThreeDOMElement {
constructor(onUpdate, gltf, material, correlatedMaterials) {
super(onUpdate, material, correlatedMaterials);
this[_a] = null;
this[_b] = null;
this[_c] = null;
if (correlatedMaterials == null) {
return;
}
if (material.pbrMetallicRoughness == null) {
material.pbrMetallicRoughness = {};
}
this[$pbrMetallicRoughness] = new PBRMetallicRoughness(onUpdate, gltf, material.pbrMetallicRoughness, correlatedMaterials);
const { normalTexture, occlusionTexture, emissiveTexture } = material;
const normalTextures = new Set();
const occlusionTextures = new Set();
const emissiveTextures = new Set();
for (const material of correlatedMaterials) {
const { normalMap, aoMap, emissiveMap } = material;
if (normalTexture != null && normalMap != null) {
normalTextures.add(normalMap);
}
if (occlusionTexture != null && aoMap != null) {
occlusionTextures.add(aoMap);
}
if (emissiveTexture != null && emissiveMap != null) {
emissiveTextures.add(emissiveMap);
}
}
if (normalTextures.size > 0) {
this[$normalTexture] =
new TextureInfo(onUpdate, gltf, normalTexture, normalTextures);
}
if (occlusionTextures.size > 0) {
this[$occlusionTexture] =
new TextureInfo(onUpdate, gltf, occlusionTexture, occlusionTextures);
}
if (emissiveTextures.size > 0) {
this[$emissiveTexture] =
new TextureInfo(onUpdate, gltf, emissiveTexture, emissiveTextures);
}
}
get name() {
return this[$sourceObject].name || '';
}
get pbrMetallicRoughness() {
return this[$pbrMetallicRoughness];
}
get normalTexture() {
return this[$normalTexture];
}
get occlusionTexture() {
return this[$occlusionTexture];
}
get emissiveTexture() {
return this[$emissiveTexture];
}
get emissiveFactor() {
return this[$sourceObject].emissiveFactor;
}
setEmissiveFactor(rgb) {
for (const material of this[$correlatedObjects]) {
material.emissive.fromArray(rgb);
}
this[$sourceObject].emissiveFactor = rgb;
this[$onUpdate]();
}
} |
JavaScript | class DisconnectedError extends MongooseError {
/**
* @param {String} connectionString
*/
constructor(connectionString) {
super('Ran out of retries trying to reconnect to "' +
connectionString + '". Try setting `server.reconnectTries` and ' +
'`server.reconnectInterval` to something higher.');
}
} |
JavaScript | class LoadSaveDialog extends React.Component {
state = {
open: false,
name: "",
error: false,
save_ok: false,
load_ok: false,
anchor: null,
}
onValueChange = event => {
this.setState({ name: event.target.value })
}
handleClickOpen = () => {
this.setState({ open: true })
}
handleClose = () => {
this.setState({ open: false })
}
handleSave = event => {
let data = this.props.data_to_save(this.state.name)
console.log(data)
if (data.length !== 0) {
localStorage.setItem("data_saved", JSON.stringify(data))
} else {
this.setState({ error: true })
}
this.handleClose()
/* consoltruee.log(event)
this.setState((prevState, props) => ({
saved_ok: true,
ancor: event.currentTarget,
})) */
}
handleLoad = () => {
if (this.state.name !== "") {
this.props.data_to_load(localStorage.getItem(this.state.name))
} else {
this.props.data_to_load(localStorage.getItem("save"))
}
this.handleClose()
}
render() {
return (
<div>
<Button
variant="text"
color="primary"
onClick={this.handleClickOpen}
>
{this.props.action === "save" ? "Save" : "Load"}
</Button>
<Dialog
open={this.state.open}
onClose={this.handleClose}
aria-labelledby="form-dialog-title"
>
<DialogTitle id="form-dialog-title">
{this.props.action === "save"
? "Save the current scenario"
: "Load a scenario"}
</DialogTitle>
<DialogContent>
<DialogContentText>
{this.props.action === "save"
? "You can save the current scenarios. Name the scenario"
: "Select a scenario for loading"}
{this.state.error && (
<Alert severity="error">
No row or country are selected to save.
</Alert>
)}
</DialogContentText>
<TextField
value={this.state.name}
onChange={this.onValueChange}
margin="dense"
name={"scenario"}
id="name"
label="Scenario Name"
type="text"
/>
</DialogContent>
<DialogActions>
<Button onClick={this.handleClose} color="primary">
Cancel
</Button>
{this.props.action === "save" ? (
<Button onClick={this.handleSave} color="primary">
Save
</Button>
) : (
<Button onClick={this.handleLoad} color="primary">
Load
</Button>
)}
</DialogActions>
</Dialog>
{/* {this.state.save_ok && (
<Popover
open={this.state.save_ok}
anchorEl={this.state.anchor}
color={"lightblue"}
anchorOrigin={{
vertical: "center",
horizontal: "center",
}}
transformOrigin={{
vertical: "center",
horizontal: "center",
}}
>
Scenario has been saved
</Popover>
)} */}
</div>
)
}
} |
JavaScript | class LocVar {
constructor() {
this.varname = null;
this.startpc = NaN; /* first point where variable is active */
this.endpc = NaN; /* first point where variable is dead */
}
} |
JavaScript | class SParser {
constructor(z, name, mode) { /* data to 'f_parser' */
this.z = z;
this.buff = new lzio.MBuffer(); /* dynamic structure used by the scanner */
this.dyd = new lparser.Dyndata(); /* dynamic structures used by the parser */
this.mode = mode;
this.name = name;
}
} |
JavaScript | class Vardesc {
constructor() {
this.idx = NaN; /* variable index in stack */
}
} |
JavaScript | class Labeldesc {
constructor() {
this.name = null; /* label identifier */
this.pc = NaN; /* position in code */
this.line = NaN; /* line where it appeared */
this.nactvar = NaN; /* local level where it appears in current block */
}
} |
JavaScript | class Labellist {
constructor() {
this.arr = []; /* array */
this.n = NaN; /* number of entries in use */
this.size = NaN; /* array size */
}
} |
JavaScript | class Dyndata {
constructor() {
this.actvar = { /* list of active local variables */
arr: [],
n: NaN,
size: NaN
};
this.gt = new Labellist();
this.label = new Labellist();
}
} |
JavaScript | class ConsControl {
constructor() {
this.v = new expdesc(); /* last list item read */
this.t = new expdesc(); /* table descriptor */
this.nh = NaN; /* total number of 'record' elements */
this.na = NaN; /* total number of array elements */
this.tostore = NaN; /* number of array elements pending to be stored */
}
} |
JavaScript | class LHS_assign {
constructor() {
this.prev = null;
this.v = new expdesc(); /* variable (global, local, upvalue, or indexed) */
}
} |
JavaScript | class LexState {
constructor() {
this.current = NaN; /* current character (charint) */
this.linenumber = NaN; /* input line counter */
this.lastline = NaN; /* line of last token 'consumed' */
this.t = new Token(); /* current token */
this.lookahead = new Token(); /* look ahead token */
this.fs = null; /* current function (parser) */
this.L = null;
this.z = null; /* input stream */
this.buff = null; /* buffer for tokens */
this.h = null; /* to reuse strings */
this.dyd = null; /* dynamic structures used by the parser */
this.source = null; /* current source name */
this.envn = null; /* environment variable name */
}
} |
JavaScript | class Header {
constructor(L) {
this.L = L;
this.islittle = true;
this.maxalign = 1;
}
} |
JavaScript | class GMatchState {
constructor() {
this.src = NaN; /* current position */
this.p = NaN; /* pattern */
this.lastmatch = NaN; /* end of last match */
this.ms = new MatchState(); /* match state */
}
} |
JavaScript | class DumpState {
constructor() {
this.L = null;
this.write = null;
this.data = null;
this.strip = NaN;
this.status = NaN;
}
} |
JavaScript | class SignUp extends Component {
state = {
email: '',
password: '',
userId: '',
firstname: '',
lastname: '',
emailError: '',
userIdValid: null,
passwordError: '',
firstNameError: false,
lastNameError: false,
isLoading: false,
passwordVisible: false,
}
onChangeUserId = async (text) => {
this.setState({ userId: text });
if (text !== '') {
// this.checkUserId(text);
await db.collection('userId').doc(this.state.userId)
.get()
.then((doc) => {
if (doc.exists) {
this.setState({
userIdValid: false
});
} else {
// doc.data() will be undefined in this case
this.setState({
userIdValid: true
});
}
})
.catch(error => console.log("ERR:", error.message))
}
else {
this.setState({
userIdValid: false
});
}
}
isValidUserId = () => {
if (this.state.userId != '') {
return this.state.userIdValid
}
else {
this.setState({
userIdValid: false
}, () => alert('Invalid User ID'));
return false
}
}
isValidPassword = () => {
if (this.state.password.length >= 8) {
this.setState({
passwordError: '',
})
return true;
}
this.setState({
passwordError: 'Atleast 8 characters',
}, () => alert(this.state.passwordError))
return false;
}
isValidEmail = () => {
if (this.state.email != '') {
this.setState({
emailError: '',
})
return true;
}
this.setState({
emailError: 'Enter a valid email',
}, () => alert(this.state.emailError))
return false;
}
isValidFirstName = () => {
if (this.state.firstname != '') {
this.setState({
firstNameError: false,
})
return true;
}
this.setState({
firstNameError: true,
})
return false;
}
isValidLastName = () => {
if (this.state.lastname != '') {
this.setState({
lastNameError: false,
})
return true;
}
this.setState({
lastNameError: true,
})
return false;
}
onSignUpClick = async () => {
this.setState({ isLoading: true });
// if (true) {
console.log('user id ', this.state.userIdValid);
if (this.isValidEmail() && this.isValidPassword() && this.isValidUserId() && this.isValidFirstName()
&& this.isValidLastName()) {
console.log(this.state.userIdValid);
let user = {
email: this.state.email,
password: this.state.password,
firstname: this.state.firstname,
lastname: this.state.lastname,
dob: new Date(1999, 1 ,1),
userId: this.state.userId,
gender: 0,
// phone: '007'
}
console.log(user);
await this.props.SignUpUser(user)
}
this.setState({ isLoading: false });
}
render() {
if (this.props.isAuthenticated) {
return <MainScreen />
}
else
return (
<Container>
<Content>
<LoaderModal loading={this.state.isLoading} />
<ImageBackground resizeMode='cover' source={require('../../../assets/bgImage.png')} style={{ height: screenHeight }}>
<Animatable.Image
animation="bounceIn"
// duration= {2000}
style={styles.logo}
source={require('../../../assets/logo.png')}
resizeMode="stretch"
/>
<Animatable.View
style={styles.footer}
animation="fadeInUpBig">
<Form>
<Item stackedLabel error={this.state.emailError !== ''}>
<Label>Email *</Label>
<Input style={{ color: '#fff' }}
keyboardType='email-address' error="#f99"
onChangeText={(text) => this.setState({ email: text })} />
</Item>
<Item stackedLabel error={this.state.passwordError !== ''}>
<Label>Password *</Label>
<View style={{ flexDirection: 'row', height: 50, alignItems: 'center' }}>
<Input secureTextEntry={!this.state.passwordVisible} style={{ color: '#fff' }}
onChangeText={(text) => this.setState({ password: text })}
error="#f99" />
<Icon name={this.state.passwordVisible ? 'eye-off' : 'eye'}
style={{ color: '#555', height: 50 }}
onPress={() => this.setState({ passwordVisible: !this.state.passwordVisible })} />
</View>
</Item>
<Item stackedLabel error={this.state.userIdValid===false}>
<Label>UserId *</Label>
<View style={{ flexDirection: 'row', height: 50, alignItems: 'center' }}>
<Input style={{ color: '#fff' }} error="#f99" value={this.state.userId}
onChangeText={(text) => this.onChangeUserId(text)} />
<Icon name={this.state.userIdValid ? 'checkmark' : null}
style={{ color: 'green', height: 50 }} />
</View>
</Item>
<View style={{ flexDirection: 'row' }} >
<Item stackedLabel style={{ flex: 1 }} error={this.state.firstNameError}>
<Label>First Name *</Label>
<Input style={{ color: '#fff' }}
error="#f99" onChangeText={(text) => this.setState({ firstname: text })} />
</Item>
<Item stackedLabel style={{ flex: 1 }} error={this.state.lastNameError}>
<Label>Last Name *</Label>
<Input style={{ color: '#fff' }}
error="#f99" onChangeText={(text) => this.setState({ lastname: text })} />
</Item>
</View>
</Form>
<View style={{ flexDirection: 'row', marginTop: 30, marginLeft: 10 }}>
<Left>
<Text style={{ color: '#ccc', }}>Sign in with Google</Text>
</Left>
<Right>
<Button style={{ backgroundColor: '#05375a', elevation: 10, zIndex: 10 }} rounded block onPress={() => this.onSignUpClick()}>
<Text>SignUp</Text>
</Button>
</Right>
</View>
</Animatable.View>
</ImageBackground>
</Content>
</Container>
)
}
} |
JavaScript | class Route {
constructor() {
this.unsubscribe = () => { return; };
this.componentProps = {};
this.exact = false;
this.group = null;
this.groupIndex = null;
this.routeRender = null;
this.match = null;
}
// Identify if the current route is a match.
computeMatch(pathname) {
if (!pathname) {
const location = this.activeRouter.get('location');
pathname = location.pathname;
}
return matchPath(pathname, {
path: this.url,
exact: this.exact,
strict: true
});
}
componentWillLoad() {
// subscribe the project's active router and listen
// for changes. Recompute the match if any updates get
// pushed
this.unsubscribe = this.activeRouter.subscribe((switchMatched) => {
if (switchMatched) {
this.match = null;
}
else {
this.match = this.computeMatch();
}
return this.match;
}, this.group, this.groupIndex);
if (!this.group) {
this.match = this.computeMatch();
}
}
componentDidUnload() {
// be sure to unsubscribe to the router so that we don't
// get any memory leaks
this.unsubscribe();
}
render() {
// If there is no activeRouter then do not render
// Check if this route is in the matching URL (for example, a parent route)
if (!this.activeRouter || !this.match) {
return null;
}
// component props defined in route
// the history api
// current match data including params
const childProps = Object.assign({}, this.componentProps, { history: this.activeRouter.get('history'), match: this.match });
// If there is a routerRender defined then use
// that and pass the component and component props with it.
if (this.routeRender) {
return this.routeRender(Object.assign({}, childProps, { component: this.component }));
}
if (this.component) {
const ChildComponent = this.component;
return h(ChildComponent, Object.assign({}, childProps));
}
}
static get is() { return "stencil-route"; }
static get properties() { return { "activeRouter": { "context": "activeRouter" }, "component": { "type": String, "attr": "component" }, "componentProps": { "type": "Any", "attr": "component-props" }, "exact": { "type": Boolean, "attr": "exact" }, "group": { "type": String, "attr": "group" }, "groupIndex": { "type": Number, "attr": "group-index" }, "location": { "context": "location" }, "match": { "state": true }, "routeRender": { "type": "Any", "attr": "route-render" }, "url": { "type": "Any", "attr": "url" } }; }
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.