language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Perlin { /** * Create the perlin noise generator. * @param {Number} seed Seed for perlin noise, or undefined for random. */ constructor(seed) { if (seed === undefined) { seed = Math.random(); } this.seed(seed); } /** * Set the perlin noise seed. * @param {Number} seed New seed value. May be either a decimal between 0 to 1, or an unsigned short between 0 to 65536. */ seed(seed) { // scale the seed out if(seed > 0 && seed < 1) { seed *= 65536; } // make sure round and current number of bits seed = Math.floor(seed); if (seed < 256) { seed |= seed << 8; } // create perm, gradP and grad3 arrays var perm = new Array(512); var gradP = new Array(512); var grad3 = [new Grad(1,1,0),new Grad(-1,1,0),new Grad(1,-1,0),new Grad(-1,-1,0), new Grad(1,0,1),new Grad(-1,0,1),new Grad(1,0,-1),new Grad(-1,0,-1), new Grad(0,1,1),new Grad(0,-1,1),new Grad(0,1,-1),new Grad(0,-1,-1)]; // apply seed for(var i = 0; i < 256; i++) { var v; if (i & 1) { v = p[i] ^ (seed & 255); } else { v = p[i] ^ ((seed>>8) & 255); } perm[i] = perm[i + 256] = v; gradP[i] = gradP[i + 256] = grad3[v % 12]; } // store new params this._perm = perm; this._gradP = gradP; } /** * Generate a perlin noise value for x,y coordinates. * @param {Number} x X coordinate to generate perlin noise for. * @param {Number} y Y coordinate to generate perlin noise for. * @param {Number} blurDistance Distance to take neighbors to blur returned value with. Defaults to 0.25. * @param {Number} contrast Optional contrast factor. * @returns {Number} Perlin noise value for given point. */ generateSmooth(x, y, blurDistance, contrast) { if (blurDistance === undefined) { blurDistance = 0.25; } let a = this.generate(x-blurDistance, y-blurDistance, contrast); let b = this.generate(x+blurDistance, y+blurDistance, contrast); let c = this.generate(x-blurDistance, y+blurDistance, contrast); let d = this.generate(x+blurDistance, y-blurDistance, contrast); return (a + b + c + d) / 4; } /** * Generate a perlin noise value for x,y coordinates. * @param {Number} x X coordinate to generate perlin noise for. * @param {Number} y Y coordinate to generate perlin noise for. * @param {Number} contrast Optional contrast factor. * @returns {Number} Perlin noise value for given point, ranged from 0 to 1. */ generate(x, y, contrast) { // default contrast if (contrast === undefined) { contrast = 1; } // store new params let perm = this._perm; let gradP = this._gradP; // find unit grid cell containing point var X = Math.floor(x), Y = Math.floor(y); // get relative xy coordinates of point within that cell x = x - X; y = y - Y; // wrap the integer cells at 255 (smaller integer period can be introduced here) X = X & 255; Y = Y & 255; // calculate noise contributions from each of the four corners var n00 = gradP[X+perm[Y]].dot2(x, y) * contrast; var n01 = gradP[X+perm[Y+1]].dot2(x, y-1) * contrast; var n10 = gradP[X+1+perm[Y]].dot2(x-1, y) * contrast; var n11 = gradP[X+1+perm[Y+1]].dot2(x-1, y-1) * contrast; // compute the fade curve value for x var u = fade(x); // interpolate the four results return Math.min(lerp( lerp(n00, n10, u), lerp(n01, n11, u), fade(y)) + 0.5, 1); }; }
JavaScript
class Rectangle { /** * Create the Rect. * @param {Number} x Rect position X (top left corner). * @param {Number} y Rect position Y (top left corner). * @param {Number} width Rect width. * @param {Number} height Rect height. */ constructor(x, y, width, height) { this.x = x || 0; this.y = y || 0; this.width = width; this.height = height; } /** * Set rectangle values. * @param {Number} x Rectangle x position. * @param {Number} y Rectangle y position. * @param {Number} width Rectangle width. * @param {Number} height Rectangle height. * @returns {Rectangle} this. */ set(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; return this; } /** * Copy another rectangle. * @param {other} other Rectangle to copy. * @returns {Rectangle} this. */ copy(other) { this.x = other.x; this.y = other.y; this.width = other.width; this.height = other.height; return this; } /** * Get position as Vector2. * @returns {Vector2} Position vector. */ getPosition() { return new Vector2(this.x, this.y); } /** * Get size as Vector2. * @returns {Vector2} Size vector. */ getSize() { return new Vector2(this.width, this.height); } /** * Get center position. * @returns {Vector2} Position vector. */ getCenter() { return new Vector2(Math.round(this.x + this.width / 2), Math.round(this.y + this.height / 2)); } /** * Get left value. * @returns {Number} rectangle left. */ get left() { return this.x; } /** * Get right value. * @returns {Number} rectangle right. */ get right() { return this.x + this.width; } /** * Get top value. * @returns {Number} rectangle top. */ get top() { return this.y; } /** * Get bottom value. * @returns {Number} rectangle bottom. */ get bottom() { return this.y + this.height; } /** * Return a clone of this rectangle. * @returns {Rectangle} Cloned rectangle. */ clone() { return new Rectangle(this.x, this.y, this.width, this.height); } /** * Get top-left corner. * @returns {Vector2} Corner position vector. */ getTopLeft() { return new Vector2(this.x, this.y); } /** * Get top-right corner. * @returns {Vector2} Corner position vector. */ getTopRight() { return new Vector2(this.x + this.width, this.y); } /** * Get bottom-left corner. * @returns {Vector2} Corner position vector. */ getBottomLeft() { return new Vector2(this.x, this.y + this.height); } /** * Get bottom-right corner. * @returns {Vector2} Corner position vector. */ getBottomRight() { return new Vector2(this.x + this.width, this.y + this.height); } /** * Convert to string. */ string() { return this.x + ',' + this.y + ',' + this.width + ',' + this.height; } /** * Check if this rectangle contains a Vector2. * @param {Vector2} p Point to check. * @returns {Boolean} if point is contained within the rectangle. */ containsVector(p) { return p.x >= this.x && p.x <= this.x + this.width && p.y >= this.y && p.y <= this.y + this.height; } /** * Check if this rectangle collides with another rectangle. * @param {Rectangle} other Rectangle to check collision with. * @return {Boolean} if rectangles collide. */ collideRect(other) { let r1 = this; let r2 = other; return !(r2.left >= r1.right || r2.right <= r1.left || r2.top >= r1.bottom || r2.bottom <= r1.top); } /** * Check if this rectangle collides with a line. * @param {Line} line Line to check collision with. * @return {Boolean} if rectangle collides with line. */ collideLine(line) { // first check if rectangle contains any of the line points if (this.containsVector(line.from) || this.containsVector(line.to)) { return true; } // now check intersection with the rectangle lines let topLeft = this.getTopLeft(); let topRight = this.getTopRight(); let bottomLeft = this.getBottomLeft(); let bottomRight = this.getBottomRight(); if (line.collideLine(new Line(topLeft, topRight))) { return true; } if (line.collideLine(new Line(topLeft, bottomLeft))) { return true; } if (line.collideLine(new Line(topRight, bottomRight))) { return true; } if (line.collideLine(new Line(bottomLeft, bottomRight))) { return true; } // no collision return false; } /** * Checks if this rectangle collides with a circle. * @param {Circle} circle Circle to check collision with. * @return {Boolean} if rectangle collides with circle. */ collideCircle(circle) { // get center and radius let center = circle.center; let radius = circle.radius; // first check if circle center is inside the rectangle - easy case let rect = this; if (rect.containsVector(center)) { return true; } // get rectangle center let rectCenter = rect.getCenter(); // get corners let topLeft = rect.getTopLeft(); let topRight = rect.getTopRight(); let bottomRight = rect.getBottomRight(); let bottomLeft = rect.getBottomLeft(); // create a list of lines to check (in the rectangle) based on circle position to rect center let lines = []; if (rectCenter.x > center.x) { lines.push([topLeft, bottomLeft]); } else { lines.push([topRight, bottomRight]); } if (rectCenter.y > center.y) { lines.push([topLeft, topRight]); } else { lines.push([bottomLeft, bottomRight]); } // now check intersection between circle and each of the rectangle lines for (let i = 0; i < lines.length; ++i) { let disToLine = pointLineDistance(center, lines[i][0], lines[i][1]); if (disToLine <= radius) { return true; } } // no collision.. return false; } /** * Get the smallest circle containing this rectangle. * @returns {Circle} Bounding circle. */ getBoundingCircle() { let center = this.getCenter(); let radius = center.distanceTo(this.getTopLeft()); return new Circle(center, radius); } /** * Build and return a rectangle from points. * @param {Array<Vector2>} points Points to build rectangle from. * @returns {Rectangle} new rectangle from points. */ static fromPoints(points) { let min_x = points[0].x; let min_y = points[0].y; let max_x = min_x; let max_y = min_y; for (let i = 1; i < points.length; ++i) { min_x = Math.min(min_x, points[i].x); min_y = Math.min(min_y, points[i].y); max_x = Math.max(max_x, points[i].x); max_y = Math.max(max_y, points[i].y); } return new Rectangle(min_x, min_y, max_x - min_x, max_y - min_y); } /** * Return a resized rectangle with the same center point. * @param {Number|Vector2} amount Amount to resize. * @returns {Rectangle} resized rectangle. */ resize(amount) { if (typeof amount === 'number') { amount = new Vector2(amount, amount); } return new Rectangle(this.x - amount.x / 2, this.y - amount.y / 2, this.width + amount.x, this.height + amount.y); } /** * Check if equal to another rectangle. * @param {Rectangle} other Other rectangle to compare to. */ equals(other) { return (this === other) || (other && (other.constructor === this.constructor) && this.x == other.x && this.y == other.y && this.width == other.width && this.height == other.height); } /** * Lerp between two rectangles. * @param {Rectangle} p1 First rectangles. * @param {Rectangle} p2 Second rectangles. * @param {Number} a Lerp factor (0.0 - 1.0). * @returns {Rectangle} result rectangle. */ static lerp(p1, p2, a) { let lerpScalar = MathHelper.lerp; return new Rectangle( lerpScalar(p1.x, p2.x, a), lerpScalar(p1.y, p2.y, a), lerpScalar(p1.width, p2.width, a), lerpScalar(p1.height, p2.height, a) ); } /** * Create rectangle from a dictionary. * @param {*} data Dictionary with {x,y,width,height}. * @returns {Rectangle} Newly created rectangle. */ static fromDict(data) { return new Rectangle(data.x, data.y, data.width, data.height); } /** * Convert to dictionary. * @returns {*} Dictionary with {x,y,width,height} */ toDict() { return {x: this.x, y: this.y, width: this.width, height: this.height}; } }
JavaScript
class SeededRandom { /** * Create the seeded random object. * @param {Number} seed Seed to start from. If not provided, will use 0. */ constructor(seed) { if (seed === undefined) { seed = 0; } this.seed = seed; } /** * Get next random value. * @param {Number} min Optional min value. If max is not provided, this will be used as max. * @param {Number} max Optional max value. * @returns {Number} A randomly generated value. */ random(min, max) { // generate next value this.seed = (this.seed * 9301 + 49297) % 233280; let rnd = this.seed / 233280; // got min and max? if (min && max) { return min + rnd * (max - min); } // got only min (used as max)? else if (min) { return rnd * min; } // no min nor max provided return rnd; } /** * Pick a random value from array. * @param {Array} options Options to pick random value from. * @returns {*} Random value from options array. */ pick(options) { return options[Math.floor(this.random(options.length))]; } }
JavaScript
class Vector2 { /** * Create the Vector object. * @param {number} x Vector X. * @param {number} y Vector Y. */ constructor(x = 0, y = 0) { this.x = x; this.y = y; } /** * Clone the vector. * @returns {Vector2} cloned vector. */ clone() { return new Vector2(this.x, this.y); } /** * Set vector value. * @param {Number} x X component. * @param {Number} y Y component. * @returns {Vector2} this. */ set(x, y) { this.x = x; this.y = y; return this; } /** * Copy values from other vector into self. * @returns {Vector2} this. */ copy(other) { this.x = other.x; this.y = other.y; return this; } /** * Return a new vector of this + other. * @param {Number|Vector2} Other Vector or number to add. * @returns {Vector2} result vector. */ add(other) { if (typeof other === 'number') { return new Vector2(this.x + other, this.y + (arguments[1] === undefined ? other : arguments[1])); } return new Vector2(this.x + other.x, this.y + other.y); } /** * Return a new vector of this - other. * @param {Number|Vector2} Other Vector or number to sub. * @returns {Vector2} result vector. */ sub(other) { if (typeof other === 'number') { return new Vector2(this.x - other, this.y - (arguments[1] === undefined ? other : arguments[1])); } return new Vector2(this.x - other.x, this.y - other.y); } /** * Return a new vector of this / other. * @param {Number|Vector2} Other Vector or number to divide. * @returns {Vector2} result vector. */ div(other) { if (typeof other === 'number') { return new Vector2(this.x / other, this.y / (arguments[1] === undefined ? other : arguments[1])); } return new Vector2(this.x / other.x, this.y / other.y); } /** * Return a new vector of this * other. * @param {Number|Vector2} Other Vector or number to multiply. * @returns {Vector2} result vector. */ mul(other) { if (typeof other === 'number') { return new Vector2(this.x * other, this.y * (arguments[1] === undefined ? other : arguments[1])); } return new Vector2(this.x * other.x, this.y * other.y); } /** * Return a round copy of this vector. * @returns {Vector2} result vector. */ round() { return new Vector2(Math.round(this.x), Math.round(this.y)); } /** * Return a floored copy of this vector. * @returns {Vector2} result vector. */ floor() { return new Vector2(Math.floor(this.x), Math.floor(this.y)); } /** * Return a ceiled copy of this vector. * @returns {Vector2} result vector. */ ceil() { return new Vector2(Math.ceil(this.x), Math.ceil(this.y)); } /** * Return a normalized copy of this vector. * @returns {Vector2} result vector. */ normalized() { if (this.x == 0 && this.y == 0) { return Vector2.zero; } let mag = this.length; return new Vector2(this.x / mag, this.y / mag); } /** * Add other vector values to self. * @param {Number|Vector2} Other Vector or number to add. * @returns {Vector2} this. */ addSelf(other) { if (typeof other === 'number') { this.x += other; this.y += (arguments[1] === undefined ? other : arguments[1]); } else { this.x += other.x; this.y += other.y; } return this; } /** * Sub other vector values from self. * @param {Number|Vector2} Other Vector or number to substract. * @returns {Vector2} this. */ subSelf(other) { if (typeof other === 'number') { this.x -= other; this.y -= (arguments[1] === undefined ? other : arguments[1]); } else { this.x -= other.x; this.y -= other.y; } return this; } /** * Divide this vector by other vector values. * @param {Number|Vector2} Other Vector or number to divide by. * @returns {Vector2} this. */ divSelf(other) { if (typeof other === 'number') { this.x /= other; this.y /= (arguments[1] === undefined ? other : arguments[1]); } else { this.x /= other.x; this.y /= other.y; } return this; } /** * Multiply this vector by other vector values. * @param {Number|Vector2} Other Vector or number to multiply by. * @returns {Vector2} this. */ mulSelf(other) { if (typeof other === 'number') { this.x *= other; this.y *= (arguments[1] === undefined ? other : arguments[1]); } else { this.x *= other.x; this.y *= other.y; } return this; } /** * Round self. * @returns {Vector2} this. */ roundSelf() { this.x = Math.round(this.x); this.y = Math.round(this.y); return this; } /** * Floor self. * @returns {Vector2} this. */ floorSelf() { this.x = Math.floor(this.x); this.y = Math.floor(this.y); return this; } /** * Ceil self. * @returns {Vector2} this. */ ceilSelf() { this.x = Math.ceil(this.x); this.y = Math.ceil(this.y); return this; } /** * Return a normalized copy of this vector. * @returns {Vector2} this. */ normalizeSelf() { if (this.x == 0 && this.y == 0) { return this; } let mag = this.length; this.x /= mag; this.y /= mag; return this; } /** * Return if vector equals another vector. * @param {Vector2} other Other vector to compare to. * @returns {Boolean} if vectors are equal. */ equals(other) { return ((this === other) || ((other.constructor === this.constructor) && this.x === other.x && this.y === other.y)); } /** * Return if vector approximately equals another vector. * @param {Vector2} other Other vector to compare to. * @param {Number} threshold Distance threshold to consider as equal. Defaults to 1. * @returns {Boolean} if vectors are equal. */ approximate(other, threshold) { threshold = threshold || 1; return ((this === other) || ( (Math.abs(this.x - other.x) <= threshold) && (Math.abs(this.y - other.y) <= threshold)) ); } /** * Return vector length (aka magnitude). * @returns {Number} Vector length. */ get length() { return Math.sqrt((this.x * this.x) + (this.y * this.y)); } /** * Return a copy of this vector multiplied by a factor. * @returns {Vector2} result vector. */ scaled(fac) { return new Vector2(this.x * fac, this.y * fac); } /** * Get vector (0,0). * @returns {Vector2} result vector. */ static get zero() { return new Vector2(); } /** * Get vector with 1,1 values. * @returns {Vector2} result vector. */ static get one() { return new Vector2(1, 1); } /** * Get vector with 0.5,0.5 values. * @returns {Vector2} result vector. */ static get half() { return new Vector2(0.5, 0.5); } /** * Get vector with -1,0 values. * @returns {Vector2} result vector. */ static get left() { return new Vector2(-1, 0); } /** * Get vector with 1,0 values. * @returns {Vector2} result vector. */ static get right() { return new Vector2(1, 0); } /** * Get vector with 0,-1 values. * @returns {Vector2} result vector. */ static get up() { return new Vector2(0, -1); } /** * Get vector with 0,1 values. * @returns {Vector2} result vector. */ static get down() { return new Vector2(0, 1); } /** * Get degrees between this vector and another vector. * @param {Vector2} other Other vector. * @returns {Number} Angle between vectors in degrees. */ degreesTo(other) { return Vector2.degreesBetween(this, other); }; /** * Get radians between this vector and another vector. * @param {Vector2} other Other vector. * @returns {Number} Angle between vectors in radians. */ radiansTo(other) { return Vector2.radiansBetween(this, other); }; /** * Get degrees between this vector and another vector. * Return values between 0 to 360. * @param {Vector2} other Other vector. * @returns {Number} Angle between vectors in degrees. */ degreesToFull(other) { return Vector2.degreesBetweenFull(this, other); }; /** * Get radians between this vector and another vector. * Return values between 0 to PI2. * @param {Vector2} other Other vector. * @returns {Number} Angle between vectors in radians. */ radiansToFull(other) { return Vector2.radiansBetweenFull(this, other); }; /** * Calculate distance between this vector and another vectors. * @param {Vector2} other Other vector. * @returns {Number} Distance between vectors. */ distanceTo(other) { return Vector2.distance(this, other); } /** * Get vector from degrees. * @param {Number} degrees Angle to create vector from (0 = vector pointing right). * @returns {Vector2} result vector. */ static fromDegree(degrees) { let rads = degrees * (Math.PI / 180); return new Vector2(Math.cos(rads), Math.sin(rads)); } /** * Get vector from radians. * @param {Number} radians Angle to create vector from (0 = vector pointing right). * @returns {Vector2} result vector. */ static fromRadians(radians) { return new Vector2(Math.cos(radians), Math.sin(radians)); } /** * Lerp between two vectors. * @param {Vector2} p1 First vector. * @param {Vector2} p2 Second vector. * @param {Number} a Lerp factor (0.0 - 1.0). * @returns {Vector2} result vector. */ static lerp(p1, p2, a) { let lerpScalar = MathHelper.lerp; return new Vector2(lerpScalar(p1.x, p2.x, a), lerpScalar(p1.y, p2.y, a)); } /** * Get degrees between two vectors. * Return values between -180 to 180. * @param {Vector2} p1 First vector. * @param {Vector2} p2 Second vector. * @returns {Number} Angle between vectors in degrees. */ static degreesBetween(P1, P2) { let deltaY = P2.y - P1.y, deltaX = P2.x - P1.x; return Math.atan2(deltaY, deltaX) * (180 / Math.PI); }; /** * Get radians between two vectors. * Return values between -PI to PI. * @param {Vector2} p1 First vector. * @param {Vector2} p2 Second vector. * @returns {Number} Angle between vectors in radians. */ static radiansBetween(P1, P2) { return MathHelper.toRadians(Vector2.degreesBetween(P1, P2)); }; /** * Get degrees between two vectors. * Return values between 0 to 360. * @param {Vector2} p1 First vector. * @param {Vector2} p2 Second vector. * @returns {Number} Angle between vectors in degrees. */ static degreesBetweenFull(P1, P2) { let temp = P2.sub(P1); return temp.getDegrees(); }; /** * Get vector's angle in degrees. * @returns {Number} Vector angle in degrees. */ getDegrees() { var angle = Math.atan2(this.y, this.x); var degrees = 180 * angle / Math.PI; return (360+Math.round(degrees)) % 360; } /** * Get vector's angle in radians. * @returns {Number} Vector angle in degrees. */ getRadians() { var angle = Math.atan2(this.y, this.x); return angle; } /** * Get radians between two vectors. * Return values between 0 to PI2. * @param {Vector2} p1 First vector. * @param {Vector2} p2 Second vector. * @returns {Number} Angle between vectors in radians. */ static radiansBetweenFull(P1, P2) { return MathHelper.toRadians(Vector2.degreesBetweenFull(P1, P2)); }; /** * Calculate distance between two vectors. * @param {Vector2} p1 First vector. * @param {Vector2} p2 Second vector. * @returns {Number} Distance between vectors. */ static distance(p1, p2) { let a = p1.x - p2.x; let b = p1.y - p2.y; return Math.sqrt(a*a + b*b); } /** * Return cross product between two vectors. * @param {Vector2} p1 First vector. * @param {Vector2} p2 Second vector. * @returns {Number} Cross between vectors. */ static cross(p1, p2) { return p1.x * p2.y - p1.y * p2.x; } /** * Return dot product between two vectors. * @param {Vector2} p1 First vector. * @param {Vector2} p2 Second vector. * @returns {Number} Dot between vectors. */ static dot(p1, p2) { return p1.x * p2.x + p1.y * p2.y; } /** * Convert to string. */ string() { return this.x + ',' + this.y; } /** * Parse and return a vector object from string in the form of "x,y". * @param {String} str String to parse. * @returns {Vector2} Parsed vector. */ static parse(str) { let parts = str.split(','); return new Vector2(parseFloat(parts[0].trim()), parseFloat(parts[1].trim())); } /** * Convert to array of numbers. * @returns {Array<Number>} Vector components as array. */ toArray() { return [this.x, this.y]; } /** * Create vector from array of numbers. * @param {Array<Number>} arr Array of numbers to create vector from. * @returns {Vector2} Vector instance. */ static fromArray(arr) { return new Vector2(arr[0], arr[1]); } /** * Create vector from a dictionary. * @param {*} data Dictionary with {x,y}. * @returns {Vector2} Newly created vector. */ static fromDict(data) { return new Vector2(data.x, data.y); } /** * Convert to dictionary. * @returns {*} Dictionary with {x,y} */ toDict() { return {x: this.x, y: this.y}; } }
JavaScript
class Vector3 { /** * Create the Vector object. * @param {number} x Vector X. * @param {number} y Vector Y. * @param {number} z Vector Z. */ constructor(x = 0, y = 0, z = 0) { this.x = x; this.y = y; this.z = z; } /** * Clone the vector. * @returns {Vector3} cloned vector. */ clone() { return new Vector3(this.x, this.y, this.z); } /** * Set vector value. * @param {Number} x X component. * @param {Number} y Y component. * @param {Number} z Z component. * @returns {Vector3} this. */ set(x, y) { this.x = x; this.y = y; this.z = z; return this; } /** * Copy values from other vector into self. * @returns {Vector3} this. */ copy(other) { this.x = other.x; this.y = other.y; this.z = other.z; return this; } /** * Return a new vector of this + other. * @param {Number|Vector3} Other Vector or number to add. * @returns {Vector3} result vector. */ add(other) { if (typeof other === 'number') { return new Vector3( this.x + other, this.y + (arguments[1] === undefined ? other : arguments[1]), this.z + (arguments[2] === undefined ? other : arguments[2]) ); } return new Vector3(this.x + other.x, this.y + other.y, this.z + other.z); } /** * Return a new vector of this - other. * @param {Number|Vector3} Other Vector or number to sub. * @returns {Vector3} result vector. */ sub(other) { if (typeof other === 'number') { return new Vector3( this.x - other, this.y - (arguments[1] === undefined ? other : arguments[1]), this.z - (arguments[2] === undefined ? other : arguments[2]) ); } return new Vector3(this.x - other.x, this.y - other.y, this.z - other.z); } /** * Return a new vector of this / other. * @param {Number|Vector3} Other Vector or number to divide. * @returns {Vector3} result vector. */ div(other) { if (typeof other === 'number') { return new Vector3( this.x / other, this.y / (arguments[1] === undefined ? other : arguments[1]), this.z / (arguments[2] === undefined ? other : arguments[2]) ); } return new Vector3(this.x / other.x, this.y / other.y, this.z / other.z); } /** * Return a new vector of this * other. * @param {Number|Vector3} Other Vector or number to multiply. * @returns {Vector3} result vector. */ mul(other) { if (typeof other === 'number') { return new Vector3( this.x * other, this.y * (arguments[1] === undefined ? other : arguments[1]), this.z * (arguments[2] === undefined ? other : arguments[2]) ); } return new Vector3(this.x * other.x, this.y * other.y, this.z * other.z); } /** * Return a round copy of this vector. * @returns {Vector3} result vector. */ round() { return new Vector3(Math.round(this.x), Math.round(this.y), Math.round(this.z)); } /** * Return a floored copy of this vector. * @returns {Vector3} result vector. */ floor() { return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z)); } /** * Return a ceiled copy of this vector. * @returns {Vector3} result vector. */ ceil() { return new Vector3(Math.ceil(this.x), Math.ceil(this.y), Math.ceil(this.z)); } /** * Return a normalized copy of this vector. * @returns {Vector3} result vector. */ normalized() { if (this.x == 0 && this.y == 0 && this.z == 0) { return Vector3.zero; } let mag = this.length; return new Vector3(this.x / mag, this.y / mag, this.z / mag); } /** * Add other vector values to self. * @param {Number|Vector3} Other Vector or number to add. * @returns {Vector3} this. */ addSelf(other) { if (typeof other === 'number') { this.x += other; this.y += (arguments[1] === undefined ? other : arguments[1]); this.z += (arguments[2] === undefined ? other : arguments[2]); } else { this.x += other.x; this.y += other.y; this.z += other.z; } return this; } /** * Sub other vector values from self. * @param {Number|Vector3} Other Vector or number to substract. * @returns {Vector3} this. */ subSelf(other) { if (typeof other === 'number') { this.x -= other; this.y -= (arguments[1] === undefined ? other : arguments[1]); this.z -= (arguments[2] === undefined ? other : arguments[2]); } else { this.x -= other.x; this.y -= other.y; this.z -= other.z; } return this; } /** * Divide this vector by other vector values. * @param {Number|Vector3} Other Vector or number to divide by. * @returns {Vector3} this. */ divSelf(other) { if (typeof other === 'number') { this.x /= other; this.y /= (arguments[1] === undefined ? other : arguments[1]); this.z /= (arguments[2] === undefined ? other : arguments[2]); } else { this.x /= other.x; this.y /= other.y; this.z /= other.z; } return this; } /** * Multiply this vector by other vector values. * @param {Number|Vector3} Other Vector or number to multiply by. * @returns {Vector3} this. */ mulSelf(other) { if (typeof other === 'number') { this.x *= other; this.y *= (arguments[1] === undefined ? other : arguments[1]); this.z *= (arguments[2] === undefined ? other : arguments[2]); } else { this.x *= other.x; this.y *= other.y; this.z *= other.z; } return this; } /** * Round self. * @returns {Vector3} this. */ roundSelf() { this.x = Math.round(this.x); this.y = Math.round(this.y); this.z = Math.round(this.z); return this; } /** * Floor self. * @returns {Vector3} this. */ floorSelf() { this.x = Math.floor(this.x); this.y = Math.floor(this.y); this.z = Math.floor(this.z); return this; } /** * Ceil self. * @returns {Vector3} this. */ ceilSelf() { this.x = Math.ceil(this.x); this.y = Math.ceil(this.y); this.z = Math.ceil(this.z); return this; } /** * Return a normalized copy of this vector. * @returns {Vector3} this. */ normalizeSelf() { if (this.x == 0 && this.y == 0 && this.z == 0) { return this; } let mag = this.length; this.x /= mag; this.y /= mag; this.z /= mag; return this; } /** * Return if vector equals another vector. * @param {Vector3} other Other vector to compare to. * @returns {Boolean} if vectors are equal. */ equals(other) { return ((this === other) || ((other.constructor === this.constructor) && this.x === other.x && this.y === other.y && this.z === other.z) ); } /** * Return if vector approximately equals another vector. * @param {Vector3} other Other vector to compare to. * @param {Number} threshold Distance threshold to consider as equal. Defaults to 1. * @returns {Boolean} if vectors are equal. */ approximate(other, threshold) { threshold = threshold || 1; return ( (this === other) || ((Math.abs(this.x - other.x) <= threshold) && (Math.abs(this.y - other.y) <= threshold) && (Math.abs(this.z - other.z) <= threshold)) ); } /** * Return vector length (aka magnitude). * @returns {Number} Vector length. */ get length() { return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z)); } /** * Return a copy of this vector multiplied by a factor. * @returns {Vector3} result vector. */ scaled(fac) { return new Vector3(this.x * fac, this.y * fac, this.z * fac); } /** * Get vector (0,0). * @returns {Vector3} result vector. */ static get zero() { return new Vector3(); } /** * Get vector with 1,1 values. * @returns {Vector3} result vector. */ static get one() { return new Vector3(1, 1, 1); } /** * Get vector with 0.5,0.5 values. * @returns {Vector3} result vector. */ static get half() { return new Vector3(0.5, 0.5, 0.5); } /** * Get vector with -1,0 values. * @returns {Vector3} result vector. */ static get left() { return new Vector3(-1, 0, 0); } /** * Get vector with 1,0 values. * @returns {Vector3} result vector. */ static get right() { return new Vector3(1, 0, 0); } /** * Get vector with 0,-1 values. * @returns {Vector3} result vector. */ static get up() { return new Vector3(0, -1, 0); } /** * Get vector with 0,1 values. * @returns {Vector3} result vector. */ static get down() { return new Vector3(0, 1, 0); } /** * Get vector with 0,0,-1 values. * @returns {Vector3} result vector. */ static get front() { return new Vector3(0, 0, -1); } /** * Get vector with 0,0,1 values. * @returns {Vector3} result vector. */ static get back() { return new Vector3(0, 0, 1); } /** * Calculate distance between this vector and another vectors. * @param {Vector3} other Other vector. * @returns {Number} Distance between vectors. */ distanceTo(other) { return Vector3.distance(this, other); } /** * Lerp between two vectors. * @param {Vector3} p1 First vector. * @param {Vector3} p2 Second vector. * @param {Number} a Lerp factor (0.0 - 1.0). * @returns {Vector3} result vector. */ static lerp(p1, p2, a) { let lerpScalar = MathHelper.lerp; return new Vector3(lerpScalar(p1.x, p2.x, a), lerpScalar(p1.y, p2.y, a), lerpScalar(p1.z, p2.z, a)); } /** * Calculate distance between two vectors. * @param {Vector3} p1 First vector. * @param {Vector3} p2 Second vector. * @returns {Number} Distance between vectors. */ static distance(p1, p2) { let a = p1.x - p2.x; let b = p1.y - p2.y; let c = p1.z - p2.z; return Math.sqrt(a*a + b*b + c*c); } /** * Return cross product between two vectors. * @param {Vector3} p1 First vector. * @param {Vector3} p2 Second vector. * @returns {Vector3} Crossed vector. */ static crossVector(p1, p2) { const ax = p1.x, ay = p1.y, az = p1.z; const bx = p2.x, by = p2.y, bz = p2.z; let x = ay * bz - az * by; let y = az * bx - ax * bz; let z = ax * by - ay * bx; return new Vector3(x, y, z); } /** * Convert to string. */ string() { return this.x + ',' + this.y + ',' + this.z; } /** * Parse and return a vector object from string in the form of "x,y". * @param {String} str String to parse. * @returns {Vector3} Parsed vector. */ static parse(str) { let parts = str.split(','); return new Vector3(parseFloat(parts[0].trim()), parseFloat(parts[1].trim()), parseFloat(parts[2].trim())); } /** * Convert to array of numbers. * @returns {Array<Number>} Vector components as array. */ toArray() { return [this.x, this.y, this.z]; } /** * Create vector from array of numbers. * @param {Array<Number>} arr Array of numbers to create vector from. * @returns {Vector3} Vector instance. */ static fromArray(arr) { return new Vector3(arr[0], arr[1], arr[2]); } /** * Create vector from a dictionary. * @param {*} data Dictionary with {x,y,z}. * @returns {Vector3} Newly created vector. */ static fromDict(data) { return new Vector3(data.x, data.y, data.z); } /** * Convert to dictionary. * @returns {*} Dictionary with {x,y,z} */ toDict() { return {x: this.x, y: this.y, z: this.z}; } }
JavaScript
class ButtonGroup { constructor() { /** A label to use for the button group's `aria-label` attribute. */ this.label = ''; } connectedCallback() { this.handleFocus = this.handleFocus.bind(this); this.handleBlur = this.handleBlur.bind(this); } componentDidLoad() { this.buttonGroup.addEventListener('sl-focus', this.handleFocus); this.buttonGroup.addEventListener('sl-blur', this.handleBlur); } disconnectedCallback() { this.buttonGroup.removeEventListener('sl-focus', this.handleFocus); this.buttonGroup.removeEventListener('sl-blur', this.handleBlur); } handleFocus(event) { const button = event.target; button.classList.add('sl-focus'); } handleBlur(event) { const button = event.target; button.classList.remove('sl-focus'); } render() { return (h("div", { ref: el => (this.buttonGroup = el), part: "base", class: "button-group", "aria-label": this.label }, h("slot", null))); } static get is() { return "sl-button-group"; } static get encapsulation() { return "shadow"; } static get originalStyleUrls() { return { "$": ["button-group.scss"] }; } static get styleUrls() { return { "$": ["button-group.css"] }; } static get properties() { return { "label": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "A label to use for the button group's `aria-label` attribute." }, "attribute": "label", "reflect": false, "defaultValue": "''" } }; } }
JavaScript
class Request { /** * Slave constructor. * @param {Slave} slave The slave associated with this request. * @param {String} command The command for this request. * @param {Object} meta Meta data for this request. * @param {Object} data The data to send with this request. * @param {String} secretId A string to prevent accidentally sending a slave request. * @param {Number} secretNumber A number to help prevent accidentally sending a slave request by mistake. * @param {Symbol} slaveSymbol The private slave symbol. * @param {Function=} callback The callback to invoke when this request is responded to. * @return {Slave} The newly created slave instance. */ constructor(slave, command, meta, data, secretId, secretNumber, slaveSymbol, callback) { // Check arguments... if (!(slave instanceof require('./Slave'))) { // eslint-disable-line global-require throw new TypeError('Request argument #0 (slave) expected a an instanceof Slave.'); } else if (typeof secretId !== 'string') { throw new TypeError(`Request argument #4 (secretId) expected a string, but got ${typeof secretId}.`); } else if (typeof secretNumber !== 'number') { throw new TypeError(`Request argument #5 (secretNumber) expected a number, but got ${typeof secretNumber}.`); } else if (typeof meta !== 'object') { throw new TypeError(`Request argument #2 (meta) expected an object, but got ${typeof object}.`); } meta = meta || {}; // Validate command argument... switch (command) { // The command to gracefully exit the slave process. case Commands.EXIT: command = '__dist.io__exit__'; break; // The command to send an acknowledgement to the slave. case Commands.ACK: command = '__dist.io__ack__'; break; // Sends a no-op command. case Commands.NULL: command = '__dist.io__null__'; break; // Sends a SIGINT command case Commands.REMOTE_KILL_SIGINT: command = '__dist.io__remote__kill__SIGINT__'; break; // Sends a SIGTERM command case Commands.REMOTE_KILL_SIGTERM: command = '__dist.io__remote__kill__SIGTERM__'; break; // Sends a SIGHUP command case Commands.REMOTE_KILL_SIGHUP: command = '__dist.io__remote__kill__SIGHUP__'; break; // Sends a SIGKILL command case Commands.REMOTE_KILL_SIGKILL: command = '__dist.io__remote__kill__SIGKILL__'; break; // Sends a SIGBREAK command case Commands.REMOTE_KILL_SIGBREAK: command = '__dist.io__remote__kill__SIGBREAK__'; break; // Sends a SIGSTOP command case Commands.REMOTE_KILL_SIGSTOP: command = '__dist.io__remote__kill__SIGSTOP__'; break; // Sends a user command. default: if (typeof command !== 'string') { throw new TypeError(`Request constructor argument #0 (command) expect a string, but got ${typeof command}.`); } } const created = Date.now(); const timeout = meta.timeout ? meta.timeout._.getNumeric() : null; /** * Protected properties for this Request instance. * @namespace RequestProtected */ this[request] = { /** * The request id. * @type {Number} */ rid: rids++, /** * The time the request was created in nanoseconds. * @type {Number} */ created, /** * The slave process associated with this request. * @type {Slave} */ slave, /** * The command for this request. * @type {String} */ command, /** * Metadata for this request. * @type {Object} */ meta, /** * The data to send with this request. * @type {Object} */ data, /** * The callback to be invoked when this request is complete. * @type {Function} * @return {undefined} */ callback: callback instanceof Function ? callback : () => {}, /** * The duration before this request times out. <= Zero means never. * @type {Object} */ ttl: 0, /** * The Timeout object associated with this request (the actual timeout). * @type {Timeout} */ timeout: null, /** * A function to invoke when the request times out. * @type {Function} * @return {undefined} */ onTimeout: () => {}, /** * The secret id from the Slave module. * @type {String} */ secretId, /** * The secret tiem from the Slave module. * @type {Number} */ secretNumber, /** * The symbol object passed in by the slave process. * @type {Symbol} */ slaveSymbol, }; if (timeout && timeout._.isNumeric()) { this[request].ttl = timeout; this[request].timeout = setTimeout(() => { this[request].onTimeout(); }, timeout); } } /** * The request id. * @return {Number} The request id. */ get id() { return this[request].rid; } /** * The request id (an alias for Request#id). * @return {Number} The request id. */ get rid() { return this[request].rid; } /** * The request time to live. * @return {Number} The request TTL. */ get ttl() { return this[request].ttl; } /** * The request's command * @return {String} The request's command. */ get command() { return this[request].command; } /** * Returns the time the Request was created. * @return {Number} The time in nanoseconds. */ get created() { return this[request].created; } /** * Returns the request's callback. * @return {Function} The callback to invoked when the response is received for this request. */ get callback() { return this[request].callback; } /** * Sends the request. * @return {Request} The current request instance. */ send() { this[request].slave[this[request].slaveSymbol].process.send(this.raw); return this; } /** * @return {Object} Exports the request as a stringifiable object. */ get raw() { return { sent: Date.now(), rid: this[request].rid, for: this[request].slave.id, meta: this[request].meta, data: this[request].data, command: this[request].command, created: this[request].created, secretId: this[request].secretId, secretNumber: this[request].secretNumber, title: 'MasterIOMessage', }; } /** * Checks whether or not the Request has timedout. * @param {Response} response The received message. * @return {Boolean} True if the message has timedout, false otherwise. */ hasTimedout(response) { if (!(response instanceof Response)) { throw new TypeError('Request#hasTimedout expected argument #0 (response) to be an instanceof Response.'); } if (this.ttl !== 0 && this[request].timeout && this.ttl < (response.received - this.created)) return true; return false; } /** * A callback that is invoked when the request times out. * @param {Function} callback The callback to invoked when the request times out. * @return {Request} The current request instance. */ onTimeout(callback) { if (callback instanceof Function) this[request].onTimeout = callback; return this; } /** * Clears the Request timeout. * @return {Request} The current request instance. */ clearTimeout() { clearTimeout(this[request].timeout); return this; } }
JavaScript
class SteinaBlocks { constructor (runtime) { /** * The runtime instantiating this block package. * @type {Runtime} */ this.runtime = runtime; if (this.runtime) { this.runtime.on('PROJECT_STOP_ALL', () => { this.runtime.videoState.playing = {}; this.runtime.audioState.playing = {}; this.runtime.targets.forEach(t => { if (t.hasOwnProperty("nonblockingSoundsAvailable")) { t.nonblockingSoundsAvailable = AudioTarget.MAX_SIMULTANEOUS_NONBLOCKING_SOUNDS; } }) }); } } /** * @returns {object} metadata for this extension and its blocks. */ getInfo () { return { id: 'steina', name: 'Steina', // blockIconURI: blockIconURI, blocks: [ // Video { opcode: 'playEntireVideoUntilDone', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.playEntireVideoUntilDone', default: 'play from start to end', description: 'plays the entire video at current playback rate from the first frame ' + 'until reaching the last frame' }) }, { opcode: 'playVideoFromAToB', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.playVideoFromAToB', default: 'play from [MARKER_A] to [MARKER_B]', description: 'plays the video at current playback rate from the first marker argument ' + 'until the second marker argument' }), arguments: { MARKER_A: { type: ArgumentType.STRING, menu: 'markers', defaultValue: 'start' }, MARKER_B: { type: ArgumentType.STRING, menu: 'markers', defaultValue: 'end' } } }, { opcode: 'playForwardReverseUntilDone', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.playForwardReverseUntilDone', default: 'play [DIRECTION]', description: 'plays the video at current playback rate from the current frame ' + 'until reaching either the final frame (forward) or the first frame (reverse) ' + 'while blocking the execution thread' }), arguments: { DIRECTION: { type: ArgumentType.STRING, menu: 'directions', defaultValue: VideoDirections.FORWARD } } }, { opcode: 'startPlayingForwardReverse', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.startPlayingForwardReverse', default: 'start playing [DIRECTION]', description: 'plays the video at current playback rate from the current frame ' + 'until reaching either the final frame (forward) or the first frame (reverse)' }), arguments: { DIRECTION: { type: ArgumentType.STRING, menu: 'directions', defaultValue: VideoDirections.FORWARD } } }, { opcode: 'startPlaying', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.startPlaying', default: 'start playing video', description: 'plays the video at the current rate wihtout blocking the thread ' + 'until reaching the end' }) }, { opcode: 'stopPlaying', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.stopPlaying', default: 'stop playing', description: 'stops the video at the current frame, if necessary' }) }, { opcode: 'goToFrame', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.goToFrame', default: 'jump to frame [FRAME]', description: 'sets the current video frame' }), arguments: { FRAME: { type: ArgumentType.NUMBER, defaultValue: 0 } } }, { opcode: 'playNFrames', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.playNFrames', default: 'play [FRAMES] frames until done', description: 'plays FRAMES frames at the current playback rate ' + 'blocking the thread until completion' }), arguments: { FRAMES: { type: ArgumentType.NUMBER, defaultValue: 30 // One second } } }, { opcode: 'playForwardUntilDone', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.playForwardUntilDone', default: 'play forward until done', description: 'plays the video at the absolute value of the playback rate ' + 'from the current frame until reaching the last frame' }) }, { opcode: 'playBackwardUntilDone', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.playBackwardUntilDone', default: 'play backward until done', description: 'plays the video at the negative absolute value of the playback rate ' + 'from the current frame until reaching the first frame' }) }, { opcode: 'nextFrame', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.nextFrame', default: 'go to next frame', description: 'increments the current video frame' }) }, { opcode: 'previousFrame', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.previousFrame', default: 'go to previous frame', description: 'decrements the current video frame' }) }, { opcode: 'changeEffectBy', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.changeEffectBy', default: 'change [EFFECT] effect by [CHANGE]', description: 'changes the selected effect parameter by the specified value' }), arguments: { EFFECT: { type: ArgumentType.STRING, menu: 'effects', defaultValue: VideoEffects.COLOR }, VALUE: { type: ArgumentType.NUMBER, defaultValue: 5 } } }, { opcode: 'setEffectTo', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.setEffectTo', default: 'set [EFFECT] effect to [VALUE]', description: 'sets the effect parameter for the selected effect' }), arguments: { EFFECT: { type: ArgumentType.STRING, menu: 'effects', defaultValue: VideoEffects.COLOR }, VALUE: { type: ArgumentType.NUMBER, defaultValue: 5 } } }, { opcode: 'clearVideoEffects', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.clearVideoEffects', default: 'clear video effects', description: 'reset video effects state to the default' }) }, { opcode: 'whenReached', blockType: BlockType.HAT, text: formatMessage({ id: 'steina.video.whenReached', default: 'when I reach [MARKER]', description: 'triggers when the video is playing and passes/reaches the specified marker or start/end point' }), arguments: { MARKER: { type: ArgumentType.STRING, menu: 'markers' } } }, { opcode: 'whenPlayedToEnd', text: formatMessage({ id: 'steina.video.whenPlayedToEnd', default: 'when played to end', description: 'triggers when the video is playing and reaches the final frame' }), blockType: BlockType.HAT }, { opcode: 'whenPlayedToBeginning', text: formatMessage({ id: 'steina.video.whenPlayedToBeginning', default: 'when played to beginning', description: 'triggers when the video is playing and reaches the first frame (for example, when playing in reverse)' }), blockType: BlockType.HAT }, { opcode: 'whenTapped', text: formatMessage({ id: 'steina.video.whenTapped', default: 'when tapped', description: 'triggers when the video is tapped by the user' }), blockType: BlockType.HAT }, { opcode: 'getCurrentFrame', text: formatMessage({ id: 'steina.video.getCurrentFrame', default: 'current frame', description: 'reports the current frame of the video' }), blockType: BlockType.REPORTER }, { opcode: 'getTotalFrames', text: formatMessage({ id: 'steina.video.getTotalFrames', default: 'total frames', description: 'reports the length of the video in frames' }), blockType: BlockType.REPORTER }, { opcode: 'isTapped', text: formatMessage({ id: 'steina.video.isTapped', default: 'tapped?', description: 'reports if the user is current touching the video or not' }), blockType: BlockType.BOOLEAN }, // Audio { opcode: 'startSound', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.audio.startSound', default: 'start sound', description: 'plays the entire sound without blocking' }) }, { opcode: 'playSound', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.audio.playSound', default: 'play sound until done', description: 'plays the entire sound while blocking execution' }) }, { opcode: 'startSoundFromAToB', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.audio.startSoundFromAToB', default: 'start sound from [MARKER_A] to [MARKER_B]', description: 'plays the sound between two markers without blocking' }), arguments: { MARKER_A: { type: ArgumentType.STRING, menu: 'markers' }, MARKER_B: { type: ArgumentType.STRING, menu: 'markers' } } }, { opcode: 'playSoundFromAToB', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.audio.playSoundFromAToB', default: 'play sound from [MARKER_A] to [MARKER_B] until done', description: 'plays the sound between two markers while blocking execution' }), arguments: { MARKER_A: { type: ArgumentType.STRING, menu: 'markers' }, MARKER_B: { type: ArgumentType.STRING, menu: 'markers' } } }, { opcode: 'setVolumeTo', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.setVolumeTo', default: 'set volume to [VALUE]', description: 'sets the volume to the given value, clamping between 0 and 500' }), arguments: { VALUE: { type: ArgumentType.NUMBER, defaultValue: 100 } } }, { opcode: 'changeVolumeBy', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.changeVolumeBy', default: 'change volume by [VALUE]', description: 'changes the volume by the given value, clamping between 0 and 500' }), arguments: { VALUE: { type: ArgumentType.NUMBER, defaultValue: 10 } } }, { opcode: 'getVolume', text: formatMessage({ id: 'steina.audio.getVolume', default: 'volume', description: 'reports the current volume of the audio clip' }), blockType: BlockType.REPORTER }, // Shared Audio and Video { opcode: 'setPlayRate', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.setPlayRate', default: 'set play rate to [RATE] %', description: 'sets the playback rate of the asset as a percentage' }), arguments: { RATE: { type: ArgumentType.NUMBER, defaultValue: 100 } } }, { opcode: 'changePlayRateBy', blockType: BlockType.COMMAND, text: formatMessage({ id: 'steina.video.changeRateBy', default: 'change play rate by [RATE]', description: 'changes the playback rate by the given value, clamping between 0 and 1000' }), arguments: { VALUE: { type: ArgumentType.NUMBER, defaultValue: 10 } } }, { opcode: 'getPlayRate', text: formatMessage({ id: 'steina.audio.getPlayRate', default: 'play rate', description: 'reports the current play rate of the audio clip' }), blockType: BlockType.REPORTER }, // Motion { opcode: 'whenTilted', text: formatMessage({ id: 'steina.motion.whenTilted', default: 'when tilted [DIRECTION]', description: 'when the device is tilted in a direction' }), blockType: BlockType.HAT, arguments: { DIRECTION: { type: ArgumentType.STRING, menu: 'tiltDirection', defaultValue: TiltDirections.RIGHT } } }, { opcode: 'isTilted', text: formatMessage({ id: 'steina.motion.isTilted', default: 'tilted [DIRECTION]?', description: 'is the device is tilted in a direction?' }), blockType: BlockType.BOOLEAN, arguments: { DIRECTION: { type: ArgumentType.STRING, menu: 'tiltDirection', defaultValue: TiltDirections.RIGHT } } }, { opcode: 'getTiltAngle', text: formatMessage({ id: 'steina.motion.tiltAngle', default: 'tilt angle [DIRECTION]', description: 'how much the device is tilted in a direction' }), blockType: BlockType.REPORTER, arguments: { DIRECTION: { type: ArgumentType.STRING, menu: 'tiltDirection', defaultValue: TiltDirections.RIGHT } } }, { opcode: 'whenPointed', text: formatMessage({ id: 'steina.motion.whenPointed', default: 'when pointed toward [DIRECTION]', description: 'when the device is rotated toward a cardinal direction' }), blockType: BlockType.HAT, arguments: { DIRECTION: { type: ArgumentType.STRING, menu: 'cardinalDirections', defaultValue: CardinalDirections.NORTH } } }, { opcode: 'isPointed', text: formatMessage({ id: 'steina.motion.isPointed', default: 'pointed [DIRECTION]?', description: 'is the device is pointed toward a cardinal direction?' }), blockType: BlockType.BOOLEAN, arguments: { DIRECTION: { type: ArgumentType.STRING, menu: 'cardinalDirections', defaultValue: CardinalDirections.NORTH } } }, { opcode: 'getCompassAngle', text: formatMessage({ id: 'steina.motion.compassAngle', default: 'compass angle', description: 'compass angle where 0.0 means north and 90.0 means east' }), blockType: BlockType.REPORTER }, ], menus: { directions: [ { text: formatMessage({ id: 'steina.video.videoDirectionMenu.forward', default: 'forward', description: 'label for playing a video in the forward direction' }), value: VideoDirections.FORWARD }, { text: formatMessage({ id: 'steina.video.videoDirectionMenu.reverse', default: 'in reverse', description: 'label for playing a video in the reverse direction' }), value: VideoDirections.REVERSE } ], effects: [ { text: formatMessage({ id: 'steina.video.effectsMenu.color', default: 'color', description: 'label for color element in effects picker for video extension' }), value: VideoEffects.COLOR }, { text: formatMessage({ id: 'steina.video.effectsMenu.whirl', default: 'whirl', description: 'label for whirl element in effects picker for video extension' }), value: VideoEffects.WHIRL }, { text: formatMessage({ id: 'steina.video.effectsMenu.brightness', default: 'brightness', description: 'label for brightness element in effects picker for video extension' }), value: VideoEffects.BRIGHTNESS }, { text: formatMessage({ id: 'steina.video.effectsMenu.ghost', default: 'ghost', description: 'label for ghost element in effects picker for video extension' }), value: VideoEffects.GHOST } // { // text: formatMessage({ // id: 'video.effectsMenu.crystallize', // default: 'crystallize', // description: 'label for crystallize element in effects picker for video extension' // }), // value: VideoEffects.CRYSTALLIZE // }, // { // text: formatMessage({ // id: 'video.effectsMenu.kaleidoscope', // default: 'kaleidoscope', // description: 'label for kaleidoscope element in effects picker for video extension' // }), // value: VideoEffects.KALEIDOSCOPE // } ], tiltDirections: [ { text: formatMessage({ id: 'steina.tiltDirectionMenu.right', default: 'right', description: 'label for right element in tilt direction picker' }), value: TiltDirections.RIGHT }, { text: formatMessage({ id: 'steina.tiltDirectionMenu.left', default: 'left', description: 'label for left element in tilt direction picker' }), value: TiltDirections.LEFT }, { text: formatMessage({ id: 'steina.tiltDirectionMenu.front', default: 'forward', description: 'label for forward element in tilt direction picker' }), value: TiltDirections.FORWARD }, { text: formatMessage({ id: 'steina.tiltDirectionMenu.back', default: 'backward', description: 'label for backward element in tilt direction picker' }), value: TiltDirections.BACKWARD } ], cardinalDirections: [ { text: formatMessage({ id: 'steina.cardinalDirectionMenu.north', default: 'north', description: 'label for north element in cardinal direction picker' }), value: CardinalDirections.NORTH }, { text: formatMessage({ id: 'steina.cardinalDirectionMenu.east', default: 'east', description: 'label for east element in cardinal direction picker' }), value: CardinalDirections.EAST }, { text: formatMessage({ id: 'steina.cardinalDirectionMenu.south', default: 'south', description: 'label for south element in cardinal direction picker' }), value: CardinalDirections.SOUTH }, { text: formatMessage({ id: 'steina.cardinalDirectionMenu.back', default: 'west', description: 'label for west element in cardinal direction picker' }), value: CardinalDirections.WEST } ], markers: '_buildMarkersMenu' } }; } _buildMarkersMenu(targetId) { if (!targetId) { return [ { text: 'n/a', value: '0' } ] } var target = this.runtime.getTargetById(targetId); if (target && target.hasOwnProperty('markers')) { var markers = target.markers; var menuItems = [ { text: formatMessage({ id: 'steina.markersMenu.start', default: 'start', description: 'label for the start of the video or audio clip' }), value: target.trimStart.toString() } ]; for (var i = 0; i < markers.length; ++i) { var marker = markers[i]; menuItems.push({ text: (i + 1).toString(), value: marker.toString() }) } menuItems.push({ text: formatMessage({ id: 'steina.markersMenu.end', default: 'end', description: 'label for the end of the video or audio clip' }), value: target.trimEnd.toString() }); return menuItems; } return [ { text: 'n/a', value: '0' } ] } // Video _queueVideo(runtime, thread, videoTarget, start, end, blocking) { var id = uid(); var playingVideo = { id: id, start: start, end: end, threadTopBlock: thread.topBlock, blocking: blocking }; // @NOTE(sean): This will overwrite any existing playing video for this target runtime.videoState.playing[videoTarget.id] = playingVideo; return id; } playEntireVideoUntilDone(args, util) { var target = util.target; var thread = util.thread; if (!util.stackFrame.playingId) { target.currentFrame = target.trimStart; var playingId = this._queueVideo(util.runtime, thread, target, target.trimStart, target.trimEnd, true); util.stackFrame.playingId = playingId; } else { var playingId = util.stackFrame.playingId; var playingVideo = util.runtime.videoState.playing[target.id]; if (!playingVideo || playingVideo.id != playingId) { // Either the video ended playing on the last frame // Or another playing video overwrote it since the last frame return; } } thread.status = Thread.STATUS_YIELD_TICK; } playVideoFromAToB(args, util) { var target = util.target; var thread = util.thread; var start = +(args.MARKER_A); var end = +(args.MARKER_B); if (!util.stackFrame.playingId) { target.currentFrame = start; var playingId = this._queueVideo(util.runtime, thread, target, start, end, true); util.stackFrame.playingId = playingId; } else { var playingId = util.stackFrame.playingId; var playingVideo = util.runtime.videoState.playing[target.id]; if (!playingVideo || playingVideo.id != playingId) { // Either the video ended playing on the last frame // Or another playing video overwrote it since the last frame return; } } thread.status = Thread.STATUS_YIELD_TICK; } playForwardReverseUntilDone(args, util) { var target = util.target; var thread = util.thread; if (!util.stackFrame.playingId) { var direction = args.DIRECTION; if (direction == VideoDirections.FORWARD) { var playingId = this._queueVideo(util.runtime, thread, target, target.currentFrame, target.trimEnd, true); util.stackFrame.playingId = playingId; } else { var playingId = this._queueVideo(util.runtime, thread, target, target.currentFrame, target.trimStart, true); util.stackFrame.playingId = playingId; } } else { var playingId = util.stackFrame.playingId; var playingVideo = util.runtime.videoState.playing[target.id]; if (!playingVideo || playingVideo.id != playingId) { // Either the video ended playing on the last frame // Or another playing video overwrote it since the last frame return; } } thread.status = Thread.STATUS_YIELD_TICK; } startPlayingForwardReverse(args, util) { var target = util.target; var thread = util.thread; var direction = args.DIRECTION; if (direction == VideoDirections.FORWARD) { this._queueVideo(util.runtime, thread, target, target.currentFrame, target.trimEnd, false); } else { this._queueVideo(util.runtime, thread, target, target.currentFrame, target.trimStart, false); } } setPlayRate(args, util) { util.target.setRate(+(args.RATE)); } changePlayRateBy(args, util) { var target = util.target; target.setRate(+(target.playbackRate) + +(args.RATE)); } startPlaying(args, util) { var target = util.target; var thread = util.thread; this._queueVideo(util.runtime, thread, target, target.currentFrame, target.trimEnd, false); } stopPlaying(args, util) { var target = util.target; if (target.id in util.runtime.videoState.playing) { delete util.runtime.videoState.playing[target.id]; } } goToFrame(args, util) { // Frames are 1-indexed in the blocks, but 0-indexed in the target var target = util.target; target.setCurrentFrame((+(args.FRAME) + target.trimStart) - 1); } playNFrames(args, util) { var target = util.target; var thread = util.thread; if (!util.stackFrame.playingId) { var framesToPlay = +(args.FRAMES); var endFrame = MathUtil.clamp(target.currentFrame + framesToPlay, target.trimStart, target.trimEnd); var playingId = this._queueVideo(util.runtime, thread, target, target.currentFrame, endFrame, true); util.stackFrame.playingId = playingId; } else { var playingId = util.stackFrame.playingId; var playingVideo = util.runtime.videoState.playing[target.id]; if (!playingVideo || playingVideo.id != playingId) { // Either the video ended playing on the last frame // Or another playing video overwrote it since the last frame return; } } thread.status = Thread.STATUS_YIELD_TICK; } playForwardUntilDone(args, util) { var target = util.target; var thread = util.thread; if (!util.stackFrame.playingId) { var playingId = this._queueVideo(util.runtime, thread, target, target.currentFrame, target.trimEnd, true); util.stackFrame.playingId = playingId; } else { var playingId = util.stackFrame.playingId; var playingVideo = util.runtime.videoState.playing[target.id]; if (!playingVideo || playingVideo.id != playingId) { // Either the video ended playing on the last frame // Or another playing video overwrote it since the last frame return; } } thread.status = Thread.STATUS_YIELD_TICK; } playBackwardUntilDone(args, util) { var target = util.target; var thread = util.thread; if (!util.stackFrame.playingId) { var playingId = this._queueVideo(util.runtime, thread, target, target.currentFrame, target.trimStart, true); util.stackFrame.playingId = playingId; } else { var playingId = util.stackFrame.playingId; var playingVideo = util.runtime.videoState.playing[target.id]; if (!playingVideo || playingVideo.id != playingId) { // Either the video ended playing on the last frame // Or another playing video overwrote it since the last frame return; } } thread.status = Thread.STATUS_YIELD_TICK; } nextFrame(args, util) { var target = util.target; target.setCurrentFrame(target.currentFrame + 1); } previousFrame(args, util) { var target = util.target; target.setCurrentFrame(target.currentFrame - 1); } isTapped(args, util) { var target = util.target; return target.tapped; } changeEffectBy(args, util) { const effect = Cast.toString(args.EFFECT).toLowerCase(); const change = Cast.toNumber(args.CHANGE); if (!util.target.effects.hasOwnProperty(effect)) return; const newValue = change + util.target.effects[effect]; util.target.setEffect(effect, newValue); } setEffectTo(args, util) { const effect = Cast.toString(args.EFFECT).toLowerCase(); const value = Cast.toNumber(args.VALUE); util.target.setEffect(effect, value); } clearVideoEffects(args, util) { util.target.clearEffects(); } whenPlayedToEnd(args, util) { var target = util.target; if (target.currentFrame == target.trimEnd) { return true; } return false; } whenPlayedToBeginning(args, util) { var target = util.target; if (target.currentFrame == target.trimStart) { return true; } return false; } whenReached(args, util) { var target = util.target; var marker = args.MARKER; return marker == target.currentFrame; } whenTapped(args, util) { var target = util.target; return target.tapped; } getCurrentFrame(args, util) { // @TODO: Should this return an integer or a float? We're going with integer for now var target = util.target; return +(target.currentFrame - target.trimStart) + 1; // 1-indexed } getTotalFrames(args, util) { var target = util.target return target.trimEnd - target.trimStart; } getPlayRate(args, util) { return util.target.playbackRate; } // Audio startSound(args, util) { var target = util.target; // Only start a sound if we're below the limit of simultaneous // unblocking sounds if (target.nonblockingSoundsAvailable > 0) { // Just queue the sound and don't yield the thread this._queueSound(util.runtime, target, target.trimStart, target.trimEnd, target.playbackRate, false); target.nonblockingSoundsAvailable--; } } playSound(args, util) { var target = util.target; var thread = util.thread; if (!util.stackFrame.playingId) { // Add the new sound to the play queue var id = this._queueSound(util.runtime, target, target.trimStart, target.trimEnd, target.playbackRate); util.stackFrame.playingId = id; } else { var playingId = util.stackFrame.playingId; if (!util.runtime.audioState.playing[playingId]) { // The sound finished on the last frame // and was removed by the runtime, so we're done return; } } thread.status = Thread.STATUS_YIELD_TICK; } startSoundFromAToB(args, util) { var target = util.target; var start = +(args.MARKER_A); var end = +(args.MARKER_B); if (target.nonblockingSoundsAvailable > 0) { // Just queue the sound and don't yield the thread this._queueSound(util.runtime, target, start, end, target.playbackRate, false); target.nonblockingSoundsAvailable--; } } playSoundFromAToB(args, util) { var target = util.target; var thread = util.thread; var start = +(args.MARKER_A); var end = +(args.MARKER_B); if (!util.stackFrame.playingId) { // Add the new sound to the play queue var id = this._queueSound(util.runtime, target, start, end, target.playbackRate); util.stackFrame.playingId = id; } else { var playingId = util.stackFrame.playingId; if (!util.runtime.audioState.playing[playingId]) { // The sound finished on the last frame // and was removed by the runtime, so we're done return; } } thread.status = Thread.STATUS_YIELD_TICK; } setVolumeTo(args, util) { util.target.setVolume(args.VALUE) } changeVolumeBy(args, util) { var target = util.target; target.setVolume(+(target.volume) + +(args.VALUE)); } getVolume(args, util) { return util.target.volume; } _queueSound(runtime, audioTarget, start, end, playbackRate, blocking = true) { var id = uid(); var firstSample = Math.max(start, 0); var lastSample = Math.min(end, audioTarget.totalSamples - 1); var playingSound = { audioTargetId : audioTarget.id, sampleRate: audioTarget.sampleRate, start: firstSample, end: lastSample, playbackRate: playbackRate, prevPlayhead: firstSample, playhead: firstSample, blocking: blocking }; runtime.audioState.playing[id] = playingSound; return id; } // Motion getTiltAngle(args, util) { return this._getTiltAngle(args.DIRECTION); } whenTilted(args, util) { return this._isTilted(args.DIRECTION); } isTilted(args, util) { return this._isTilted(args.DIRECTION); } _getTiltAngle(direction) { if (direction == TiltDirections.FORWARD) { return this.runtime.motion.pitch; } else if (direction == TiltDirections.BACKWARD) { return -this.runtime.motion.pitch; } else if (direction == TiltDirections.LEFT) { return -this.runtime.motion.roll; } else if (direction == TiltDirections.RIGHT) { return this.runtime.motion.roll; } } _isTilted(direction) { return this._getTiltAngle(direction) >= TILT_THRESHOLD; } getCompassAngle(args, util) { return util.runtime.motion.heading; } whenPointed(args, util) { return this._isPointed(args.DIRECTION); } isPointed(args, util) { return this._isPointed(args.DIRECTION); } _isPointed(direction) { var compass = this.runtime.motion.heading; if (direction == CardinalDirections.NORTH) { return compass <= (COMPASS_THRESHOLD / 2.0) || compass >= 360.0 - (COMPASS_THRESHOLD / 2.0); } else if (direction == CardinalDirections.SOUTH) { return Math.abs(compass - 180.0) <= COMPASS_THRESHOLD; } else if (direction == CardinalDirections.EAST) { return Math.abs(compass - 90.0) <= COMPASS_THRESHOLD; } else if (direction == CardinalDirections.WEST) { return Math.abs(compass - 270.0) <= COMPASS_THRESHOLD; } } }
JavaScript
class Deferred { constructor() { this.reject = () => { }; this.resolve = () => { }; this.promise = new Promise((resolve, reject) => { this.resolve = resolve; this.reject = reject; }); } /** * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback * and returns a node-style callback which will resolve or reject the Deferred's promise. */ wrapCallback(callback) { return (error, value) => { if (error) { this.reject(error); } else { this.resolve(value); } if (typeof callback === 'function') { // Attaching noop handler just in case developer wasn't expecting // promises this.promise.catch(() => { }); // Some of our callbacks don't expect a value and our own tests // assert that the parameter length is 1 if (callback.length === 1) { callback(error); } else { callback(error, value); } } }; } }
JavaScript
class Sha1 { constructor() { /** * Holds the previous values of accumulated variables a-e in the compress_ * function. * @private */ this.chain_ = []; /** * A buffer holding the partially computed hash result. * @private */ this.buf_ = []; /** * An array of 80 bytes, each a part of the message to be hashed. Referred to * as the message schedule in the docs. * @private */ this.W_ = []; /** * Contains data needed to pad messages less than 64 bytes. * @private */ this.pad_ = []; /** * @private {number} */ this.inbuf_ = 0; /** * @private {number} */ this.total_ = 0; this.blockSize = 512 / 8; this.pad_[0] = 128; for (let i = 1; i < this.blockSize; ++i) { this.pad_[i] = 0; } this.reset(); } reset() { this.chain_[0] = 0x67452301; this.chain_[1] = 0xefcdab89; this.chain_[2] = 0x98badcfe; this.chain_[3] = 0x10325476; this.chain_[4] = 0xc3d2e1f0; this.inbuf_ = 0; this.total_ = 0; } /** * Internal compress helper function. * @param buf Block to compress. * @param offset Offset of the block in the buffer. * @private */ compress_(buf, offset) { if (!offset) { offset = 0; } const W = this.W_; // get 16 big endian words if (typeof buf === 'string') { for (let i = 0; i < 16; i++) { // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS // have a bug that turns the post-increment ++ operator into pre-increment // during JIT compilation. We have code that depends heavily on SHA-1 for // correctness and which is affected by this bug, so I've removed all uses // of post-increment ++ in which the result value is used. We can revert // this change once the Safari bug // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and // most clients have been updated. W[i] = (buf.charCodeAt(offset) << 24) | (buf.charCodeAt(offset + 1) << 16) | (buf.charCodeAt(offset + 2) << 8) | buf.charCodeAt(offset + 3); offset += 4; } } else { for (let i = 0; i < 16; i++) { W[i] = (buf[offset] << 24) | (buf[offset + 1] << 16) | (buf[offset + 2] << 8) | buf[offset + 3]; offset += 4; } } // expand to 80 words for (let i = 16; i < 80; i++) { const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff; } let a = this.chain_[0]; let b = this.chain_[1]; let c = this.chain_[2]; let d = this.chain_[3]; let e = this.chain_[4]; let f, k; // TODO(user): Try to unroll this loop to speed up the computation. for (let i = 0; i < 80; i++) { if (i < 40) { if (i < 20) { f = d ^ (b & (c ^ d)); k = 0x5a827999; } else { f = b ^ c ^ d; k = 0x6ed9eba1; } } else { if (i < 60) { f = (b & c) | (d & (b | c)); k = 0x8f1bbcdc; } else { f = b ^ c ^ d; k = 0xca62c1d6; } } const t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff; e = d; d = c; c = ((b << 30) | (b >>> 2)) & 0xffffffff; b = a; a = t; } this.chain_[0] = (this.chain_[0] + a) & 0xffffffff; this.chain_[1] = (this.chain_[1] + b) & 0xffffffff; this.chain_[2] = (this.chain_[2] + c) & 0xffffffff; this.chain_[3] = (this.chain_[3] + d) & 0xffffffff; this.chain_[4] = (this.chain_[4] + e) & 0xffffffff; } update(bytes, length) { // TODO(johnlenz): tighten the function signature and remove this check if (bytes == null) { return; } if (length === undefined) { length = bytes.length; } const lengthMinusBlock = length - this.blockSize; let n = 0; // Using local instead of member variables gives ~5% speedup on Firefox 16. const buf = this.buf_; let inbuf = this.inbuf_; // The outer while loop should execute at most twice. while (n < length) { // When we have no data in the block to top up, we can directly process the // input buffer (assuming it contains sufficient data). This gives ~25% // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that // the data is provided in large chunks (or in multiples of 64 bytes). if (inbuf === 0) { while (n <= lengthMinusBlock) { this.compress_(bytes, n); n += this.blockSize; } } if (typeof bytes === 'string') { while (n < length) { buf[inbuf] = bytes.charCodeAt(n); ++inbuf; ++n; if (inbuf === this.blockSize) { this.compress_(buf); inbuf = 0; // Jump to the outer loop so we use the full-block optimization. break; } } } else { while (n < length) { buf[inbuf] = bytes[n]; ++inbuf; ++n; if (inbuf === this.blockSize) { this.compress_(buf); inbuf = 0; // Jump to the outer loop so we use the full-block optimization. break; } } } } this.inbuf_ = inbuf; this.total_ += length; } /** @override */ digest() { const digest = []; let totalBits = this.total_ * 8; // Add pad 0x80 0x00*. if (this.inbuf_ < 56) { this.update(this.pad_, 56 - this.inbuf_); } else { this.update(this.pad_, this.blockSize - (this.inbuf_ - 56)); } // Add # bits. for (let i = this.blockSize - 1; i >= 56; i--) { this.buf_[i] = totalBits & 255; totalBits /= 256; // Don't use bit-shifting here! } this.compress_(this.buf_); let n = 0; for (let i = 0; i < 5; i++) { for (let j = 24; j >= 0; j -= 8) { digest[n] = (this.chain_[i] >> j) & 255; ++n; } } return digest; } }
JavaScript
class ObserverProxy { /** * @param executor Function which can make calls to a single Observer * as a proxy. * @param onNoObservers Callback when count of Observers goes to zero. */ constructor(executor, onNoObservers) { this.observers = []; this.unsubscribes = []; this.observerCount = 0; // Micro-task scheduling by calling task.then(). this.task = Promise.resolve(); this.finalized = false; this.onNoObservers = onNoObservers; // Call the executor asynchronously so subscribers that are called // synchronously after the creation of the subscribe function // can still receive the very first value generated in the executor. this.task .then(() => { executor(this); }) .catch(e => { this.error(e); }); } next(value) { this.forEachObserver((observer) => { observer.next(value); }); } error(error) { this.forEachObserver((observer) => { observer.error(error); }); this.close(error); } complete() { this.forEachObserver((observer) => { observer.complete(); }); this.close(); } /** * Subscribe function that can be used to add an Observer to the fan-out list. * * - We require that no event is sent to a subscriber sychronously to their * call to subscribe(). */ subscribe(nextOrObserver, error, complete) { let observer; if (nextOrObserver === undefined && error === undefined && complete === undefined) { throw new Error('Missing Observer.'); } // Assemble an Observer object when passed as callback functions. if (implementsAnyMethods(nextOrObserver, [ 'next', 'error', 'complete' ])) { observer = nextOrObserver; } else { observer = { next: nextOrObserver, error, complete }; } if (observer.next === undefined) { observer.next = noop; } if (observer.error === undefined) { observer.error = noop; } if (observer.complete === undefined) { observer.complete = noop; } const unsub = this.unsubscribeOne.bind(this, this.observers.length); // Attempt to subscribe to a terminated Observable - we // just respond to the Observer with the final error or complete // event. if (this.finalized) { // eslint-disable-next-line @typescript-eslint/no-floating-promises this.task.then(() => { try { if (this.finalError) { observer.error(this.finalError); } else { observer.complete(); } } catch (e) { // nothing } return; }); } this.observers.push(observer); return unsub; } // Unsubscribe is synchronous - we guarantee that no events are sent to // any unsubscribed Observer. unsubscribeOne(i) { if (this.observers === undefined || this.observers[i] === undefined) { return; } delete this.observers[i]; this.observerCount -= 1; if (this.observerCount === 0 && this.onNoObservers !== undefined) { this.onNoObservers(this); } } forEachObserver(fn) { if (this.finalized) { // Already closed by previous event....just eat the additional values. return; } // Since sendOne calls asynchronously - there is no chance that // this.observers will become undefined. for (let i = 0; i < this.observers.length; i++) { this.sendOne(i, fn); } } // Call the Observer via one of it's callback function. We are careful to // confirm that the observe has not been unsubscribed since this asynchronous // function had been queued. sendOne(i, fn) { // Execute the callback asynchronously // eslint-disable-next-line @typescript-eslint/no-floating-promises this.task.then(() => { if (this.observers !== undefined && this.observers[i] !== undefined) { try { fn(this.observers[i]); } catch (e) { // Ignore exceptions raised in Observers or missing methods of an // Observer. // Log error to console. b/31404806 if (typeof console !== 'undefined' && console.error) { console.error(e); } } } }); } close(err) { if (this.finalized) { return; } this.finalized = true; if (err !== undefined) { this.finalError = err; } // Proxy is no longer needed - garbage collect references // eslint-disable-next-line @typescript-eslint/no-floating-promises this.task.then(() => { this.observers = undefined; this.onNoObservers = undefined; }); } }
JavaScript
class PlatformLoggerServiceImpl { constructor(container) { this.container = container; } // In initial implementation, this will be called by installations on // auth token refresh, and installations will send this string. getPlatformInfoString() { const providers = this.container.getProviders(); // Loop through providers and get library/version pairs from any that are // version components. return providers .map(provider => { if (isVersionServiceProvider(provider)) { const service = provider.getImmediate(); return `${service.library}/${service.version}`; } else { return null; } }) .filter(logString => logString) .join(' '); } }
JavaScript
class FirebaseAppImpl { constructor(options, config, container) { this._isDeleted = false; this._options = Object.assign({}, options); this._config = Object.assign({}, config); this._name = config.name; this._automaticDataCollectionEnabled = config.automaticDataCollectionEnabled; this._container = container; this.container.addComponent(new _firebase_component__WEBPACK_IMPORTED_MODULE_0__.Component('app', () => this, "PUBLIC" /* PUBLIC */)); } get automaticDataCollectionEnabled() { this.checkDestroyed(); return this._automaticDataCollectionEnabled; } set automaticDataCollectionEnabled(val) { this.checkDestroyed(); this._automaticDataCollectionEnabled = val; } get name() { this.checkDestroyed(); return this._name; } get options() { this.checkDestroyed(); return this._options; } get config() { this.checkDestroyed(); return this._config; } get container() { return this._container; } get isDeleted() { return this._isDeleted; } set isDeleted(val) { this._isDeleted = val; } /** * This function will throw an Error if the App has already been deleted - * use before performing API actions on the App. */ checkDestroyed() { if (this.isDeleted) { throw ERROR_FACTORY.create("app-deleted" /* APP_DELETED */, { appName: this._name }); } } }
JavaScript
class Component { /** * * @param name The public service name, e.g. app, auth, firestore, database * @param instanceFactory Service factory responsible for creating the public interface * @param type whether the service provided by the component is public or private */ constructor(name, instanceFactory, type) { this.name = name; this.instanceFactory = instanceFactory; this.type = type; this.multipleInstances = false; /** * Properties to be added to the service namespace */ this.serviceProps = {}; this.instantiationMode = "LAZY" /* LAZY */; this.onInstanceCreated = null; } setInstantiationMode(mode) { this.instantiationMode = mode; return this; } setMultipleInstances(multipleInstances) { this.multipleInstances = multipleInstances; return this; } setServiceProps(props) { this.serviceProps = props; return this; } setInstanceCreatedCallback(callback) { this.onInstanceCreated = callback; return this; } }
JavaScript
class Provider { constructor(name, container) { this.name = name; this.container = container; this.component = null; this.instances = new Map(); this.instancesDeferred = new Map(); this.instancesOptions = new Map(); this.onInitCallbacks = new Map(); } /** * @param identifier A provider can provide mulitple instances of a service * if this.component.multipleInstances is true. */ get(identifier) { // if multipleInstances is not supported, use the default name const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); if (!this.instancesDeferred.has(normalizedIdentifier)) { const deferred = new _firebase_util__WEBPACK_IMPORTED_MODULE_0__.Deferred(); this.instancesDeferred.set(normalizedIdentifier, deferred); if (this.isInitialized(normalizedIdentifier) || this.shouldAutoInitialize()) { // initialize the service if it can be auto-initialized try { const instance = this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier }); if (instance) { deferred.resolve(instance); } } catch (e) { // when the instance factory throws an exception during get(), it should not cause // a fatal error. We just return the unresolved promise in this case. } } } return this.instancesDeferred.get(normalizedIdentifier).promise; } getImmediate(options) { var _a; // if multipleInstances is not supported, use the default name const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier); const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false; if (this.isInitialized(normalizedIdentifier) || this.shouldAutoInitialize()) { try { return this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier }); } catch (e) { if (optional) { return null; } else { throw e; } } } else { // In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw if (optional) { return null; } else { throw Error(`Service ${this.name} is not available`); } } } getComponent() { return this.component; } setComponent(component) { if (component.name !== this.name) { throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`); } if (this.component) { throw Error(`Component for ${this.name} has already been provided`); } this.component = component; // return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`) if (!this.shouldAutoInitialize()) { return; } // if the service is eager, initialize the default instance if (isComponentEager(component)) { try { this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME }); } catch (e) { // when the instance factory for an eager Component throws an exception during the eager // initialization, it should not cause a fatal error. // TODO: Investigate if we need to make it configurable, because some component may want to cause // a fatal error in this case? } } // Create service instances for the pending promises and resolve them // NOTE: if this.multipleInstances is false, only the default instance will be created // and all promises with resolve with it regardless of the identifier. for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) { const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); try { // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy. const instance = this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier }); instanceDeferred.resolve(instance); } catch (e) { // when the instance factory throws an exception, it should not cause // a fatal error. We just leave the promise unresolved. } } } clearInstance(identifier = DEFAULT_ENTRY_NAME) { this.instancesDeferred.delete(identifier); this.instancesOptions.delete(identifier); this.instances.delete(identifier); } // app.delete() will call this method on every provider to delete the services // TODO: should we mark the provider as deleted? async delete() { const services = Array.from(this.instances.values()); await Promise.all([ ...services .filter(service => 'INTERNAL' in service) // legacy services // eslint-disable-next-line @typescript-eslint/no-explicit-any .map(service => service.INTERNAL.delete()), ...services .filter(service => '_delete' in service) // modularized services // eslint-disable-next-line @typescript-eslint/no-explicit-any .map(service => service._delete()) ]); } isComponentSet() { return this.component != null; } isInitialized(identifier = DEFAULT_ENTRY_NAME) { return this.instances.has(identifier); } getOptions(identifier = DEFAULT_ENTRY_NAME) { return this.instancesOptions.get(identifier) || {}; } initialize(opts = {}) { const { options = {} } = opts; const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier); if (this.isInitialized(normalizedIdentifier)) { throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`); } if (!this.isComponentSet()) { throw Error(`Component ${this.name} has not been registered yet`); } const instance = this.getOrInitializeService({ instanceIdentifier: normalizedIdentifier, options }); // resolve any pending promise waiting for the service instance for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) { const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier); if (normalizedIdentifier === normalizedDeferredIdentifier) { instanceDeferred.resolve(instance); } } return instance; } /** * * @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize(). * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program. * * @param identifier An optional instance identifier * @returns a function to unregister the callback */ onInit(callback, identifier) { var _a; const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier); const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set(); existingCallbacks.add(callback); this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks); const existingInstance = this.instances.get(normalizedIdentifier); if (existingInstance) { callback(existingInstance, normalizedIdentifier); } return () => { existingCallbacks.delete(callback); }; } /** * Invoke onInit callbacks synchronously * @param instance the service instance` */ invokeOnInitCallbacks(instance, identifier) { const callbacks = this.onInitCallbacks.get(identifier); if (!callbacks) { return; } for (const callback of callbacks) { try { callback(instance, identifier); } catch (_a) { // ignore errors in the onInit callback } } } getOrInitializeService({ instanceIdentifier, options = {} }) { let instance = this.instances.get(instanceIdentifier); if (!instance && this.component) { instance = this.component.instanceFactory(this.container, { instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier), options }); this.instances.set(instanceIdentifier, instance); this.instancesOptions.set(instanceIdentifier, options); /** * Invoke onInit listeners. * Note this.component.onInstanceCreated is different, which is used by the component creator, * while onInit listeners are registered by consumers of the provider. */ this.invokeOnInitCallbacks(instance, instanceIdentifier); /** * Order is important * onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which * makes `isInitialized()` return true. */ if (this.component.onInstanceCreated) { try { this.component.onInstanceCreated(this.container, instanceIdentifier, instance); } catch (_a) { // ignore errors in the onInstanceCreatedCallback } } } return instance || null; } normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) { if (this.component) { return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME; } else { return identifier; // assume multiple instances are supported before the component is provided. } } shouldAutoInitialize() { return (!!this.component && this.component.instantiationMode !== "EXPLICIT" /* EXPLICIT */); } }
JavaScript
class ComponentContainer { constructor(name) { this.name = name; this.providers = new Map(); } /** * * @param component Component being added * @param overwrite When a component with the same name has already been registered, * if overwrite is true: overwrite the existing component with the new component and create a new * provider with the new component. It can be useful in tests where you want to use different mocks * for different tests. * if overwrite is false: throw an exception */ addComponent(component) { const provider = this.getProvider(component.name); if (provider.isComponentSet()) { throw new Error(`Component ${component.name} has already been registered with ${this.name}`); } provider.setComponent(component); } addOrOverwriteComponent(component) { const provider = this.getProvider(component.name); if (provider.isComponentSet()) { // delete the existing provider from the container, so we can register the new component this.providers.delete(component.name); } this.addComponent(component); } /** * getProvider provides a type safe interface where it can only be called with a field name * present in NameServiceMapping interface. * * Firebase SDKs providing services should extend NameServiceMapping interface to register * themselves. */ getProvider(name) { if (this.providers.has(name)) { return this.providers.get(name); } // create a Provider for a service that hasn't registered with Firebase const provider = new Provider(name, this); this.providers.set(name, provider); return provider; } getProviders() { return Array.from(this.providers.values()); } }
JavaScript
class MessagingService { constructor(app, installations, analyticsProvider) { // logging is only done with end user consent. Default to false. this.deliveryMetricsExportedToBigQueryEnabled = false; this.onBackgroundMessageHandler = null; this.onMessageHandler = null; this.logEvents = []; this.isLogServiceStarted = false; const appConfig = extractAppConfig(app); this.firebaseDependencies = { app, appConfig, installations, analyticsProvider }; } _delete() { return Promise.resolve(); } }
JavaScript
class SignUp { /** * Class constructor, called when instantiating new class object */ constructor() { // declare our class properties // call init this.init(); } /** * We run init when our class is first instantiated */ init() { // bind events this.bindEvents(); } /** * bind all necessary events */ bindEvents() { let self = this; // handle form validation success action $('#sign_up_form input[name="subdomain"]').on('blur', function(e) { self.handleFieldBlur(); }); } /* handle the ajax form validation success */ handleFieldBlur(obj) { let self = this; let $field = $('#sign_up_form input[name="subdomain"]'); let $feedback = $field.closest('.form-group').find('.fv-control-feedback'); $('.subdomain-validation-error').hide(); if ( $field.val() !== '' && !$field.closest('.form-group').hasClass('has-warning') ) { // convert field value to proper format $field.val($field.val().replace(/\s+/, '').toLowerCase()); $feedback.removeClass('fa-check text-success fa-times text-danger').addClass('fa-circle-o-notch fa-spin text-info'); // do the ajax call here $.ajax({ url: Core.url('validate-subdomain'), method: 'POST', data: { subdomain: $field.val() } }).done(function(data, textStatus, jqXHR) { self.handleValidateSubdomainSuccess(data, $feedback); }).fail(function(jqXHR, textStatus, errorThrown) { self.handleValidateSubdomainError(jqXHR, $feedback); }); } } /* handle the ajax call success */ handleValidateSubdomainSuccess(data, $feedback) { $('#sign_up_form').removeClass('invalid'); $('input[name="subdomain-validation"]').val('human'); $feedback.removeClass('fa-circle-o-notch fa-spin text-info').addClass('fa-check text-success'); } /* handle the ajax call error */ handleValidateSubdomainError(jqXHR, $feedback) { $('#sign_up_form').addClass('invalid'); $feedback.removeClass('fa-circle-o-notch fa-spin text-info').addClass('fa-times text-danger'); $('.subdomain-validation-error').html(jqXHR.responseJSON.message).show(); } }
JavaScript
class LanguageSwitcherButton extends Control { /** * @param {LanguageSwitcherButtonOptions} options */ constructor (options = {}) { options.element = $('<button>').get(0) options.singleButton = true options.className = options.className || 'g4u-languageswitcher' super(options) /** * @type {jQuery} * @private */ this.$button_ = this.get$Element().addClass(this.className_ + '-button') const languages = this.getLocaliser().getAvailableLanguages() if (languages.length < 2) { Debug.info('You do not have any languages to switch between.') Debug.info('Could it be that you forgot to disable languageSwitcherButton?') } else if (languages.length > 2) { Debug.info('You have more than 2 languages to switch between.') Debug.info('In this case you need to use languageSwitcherMenu.') } this.$button_.on('click', () => { const targetLanguage = languages[1 - languages.indexOf(this.getLocaliser().getCurrentLang())] this.getLocaliser().setCurrentLang(targetLanguage) }) } /** * @param {G4UMap} map */ setMap (map) { if (map) { this.$button_.html(this.getLocaliser().getCurrentLang()) addTooltip(this.$button_, this.getLocaliser().localiseUsingDictionary('LanguageSwitcherButton tipLabel')) } super.setMap(map) } }
JavaScript
class memoryInterface { /** * Constructor that set the internal data with the initialData if any. * @param {Object} [initialData={}] - The initial state to store when * creating this interface. */ constructor(initialData = {}) { this.data = initialData; } /** * Sets a value under the given path in the state. If the path does not * exist, it will be created as a path of objects. * @param {string} path - The path where the value is located, must * be a string using the usual dot notation for javascript. * @param {*} value - The value to set a the end of the path. * @see [setRecursively]{@link module:memoryInterface~setRecursively} */ set(path, value) { this.data = setRecursively(this.data, path.split('.'), value); } /** * Removes a value under the given path in the state. It removes the value * by setting it as undefined. * @param {string} path - The path where the value is located, must * be a string using the usual dot notation for javascript. * @see [setRecursively]{@link module:memoryInterface~setRecursively} */ remove(path) { this.data = setRecursively(this.data, path.split('.'), undefined); } /** * Finds a value under the given path in the state. I will follow the path * as long as it exists and will return immeditatly if the path does not * exists. * @param {string} path - The path where the value is located, must * be a string using the usual dot notation for javascript. * @returns {*} Returns the found value or undefined if it could not be * found. */ find(path) { let value = this.data; //Split the path into its parts if it is a valid path const parts = path.split('.'); //Go through all parts for (let part in parts) { part = parts[part]; //If the part can be found if (value[part]) { //Continue deeper value = value[part]; } else { //Else, cancel the search return undefined; } } //Return the latest found value return value; } /** * Clears the memory state by replacing the old state with an empty object. */ clear() { this.data = {}; } /** * Returns all the content currently stored inside the state. * @returns {Object} Returns the object store in memory. */ all() { return this.data; } }
JavaScript
class GitDeployerEditor extends HashBrown.Views.Editors.Editor { static get alias() { return 'git'; } /** * Renders this editor */ template() { return _.div({class: 'editor__field-group'}, this.field( 'Repository (https://)', new HashBrown.Views.Widgets.Input({ type: 'text', value: this.model.repo, placeholder: 'example.com/user/repo.git', onChange: (newRepo) => { this.model.repo = newRepo; } }) ), this.field( 'Branch', new HashBrown.Views.Widgets.Input({ type: 'text', value: this.model.branch, placeholder: 'master', onChange: (newBranch) => { this.model.branch = newBranch; } }) ), this.field( 'Username', new HashBrown.Views.Widgets.Input({ type: 'text', value: this.model.username, onChange: (newUsername) => { this.model.username = newUsername; } }) ), this.field( 'Password', new HashBrown.Views.Widgets.Input({ type: 'password', value: this.model.password, onChange: (newPassword) => { this.model.password = newPassword; } }) ) ); } }
JavaScript
class KeycloakVerifyProvider { constructor() { } value() { return async (accessToken, refreshToken, profile, cb) => { throw new rest_1.HttpErrors.NotImplemented(`VerifyFunction.KeycloakAuthFn is not implemented`); }; } }
JavaScript
class LoggerBuilder { /** * Create a new logger builder instance. * * @public */ constructor() { /** * A list of log handlers. * * @private * @type {Array.<LogHandlerInterface>} */ this.handlers = []; } /** * Add a log handler to the set of log delegates. * * @public * @param {LogHandlerInterface} handler Log handler to add. * @return {this} The same instance for method chaining. */ addHandler(handler) { this.handlers.push(handler); return this; } /** * Build a logger instance with all registered log handlers. * * @public * @return {Logger} Logger instance with all registered log handlers. */ build() { return new Logger(this.handlers); } }
JavaScript
class App extends React.Component { constructor(props) { super(props); const pipelineData = loadData(props.data, this.resetStoreData.bind(this)); const initialState = getInitialState(pipelineData, props); this.store = store(initialState); } componentDidUpdate(prevProps) { if (this.dataWasUpdated(prevProps.data, this.props.data)) { this.store.dispatch(resetSnapshotData(formatSnapshots(this.props.data))); } } /** * Quickly determine whether snapshots have been updated * @param {Object} prevData Previous data prop * @param {Object} newData New data prop */ dataWasUpdated(prevData, newData) { // Check just the schema IDs of incoming data updates const dataID = ({ snapshots }) => Array.isArray(snapshots) && snapshots.map(d => d.schema_id).join(''); return dataID(prevData) !== dataID(newData); } /** * Dispatch an action to update the store with all new snapshot data * @param {Object} formattedData The formatted snapshots */ resetStoreData(formattedData) { this.store.dispatch(resetSnapshotData(formattedData)); } render() { return this.props.data ? ( <Provider store={this.store}> <Wrapper /> </Provider> ) : null; } }
JavaScript
class Router { constructor(favorites) { this.myFavorites = favorites; // Add event handlers for a.pop-links once this.addEventHandler(); // Call changePage on initial page load this.changePage(); // Call changePage on pop events // (the user clicks the forward or backward button) // from an arrow function to keep "this" // inside changePage pointing to the PopStateHandler object window.addEventListener('popstate', () => this.changePage()); } addEventHandler() { let that = this; $(document).on('click', 'a.pop', function (e) { // Create a push state event let href = $(this).attr('href'); history.pushState(null, null, href); // Call the changePage function that.changePage(); // Stop the browser from starting a page reload e.preventDefault(); }); } urlMaker() { $.getJSON("/json/recipes.json", (recipes) => { this.recipes = recipes; }).then(() => { for (let recipe of this.recipes) { this.urls[`/recept/${recipe.url}`] = 'recipePage'; } }); } changePage() { // React on page changed // (replace part of the DOM etc.) // Get the current url let url = location.pathname; // Change which menu link that is active $('header ul li a').removeClass('active'); $(`header ul li a[href="${url}"]`).addClass('active'); // A small "dictionary" of what method to call on which url this.urls = { '/': 'startpage', '/footer': 'footer', '/add-recipe': 'addrecipe', '/searchresult': 'searchResult' }; function translateCharacters(str) { return str.replace(/%C3%A5/g, "å").replace(/%C3%A4/g, "ä").replace(/%C3%B6/g, "ö").replace(/%C3%A9/g, "é"); } /** * Checks if url is searchresult. * If it is it checks for search-word/s and filters * Then sends it to searchresult with in-parameters to the class. * * @author Andreas */ if (url.includes('searchresult')) { url = translateCharacters(url); let newUrl = url.substring(0, 13); let indexOfFilters = url.indexOf('/filters'); let searchStr = url.substring(14); let filters = []; if (indexOfFilters > -1) { searchStr = url.substring(14, indexOfFilters); filters = url.substring(indexOfFilters + 8).replace(/-/g, ' ').split(' ').map(x => x.replace(/%20/g, ' ')); } let methodName = this.urls[newUrl]; // Call the right method this[methodName](searchStr, filters); } else { this.urlMaker(); setTimeout(() => { let methodName = this.urls[location.pathname]; this[methodName](); }, 100); } window.scrollTo(0, 0); } //Methods for rendering in our templates in the SPA startpage() { this.startPage = new Startpage(); } addrecipe() { this.addRecipe = new AddRecipe(this); $('main').empty(); this.addRecipe.render('main'); this.addRecipe.renderNewForm(); this.addRecipe.renderNewForm(); this.addRecipe.renderNewForm(); this.addRecipe.checkSizeWindowAndAppend(); } recipePage() { this.recipepage = new Recipepage(this.myFavorites); } searchResult(searchStr, filters) { this.searchresult = new Searchresult(searchStr, filters, this.myFavorites); } }
JavaScript
class App extends React.Component { render() { return ( <Provider store={createStore(reducers, {}, applyMiddleware(thunk))} > {/* <LoginForm /> */} <Router> <Stack key="root"> <Scene key="login" component={LoginForm} title="Login"></Scene> <Scene key="home" component={Home} title="Stories"></Scene> <Scene key="profile" component={Profile} title="Profile"></Scene> </Stack> </Router> </Provider> ); } }
JavaScript
class ColorPicker extends React.Component{ constructor(props){ super(props) this.state = { currentColor: 'black', colors: ['black', 'pink', 'red'], inSelection: false, } this.handleClickSelectColor = this.handleClickSelectColor.bind() } componentDidMount(){ this.setState({ currentColor: 'black', colors: ['black', 'pink', 'red'], }) } /* setupColorPicker() { const picker = document.createElement('div') picker.classList.add('color-selector') colors .map(color => { const marker = document.createElement('div') marker.classList.add('marker') marker.dataset.color = color marker.style.backgroundColor = color return marker }) .forEach(color => picker.appendChild(color)) picker.addEventListener('click', ({ target }) => { color = target.dataset.color if (!color) return const current = picker.querySelector('.selected') current && current.classList.remove('selected') target.classList.add('selected') }) document.body.appendChild(picker) // Select the first color picker.firstChild.click() } */ handleClickSelectColor = (event) => { console.log('select color has been clicked, currentColor is: ', this.state) console.log('colorSelect is: ', this.state) console.log('event is: ', event) this.setState({ inSelection: true }) } render() { console.log(this.state) return ( <Wrapper> <a onClick={this.handleClickSelectColor} > select color </a> { this.state.inSelection ? this.state.colors.map( (color) => <div> {color} </div> ) : null } </Wrapper> ) } }
JavaScript
class BaseSource extends BaseSpatializer { /** * Creates a spatializer that keeps track of the relative position * of an audio element to the listener destination. * @param {string} id * @param {MediaStream|HTMLAudioElement} stream */ constructor(id, stream) { super(); this.id = id; /** @type {HTMLAudioElement} */ this.audio = null; /** @type {MediaStream} */ this.stream = null; this.volume = 1; if (stream instanceof HTMLAudioElement) { this.audio = stream; } else if (stream instanceof MediaStream) { this.stream = stream; this.audio = document.createElement("audio"); this.audio.srcObject = this.stream; } else if (stream !== null) { throw new Error("Can't create a node from the given stream. Expected type HTMLAudioElement or MediaStream."); } this.audio.playsInline = true; } play() { if (this.audio) { this.audio.play(); } } /** * Discard values and make this instance useless. */ dispose() { if (this.audio) { this.audio.pause(); this.audio = null; } this.stream = null; super.dispose(); } /** * Changes the device to which audio will be output * @param {string} deviceID */ setAudioOutputDevice(deviceID) { if (this.audio && canChangeAudioOutput) { this.audio.setSinkId(deviceID); } } }
JavaScript
class BTC extends Coin { constructor(network='main') { super('BTC',network); } default_hdtype() { if(network=='main') { return -0; } else { return -1; } } //other overloads as necessary...call the base as much as possible }
JavaScript
class LockDevice extends Component { constructor(props) { super(props); this.state = { page: "devices" } } componentDidMount(){ } render() { return ( <div className="animated fadeIn"> <Row> <Col xs="12" sm="6" lg="6"> <Lock color="success" header='Home' mainText="Home Lock" smallText="small text here" /> </Col> </Row> </div> ); } }
JavaScript
class AzureKeyVaultSecretReference extends models['SecretBase'] { /** * Create a AzureKeyVaultSecretReference. * @member {object} store The Azure Key Vault linked service reference. * @member {string} [store.referenceName] Reference LinkedService name. * @member {object} [store.parameters] Arguments for LinkedService. * @member {object} secretName The name of the secret in Azure Key Vault. * Type: string (or Expression with resultType string). * @member {object} [secretVersion] The version of the secret in Azure Key * Vault. The default value is the latest version of the secret. Type: string * (or Expression with resultType string). */ constructor() { super(); } /** * Defines the metadata of AzureKeyVaultSecretReference * * @returns {object} metadata of AzureKeyVaultSecretReference * */ mapper() { return { required: false, serializedName: 'AzureKeyVaultSecret', type: { name: 'Composite', polymorphicDiscriminator: { serializedName: 'type', clientName: 'type' }, uberParent: 'SecretBase', className: 'AzureKeyVaultSecretReference', modelProperties: { type: { required: true, serializedName: 'type', isPolymorphicDiscriminator: true, type: { name: 'String' } }, store: { required: true, serializedName: 'store', defaultValue: {}, type: { name: 'Composite', className: 'LinkedServiceReference' } }, secretName: { required: true, serializedName: 'secretName', type: { name: 'Object' } }, secretVersion: { required: false, serializedName: 'secretVersion', type: { name: 'Object' } } } } }; } }
JavaScript
class Empresa extends Cliente{ constructor(nombre , saldo, telefono, tipo){ super(nombre, saldo); this.telefono = telefono; this.tipo = tipo; } }
JavaScript
class Move { /** * Constructor * Create a Move. * @param {String} name : move name * @param {String} type : move type * @param {String} category : caregory * @param {int} pp : power point * @param {int} power : move power * @param {int} accuracy : move accurence (%) */ constructor(name, type, category, pp, power, accuracy) { this.name = name this.type = type this.category = category this.pp = pp this.power = power this.accuracy = accuracy } }
JavaScript
class FileSystemStatsObject { /** * @returns {boolean} */ isSocket () {} }
JavaScript
class AzureFileVolume { /** * Create a AzureFileVolume. * @member {string} shareName The name of the Azure File share to be mounted * as a volume. * @member {boolean} [readOnly] The flag indicating whether the Azure File * shared mounted as a volume is read-only. * @member {string} storageAccountName The name of the storage account that * contains the Azure File share. * @member {string} [storageAccountKey] The storage account access key used * to access the Azure File share. */ constructor() { } /** * Defines the metadata of AzureFileVolume * * @returns {object} metadata of AzureFileVolume * */ mapper() { return { required: false, serializedName: 'AzureFileVolume', type: { name: 'Composite', className: 'AzureFileVolume', modelProperties: { shareName: { required: true, serializedName: 'shareName', type: { name: 'String' } }, readOnly: { required: false, serializedName: 'readOnly', type: { name: 'Boolean' } }, storageAccountName: { required: true, serializedName: 'storageAccountName', type: { name: 'String' } }, storageAccountKey: { required: false, serializedName: 'storageAccountKey', type: { name: 'String' } } } } }; } }
JavaScript
class ApplicationUpgradeUpdateDescription { /** * Create a ApplicationUpgradeUpdateDescription. * @member {string} name * @member {string} upgradeKind Possible values include: 'Invalid', * 'Rolling'. Default value: 'Rolling' . * @member {object} [applicationHealthPolicy] * @member {boolean} [applicationHealthPolicy.considerWarningAsError] * Indicates whether warnings are treated with the same severity as errors. * @member {number} * [applicationHealthPolicy.maxPercentUnhealthyDeployedApplications] The * maximum allowed percentage of unhealthy deployed applications. Allowed * values are Byte values from zero to 100. * The percentage represents the maximum tolerated percentage of deployed * applications that can be unhealthy before the application is considered in * error. * This is calculated by dividing the number of unhealthy deployed * applications over the number of nodes where the application is currently * deployed on in the cluster. * The computation rounds up to tolerate one failure on small numbers of * nodes. Default percentage is zero. * @member {object} [applicationHealthPolicy.defaultServiceTypeHealthPolicy] * @member {number} * [applicationHealthPolicy.defaultServiceTypeHealthPolicy.maxPercentUnhealthyPartitionsPerService] * The maximum allowed percentage of unhealthy partitions per service. * Allowed values are Byte values from zero to 100 * * The percentage represents the maximum tolerated percentage of partitions * that can be unhealthy before the service is considered in error. * If the percentage is respected but there is at least one unhealthy * partition, the health is evaluated as Warning. * The percentage is calculated by dividing the number of unhealthy * partitions over the total number of partitions in the service. * The computation rounds up to tolerate one failure on small numbers of * partitions. Default percentage is zero. * @member {number} * [applicationHealthPolicy.defaultServiceTypeHealthPolicy.maxPercentUnhealthyReplicasPerPartition] * The maximum allowed percentage of unhealthy replicas per partition. * Allowed values are Byte values from zero to 100. * * The percentage represents the maximum tolerated percentage of replicas * that can be unhealthy before the partition is considered in error. * If the percentage is respected but there is at least one unhealthy * replica, the health is evaluated as Warning. * The percentage is calculated by dividing the number of unhealthy replicas * over the total number of replicas in the partition. * The computation rounds up to tolerate one failure on small numbers of * replicas. Default percentage is zero. * @member {number} * [applicationHealthPolicy.defaultServiceTypeHealthPolicy.maxPercentUnhealthyServices] * The maximum maximum allowed percentage of unhealthy services. Allowed * values are Byte values from zero to 100. * * The percentage represents the maximum tolerated percentage of services * that can be unhealthy before the application is considered in error. * If the percentage is respected but there is at least one unhealthy * service, the health is evaluated as Warning. * This is calculated by dividing the number of unhealthy services of the * specific service type over the total number of services of the specific * service type. * The computation rounds up to tolerate one failure on small numbers of * services. Default percentage is zero. * @member {array} [applicationHealthPolicy.serviceTypeHealthPolicyMap] * @member {object} [updateDescription] * @member {string} [updateDescription.rollingUpgradeMode] Possible values * include: 'Invalid', 'UnmonitoredAuto', 'UnmonitoredManual', 'Monitored' * @member {boolean} [updateDescription.forceRestart] * @member {number} [updateDescription.replicaSetCheckTimeoutInMilliseconds] * @member {string} [updateDescription.failureAction] Possible values * include: 'Invalid', 'Rollback', 'Manual' * @member {string} [updateDescription.healthCheckWaitDurationInMilliseconds] * @member {string} * [updateDescription.healthCheckStableDurationInMilliseconds] * @member {string} [updateDescription.healthCheckRetryTimeoutInMilliseconds] * @member {string} [updateDescription.upgradeTimeoutInMilliseconds] * @member {string} [updateDescription.upgradeDomainTimeoutInMilliseconds] */ constructor() { } /** * Defines the metadata of ApplicationUpgradeUpdateDescription * * @returns {object} metadata of ApplicationUpgradeUpdateDescription * */ mapper() { return { required: false, serializedName: 'ApplicationUpgradeUpdateDescription', type: { name: 'Composite', className: 'ApplicationUpgradeUpdateDescription', modelProperties: { name: { required: true, serializedName: 'Name', type: { name: 'String' } }, upgradeKind: { required: true, serializedName: 'UpgradeKind', defaultValue: 'Rolling', type: { name: 'String' } }, applicationHealthPolicy: { required: false, serializedName: 'ApplicationHealthPolicy', type: { name: 'Composite', className: 'ApplicationHealthPolicy' } }, updateDescription: { required: false, serializedName: 'UpdateDescription', type: { name: 'Composite', className: 'RollingUpgradeUpdateDescription' } } } } }; } }
JavaScript
class CustomVersionFilePlugin { apply(compiler) { compiler.hooks.done.tap(this.constructor.name, () => new Promise((resolve, reject) => { const versionPath = path.join(__dirname, '/../../dist/version.json'); fs.mkdir(path.dirname(versionPath), {recursive: true}, (dirErr) => { if (dirErr) { reject(dirErr); return; } fs.writeFile(versionPath, JSON.stringify({version: APP_VERSION}), 'utf8', (fileErr) => { if (fileErr) { reject(fileErr); return; } resolve(); }); }); })); } }
JavaScript
class ConverterController { constructor() { this._converters = {} } addConverter(name, converter) { this._converters[name] = converter } getConverter(name) { return this._converters[name] } }
JavaScript
class Sticky extends React.Component { componentDidMount () { const stickies = Array.from(document.querySelectorAll(`.${this.props.baseCSS}`)) document.addEventListener('scroll', _throttle((e) => { const fromTop = document.documentElement.scrollTop || document.body.scrollTop const pageBottom = document.documentElement.scrollHeight || document.body.scrollHeight stickies.map(sticky => { const start = this.props.start || sticky.offsetTop const stop = this.props.stop || pageBottom if (fromTop >= start && fromTop <= stop) { sticky.firstElementChild.className = this.props.activeChildCSS } else { sticky.firstElementChild.className = this.props.inactiveChildCSS } }) }, 16.67)) } render () { const { baseCSS, inactiveChildCSS, start, stop, children } = this.props return ( <div className={baseCSS} data-sticky-start={start} data-sticky-stop={stop} > <div className={inactiveChildCSS} > {children} </div> </div> ) } }
JavaScript
class TClay extends Clay { constructor(agr){ super(agr); this.__.signalStore = []; this.__.collected = new Set(); this.__.center = new Proxy(this, { get(target, connectPoint) { return target._getSignalStore(connectPoint); }, set(target, connectPoint, signal) { const me = target; let pair = me.__.contacts.find(p => me.isSamePoint(p[1], connectPoint)) pair && Clay.vibrate(pair[0], connectPoint, signal, me) return true; } }); Object.defineProperty(this, "center", { get() { return this.__.center; } }) this.defineAgreement("sensorPoints",[]); this.onInit(); } _getSignalStore(cp){ let signalStore = this.__.signalStore; const k = signalStore.find(x => this.isSamePoint(cp, x[0])); return k ? k[1] : undefined; } _setSignalStore(cp, signal){ const signalStore = this.__.signalStore; const k = signalStore.find(x => this.isSamePoint(cp, x[0])); k ? k[1] = signal : signalStore.push([cp, signal]); } setSensorPoint(sp,val){ if(this._isValidSensorPoint(sp)) { this._setSignalStore(sp,val); this.__.collected.add(sp); } } _isValidSensorPoint(sp){ return this.agreement.sensorPoints.findIndex(x=>this.isSamePoint(sp,x))>=0; } _allSignalsReady(){ let collected = this.__.collected; let sensorPoints = this.agreement.sensorPoints; return collected.size === sensorPoints.length } onInit(){} }
JavaScript
class Graph { constructor() { this.addNodes = this.addNodes.bind(this) this.removeNode = this.removeNode.bind(this) this.updateNode = this.updateNode.bind(this) this.removeConnectedRelationships = this.removeConnectedRelationships.bind( this ) this.addRelationships = this.addRelationships.bind(this) this.addInternalRelationships = this.addInternalRelationships.bind(this) this.pruneInternalRelationships = this.pruneInternalRelationships.bind(this) this.findNode = this.findNode.bind(this) this.findNodeNeighbourIds = this.findNodeNeighbourIds.bind(this) this.findRelationship = this.findRelationship.bind(this) this.findAllRelationshipToNode = this.findAllRelationshipToNode.bind(this) this.nodeMap = {} this.expandedNodeMap = {} this._nodes = [] this.relationshipMap = {} this._relationships = [] } nodes() { return this._nodes } relationships() { return this._relationships } groupedRelationships() { const groups = {} for (const relationship of Array.from(this._relationships)) { let nodePair = new NodePair(relationship.source, relationship.target) nodePair = groups[nodePair] != null ? groups[nodePair] : nodePair nodePair.relationships.push(relationship) groups[nodePair] = nodePair } return (() => { const result = [] for (const ignored in groups) { const pair = groups[ignored] result.push(pair) } return result })() } addNodes(nodes) { for (const node of Array.from(nodes)) { if (this.findNode(node.id) == null) { this.nodeMap[node.id] = node this._nodes.push(node) } } return this } addExpandedNodes = (node, nodes) => { for (const eNode of Array.from(nodes)) { if (this.findNode(eNode.id) == null) { this.nodeMap[eNode.id] = eNode this._nodes.push(eNode) this.expandedNodeMap[node.id] = this.expandedNodeMap[node.id] ? [...new Set(this.expandedNodeMap[node.id].concat([eNode.id]))] : [eNode.id] } } } removeNode(node) { if (this.findNode(node.id) != null) { delete this.nodeMap[node.id] this._nodes.splice(this._nodes.indexOf(node), 1) } return this } collapseNode = node => { if (!this.expandedNodeMap[node.id]) { return } this.expandedNodeMap[node.id].forEach(id => { const eNode = this.nodeMap[id] this.collapseNode(eNode) this.removeConnectedRelationships(eNode) this.removeNode(eNode) }) this.expandedNodeMap[node.id] = [] } updateNode(node) { if (this.findNode(node.id) != null) { this.removeNode(node) node.expanded = false node.minified = true this.addNodes([node]) } return this } removeConnectedRelationships(node) { for (const r of Array.from(this.findAllRelationshipToNode(node))) { this.updateNode(r.source) this.updateNode(r.target) this._relationships.splice(this._relationships.indexOf(r), 1) delete this.relationshipMap[r.id] } return this } addRelationships(relationships) { for (const relationship of Array.from(relationships)) { const existingRelationship = this.findRelationship(relationship.id) if (existingRelationship != null) { existingRelationship.internal = false } else { relationship.internal = false this.relationshipMap[relationship.id] = relationship this._relationships.push(relationship) } } return this } addInternalRelationships(relationships) { for (const relationship of Array.from(relationships)) { relationship.internal = true if (this.findRelationship(relationship.id) == null) { this.relationshipMap[relationship.id] = relationship this._relationships.push(relationship) } } return this } pruneInternalRelationships() { const relationships = this._relationships.filter( relationship => !relationship.internal ) this.relationshipMap = {} this._relationships = [] return this.addRelationships(relationships) } findNode(id) { return this.nodeMap[id] } findNodeNeighbourIds(id) { return this._relationships .filter( relationship => relationship.source.id === id || relationship.target.id === id ) .map(function(relationship) { if (relationship.target.id === id) { return relationship.source.id } return relationship.target.id }) } findRelationship(id) { return this.relationshipMap[id] } findAllRelationshipToNode(node) { return this._relationships.filter( relationship => relationship.source.id === node.id || relationship.target.id === node.id ) } resetGraph() { this.nodeMap = {} this._nodes = [] this.relationshipMap = {} return (this._relationships = []) } }
JavaScript
class A { /** * @bug https://github.com/Domiii/dbux/issues/428 * NOTE: preset-env will automatically insert a ctor (a new, yet uninstrumented staticContext) and assign `f` in that. * If not handled well, Dbux would assume that `f` belongs to B.constructor (or, if that does not exist, the context that calls the ctor). */ f = () => { console.log('f'); } }
JavaScript
class Service { constructor ( ) { "ngInject"; Object.assign(this, { }); } get log () { return this._log; } set log (value) { this._log.push(value); } }
JavaScript
class EGRDataCollectionProvider extends wrapper_1.ProviderWrapper { constructor(provider, mochaConfig) { super(provider); this.mochaConfig = mochaConfig; } async request(args) { // Truffle if (args.method === "eth_getTransactionReceipt") { const receipt = await this._wrappedProvider.request(args); if ((receipt === null || receipt === void 0 ? void 0 : receipt.status) && (receipt === null || receipt === void 0 ? void 0 : receipt.transactionHash)) { const tx = await this._wrappedProvider.request({ method: "eth_getTransactionByHash", params: [receipt.transactionHash] }); await this.mochaConfig.attachments.recordTransaction(receipt, tx); } return receipt; // Ethers: will get run twice for deployments (e.g both receipt and txhash are fetched) } else if (args.method === 'eth_getTransactionByHash') { const receipt = await this._wrappedProvider.request({ method: "eth_getTransactionReceipt", params: args.params }); const tx = await this._wrappedProvider.request(args); if (receipt === null || receipt === void 0 ? void 0 : receipt.status) { await this.mochaConfig.attachments.recordTransaction(receipt, tx); } return tx; // Waffle: This is necessary when using Waffle wallets. eth_sendTransaction fetches the // transactionHash as part of its flow, eth_sendRawTransaction *does not*. } else if (args.method === 'eth_sendRawTransaction') { const txHash = await this._wrappedProvider.request(args); if (typeof txHash === 'string') { const tx = await this._wrappedProvider.request({ method: "eth_getTransactionByHash", params: [txHash] }); const receipt = await this._wrappedProvider.request({ method: "eth_getTransactionReceipt", params: [txHash] }); if (receipt === null || receipt === void 0 ? void 0 : receipt.status) { await this.mochaConfig.attachments.recordTransaction(receipt, tx); } } return txHash; } return this._wrappedProvider.request(args); } }
JavaScript
class EGRAsyncApiProvider { constructor(provider) { this.provider = provider; } async getNetworkId() { return this.provider.send("net_version", []); } async getCode(address) { return this.provider.send("eth_getCode", [address, "latest"]); } async getLatestBlock() { return this.provider.send("eth_getBlockByNumber", ["latest", false]); } async getBlockByNumber(num) { const hexNumber = `0x${num.toString(16)}`; return this.provider.send("eth_getBlockByNumber", [hexNumber, true]); } async blockNumber() { const block = await this.getLatestBlock(); return parseInt(block.number, 16); } async getTransactionByHash(tx) { return this.provider.send("eth_getTransactionByHash", [tx]); } async call(payload, blockNumber) { return this.provider.send("eth_call", [payload, blockNumber]); } }
JavaScript
class GamesController { /** * * Gets Game Leaderboard * * @static * @param {object} req Express request object * @param {object} res Express response object * @param {object} next Express next object * @returns {object} leaderboard * Leader board consists of the first 10 players with the * highest scores on the platform. We are querying the db to get * players with scores greater than 1 sorted in descending order */ static leaderboard(req, res, next) { return User.find({ gamesWon: { $gte: 1 } }, '-__v -hashedPassword -donations') .limit(10) .sort({ gamesWon: -1 }) .exec((err, users) => { if (err) return next(err); return res.json({ success: true, players: users }); }); } /** * * Gets Game History for a User * * @static * @param {object} req Express request object * @param {object} res Express response object * @param {object} next Express next object * @returns {object} game history */ static history(req, res, next) { const { username } = req.decoded; return Game.find({ players: username }).exec((err, games) => { if (err) return next(err); res.json({ success: true, games }); }); } /** * * @param {object} req - Express request object * @param {object} res - Express response object * @returns {object} - object */ static saveGame(req, res) { const { winner } = req.body; User.findOneAndUpdate( { username: winner }, { $inc: { gamesWon: 1 } }, (err, res) => res ); const gameDetails = new Game(req.body); gameDetails.save() .then((game) => { res.status(201).json({ success: true, message: 'Game saved successfully', game }); }) .catch(() => { res.status(400).json({ success: false, message: 'Game Details not saved' }); }); } }
JavaScript
class Radio { constructor() { this.inputId = `radio-${++id}`; this.labelId = `radio-label-${id}`; this.hasFocus = false; /** Set to true to disable the radio. */ this.disabled = false; /** Set to true to draw the radio in a checked state. */ this.checked = false; /** * This will be true when the control is in an invalid state. Validity in range inputs is determined by the message * provided by the `setCustomValidity` method. */ this.invalid = false; } handleCheckedChange() { if (this.checked) { this.getSiblingRadios().map(radio => (radio.checked = false)); } this.input.checked = this.checked; this.slChange.emit(); } connectedCallback() { this.handleClick = this.handleClick.bind(this); this.handleBlur = this.handleBlur.bind(this); this.handleFocus = this.handleFocus.bind(this); this.handleKeyDown = this.handleKeyDown.bind(this); this.handleMouseDown = this.handleMouseDown.bind(this); } /** Sets focus on the radio. */ async setFocus(options) { this.input.focus(options); } /** Removes focus from the radio. */ async removeFocus() { this.input.blur(); } /** Checks for validity and shows the browser's validation message if the control is invalid. */ async reportValidity() { return this.input.reportValidity(); } /** Sets a custom validation message. If `message` is not empty, the field will be considered invalid. */ async setCustomValidity(message) { this.input.setCustomValidity(message); this.invalid = !this.input.checkValidity(); } getAllRadios() { const form = this.host.closest('sl-form, form') || document.body; if (!this.name) return []; return [...form.querySelectorAll('sl-radio')].filter((radio) => radio.name === this.name); } getSiblingRadios() { return this.getAllRadios().filter(radio => radio !== this.host); } handleClick() { this.checked = this.input.checked; } handleBlur() { this.hasFocus = false; this.slBlur.emit(); } handleFocus() { this.hasFocus = true; this.slFocus.emit(); } handleKeyDown(event) { if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(event.key)) { const radios = this.getAllRadios().filter(radio => !radio.disabled); const incr = ['ArrowUp', 'ArrowLeft'].includes(event.key) ? -1 : 1; let index = radios.indexOf(this.host) + incr; if (index < 0) index = radios.length - 1; if (index > radios.length - 1) index = 0; this.getAllRadios().map(radio => (radio.checked = false)); radios[index].setFocus(); radios[index].checked = true; event.preventDefault(); } } handleMouseDown(event) { // Prevent clicks on the label from briefly blurring the input event.preventDefault(); this.input.focus(); } render() { return (h("label", { part: "base", class: { radio: true, 'radio--checked': this.checked, 'radio--disabled': this.disabled, 'radio--focused': this.hasFocus }, htmlFor: this.inputId, onKeyDown: this.handleKeyDown, onMouseDown: this.handleMouseDown }, h("span", { part: "control", class: "radio__control" }, h("span", { part: "checked-icon", class: "radio__icon" }, h("svg", { viewBox: "0 0 16 16" }, h("g", { stroke: "none", "stroke-width": "1", fill: "none", "fill-rule": "evenodd" }, h("g", { fill: "currentColor" }, h("circle", { cx: "8", cy: "8", r: "3.42857143" }))))), h("input", { ref: el => (this.input = el), id: this.inputId, type: "radio", name: this.name, value: this.value, checked: this.checked, disabled: this.disabled, role: "radio", "aria-checked": this.checked ? 'true' : 'false', "aria-labelledby": this.labelId, onClick: this.handleClick, onBlur: this.handleBlur, onFocus: this.handleFocus })), h("span", { part: "label", id: this.labelId, class: "radio__label" }, h("slot", null)))); } static get is() { return "sl-radio"; } static get encapsulation() { return "shadow"; } static get originalStyleUrls() { return { "$": ["radio.scss"] }; } static get styleUrls() { return { "$": ["radio.css"] }; } static get properties() { return { "name": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "The radio's name attribute." }, "attribute": "name", "reflect": false }, "value": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "The radio's value attribute." }, "attribute": "value", "reflect": false }, "disabled": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Set to true to disable the radio." }, "attribute": "disabled", "reflect": false, "defaultValue": "false" }, "checked": { "type": "boolean", "mutable": true, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "Set to true to draw the radio in a checked state." }, "attribute": "checked", "reflect": true, "defaultValue": "false" }, "invalid": { "type": "boolean", "mutable": true, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "This will be true when the control is in an invalid state. Validity in range inputs is determined by the message\nprovided by the `setCustomValidity` method." }, "attribute": "invalid", "reflect": true, "defaultValue": "false" } }; } static get states() { return { "hasFocus": {} }; } static get events() { return [{ "method": "slBlur", "name": "sl-blur", "bubbles": true, "cancelable": true, "composed": true, "docs": { "tags": [], "text": "Emitted when the control loses focus." }, "complexType": { "original": "any", "resolved": "any", "references": {} } }, { "method": "slChange", "name": "sl-change", "bubbles": true, "cancelable": true, "composed": true, "docs": { "tags": [], "text": "Emitted when the control's checked state changes." }, "complexType": { "original": "any", "resolved": "any", "references": {} } }, { "method": "slFocus", "name": "sl-focus", "bubbles": true, "cancelable": true, "composed": true, "docs": { "tags": [], "text": "Emitted when the control gains focus." }, "complexType": { "original": "any", "resolved": "any", "references": {} } }]; } static get methods() { return { "setFocus": { "complexType": { "signature": "(options?: FocusOptions) => Promise<void>", "parameters": [{ "tags": [], "text": "" }], "references": { "Promise": { "location": "global" }, "FocusOptions": { "location": "global" } }, "return": "Promise<void>" }, "docs": { "text": "Sets focus on the radio.", "tags": [] } }, "removeFocus": { "complexType": { "signature": "() => Promise<void>", "parameters": [], "references": { "Promise": { "location": "global" } }, "return": "Promise<void>" }, "docs": { "text": "Removes focus from the radio.", "tags": [] } }, "reportValidity": { "complexType": { "signature": "() => Promise<boolean>", "parameters": [], "references": { "Promise": { "location": "global" } }, "return": "Promise<boolean>" }, "docs": { "text": "Checks for validity and shows the browser's validation message if the control is invalid.", "tags": [] } }, "setCustomValidity": { "complexType": { "signature": "(message: string) => Promise<void>", "parameters": [{ "tags": [], "text": "" }], "references": { "Promise": { "location": "global" } }, "return": "Promise<void>" }, "docs": { "text": "Sets a custom validation message. If `message` is not empty, the field will be considered invalid.", "tags": [] } } }; } static get elementRef() { return "host"; } static get watchers() { return [{ "propName": "checked", "methodName": "handleCheckedChange" }]; } }
JavaScript
class RepositoryHandlerError extends Error { /** * @param {Symbol} type - error type * @param {Object} meta - meta information */ constructor(type, meta = {}) { const {repository} = meta let message = '' switch(type) { case REPOSITORY_NOT_FOUND: message = `Repository ${repository} not found.`; break; case DATABASE_ERROR: message = `An error occured while storing/loading repository ${repository}.`; break; } super('Error during repository handling') this.type = REPO_ERROR_TYPE this.detail = message } }
JavaScript
class Store { constructor() { this.db = new Map() this.pubsub = new PubSub() } static build() { return new Store() } async has(k) { return await this.db.has(k) } async get(k) { return await this.db.get(k) } async set(k, v) { await this.db.set(k, v) await this.pubsub.pub(k, v, 'set') } async del(k) { if (! await this.has(k)) throw new StoreError('store.error.delete.key.not.exists', k) let v = await this.get(k) await this.db.delete(k) await this.pubsub.pub(k, v, 'del') } find(q, f = x=>x) { if (typeof q === 'undefined') { q = () => true } else if (q instanceof RegExp) { let test = RegExp.prototype.test.bind(q) q = ([k]) => (test(k)) } return function* gen() { for (let [k, v] of this.db.entries()) { let kv = [k, f(v)] if ( q(kv) ) yield kv } }.bind(this)() } async findOne(q) { let { value, done } = await this.find(q).next() if (!done){ let [,v] = value return v } else return undefined } async sub(src, k, cb, now) { if (! await this.has(k)) throw new StoreError('store.error.sub.key.not.exists(k)', k) await this.pubsub.sub(src, k, cb) if (now) { let v = await this.get(k) await this.pubsub.pub(k, v, 'sub') } } async unsub(src, k) { if (! await this.has(k)) throw new StoreError('store.error.unsub.key.not.exists(k)', k) await this.pubsub.unsub(src, k) } async subGlobal(src, cb){ await this.pubsub.subGlobal(src, cb) } async unsubGlobal(src) { await this.pubsub.unsubGlobal(src) } async unsubEveryWhere(src) { await this.pubsub.unsubEveryWhere(src) } }
JavaScript
class Transaction { constructor(fromAddress, toAddress, amount) { this.fromAddress = fromAddress; this.toAddress = toAddress; this.amount = amount; } }
JavaScript
class StorageModelManager extends ModelManagerAbstract { /** * @param {StorageLocatorAbstract} locator */ constructor(locator) { super(); /** @protected */ this._locator = locator; } /** * @inheritdoc * * @return {Promise.<Model>} */ get(id, modelClass, options = {}) { return new Promise((resolve, reject) => { try { const model = this.getSync(id, modelClass, options); resolve(model); } catch (e) { reject(e); } }); } /** * Synchronous version of the `get` method. * * @param id * @param {Model.prototype} modelClass * @param {Object} [options] * * @return {Model} */ getSync(id, modelClass, options = {}) { const locate = this._locator.locateById(id); const item = this._locator.storage.getItem(locate); if (item === null) { throw new TypeError(`Item with the key [${locate}] was not found`); } return new modelClass(this.createInputTransformer().transform(JSON.parse(item))); } /** * Get all stored Models. * * @param {Model.prototype} modelClass * * @return {Model.Array} */ getAll(modelClass) { const ArrayModel = new Model.Array(modelClass); const items = []; this.getKeys().forEach((id) => { items.push(this.getSync(id, modelClass)); }); return ArrayModel(items); } /** * @inheritdoc */ save(model, options = {}) { return new Promise((resolve, reject) => { try { this.saveSync(model, options); resolve({}); } catch (e) { reject(e); } }); } /** * Synchronous version of the `save` method. * * @param {Model} model * @param {Object} [options] */ saveSync(model, options = {}) { this._locator.storage.setItem(this._locator.locate(model), JSON.stringify(this.createOutputTransformer().transform(model))); this._persistId(this._locator.getModelId(model)); } /** * @inheritdoc */ remove(model, options = {}) { return new Promise((resolve, reject) => { try { this.removeSync(model, options); resolve({}); } catch (e) { reject(e); } }); } /** * Synchronous version of the `remove` method. * * @param {Model} model * @param {Object} [options] */ removeSync(model, options = {}) { this._locator.storage.removeItem(this._locator.locate(model)); this._removeId(this._locator.getModelId(model)); } /** * Does exists an item with given id? * * @param id * * @return {boolean} */ has(id) { return this._locator.storage.getItem(this._locator.locateById(id)) !== null; } /** * Return Array with all stored models ids. */ getKeys() { const ids = []; const item = this._locator.storage.getItem(this._getIdsKey()); if (item !== null) { let data; try { data = JSON.parse(item); } catch (e) { data = []; } if (Array.isArray(data)) { data.forEach((id) => { if (id !== null && this.has(id) && typeof id.toString === 'function' && ids.indexOf(id.toString()) === -1 ) { ids.push(id.toString()); } }); } } return ids; } /** * The key that gives access to Models Ids. * * @return {string} * * @protected */ _getIdsKey() { return '__ids__' + this._locator.basePath; } /** * Persist Model Id. * * @param id * * @protected */ _persistId(id) { if (id !== null && this.has(id) && typeof id.toString === 'function') { const ids = this.getKeys(); if (ids.indexOf(id.toString()) === -1) { ids.push(id.toString()); this._locator.storage.setItem(this._getIdsKey(), JSON.stringify(ids)); } } } /** * Remove Model Id. * * @param id * * @protected */ _removeId(id) { const ids = this.getKeys().filter(el => el.toString() !== id.toString()); this._locator.storage.setItem(this._getIdsKey(), JSON.stringify(ids)); } }
JavaScript
class MissionControl { /** * Create a MissionControl instance * @property {String} commandData * @example: "12 N \n LMLMLMLMM" * @property {String} [location] - The name/location of the control center. * Used in error messaging. */ constructor({ commandData, location }) { this.location = location ? location : 'NASA'; this.state = { status: statusEnums['SUCCESS'] }; this.extractGridCoords(commandData); this.createRovers(commandData); } /** * Extract MissionControl's grid size from input data * @property {String} input - the full instructions for this instance of MissionControl * @example: "55\n12 N\nLMLMLMLMM" */ extractGridCoords(input) { const gridCoords = input.match(/^\d\d\n/g); if (gridCoords) { const arr = gridCoords[0].split(''); this.gridSize = { w: parseInt(arr[0]), h: parseInt(arr[1]) }; } else { // If a descernable gridSize does not exist in the very first line of // the input data, then we stop everything. // Critical failure. Yes it's quite conservative - but we're controlling // rovers on mars, thus a failure of this kind is unacceptable. this.state.status = statusEnums['CRITICAL_FAILURE']; this.state.details = `Critical Failure!` + ` CommandData does not begin with valid GridSize data.`; console.error(this.state.details); } } /** * Extract each rover's basic start position, orientation and command sequence * @property {String} input - Rover's start / command details. * @example: "12 N \n LMLMLMLMM" */ createRovers(input) { this.rovers = input.match(/\d\d\s[N|E|S|W]\n?\D+/g).reduce((arr, match) => { arr.push(new Rover({ initData: match })); return arr; }, []); } /** * Execute Rover commands synchronously. */ deployRovers() { // If mission control has already encountered a Critical Error, then simply return // false and cease operations. if (this.state.status === statusEnums['CRITICAL_FAILURE']) { console.error(`Uh ${this.location}, we've had a problem. Details: ${this.state.details}`) return false; } // Excecute all rover command sequences, one rover at a time this.rovers.forEach((rover, i) => { let roverIsViable = true; // Step through current rover's entire command sequence, // checking each step as we go while (rover.commands.length !== 0 && roverIsViable) { const newState = rover.getNextState(); // Check if Rover's next move is valid before we commit it const viability = this.checkViability({ newState, i }); if (viability.valid) { rover.commitState({ ...newState }); } else { // We found a problem with the Rover's commands, so stop here. // This might be being a little conservative - but when a rover excutes an // invalid command, it will mark itself as invalid and move itself back to // it's starting position and orientation. // No further commands are to be executed by this rover. roverIsViable = false; rover.markInvalid({ reason: viability.reason }); } } }); // Finished moving all the rovers - so print out the final positions of each Rover. this.printFinalPositions(); } /** * @typedef {Object} viability * @property {Boolean} valid - Boolean stating the purposed move's validity * @property {String} [reason] - Any possible error details */ /** * Return the viability of a single Rover command, based on it's current position * (and the * position of other rovers) * @property {Object} newState - Object containing the purposed new state of the Rover * @property {Object} [newState.position] * @property {Array} [newState.orientation] * @property {Number} i - Relevant Rover's index integer * @returns {viability} */ checkViability({ newState, i }) { const viability = { valid: true }; // Only commands where the position changes, need to be evaluated for validity. if (newState.position) { // 1 - check if the move puts the rover out of bounds: if (this.checkOutOfBounds({ ...newState.position })) { Object.assign(viability, { valid: false, reason: `Commands contain a directive that moves the rover outside bounds`, }); this.state.status = statusEnums['PARTIAL_FAILURE']; this.state.details = viability.reason; // 2 - check if the move puts the rover into the same square as any other rovers: } else if (this.checkCollisionCourse({ ...newState, roverIndex: i })) { Object.assign(viability, { valid: false, reason: `Commands contain a directive that would cause rovers to collide`, }); this.state.status = statusEnums['PARTIAL_FAILURE']; this.state.details = viability.reason; } } return viability; } /** * Check the new potential position for a Rover for collision with all other Rovers * @property {Object} position - Object containing new purposed position of the Rover * @property {Number} position.x - x value of new Rover position * @property {Number} position.y - y value of new Rover position * @property {Number} roverIndex - Relevant Rover's index integer * @returns {Boolean} collisionDetected - Will the Rover collide with anothe Rover */ checkCollisionCourse({ position, roverIndex }) { let collisionDetected = false; // Step through the rovers and check that no rover is already in the // nominated position this.rovers.forEach((rover, i) => { if (roverIndex !== i && position.x === rover.state.position.x && position.y === rover.state.position.y) { collisionDetected = true; } }); return collisionDetected; } /** * Check the new potential position for a Rover for collision with all other Rovers * @property {Object} position - Object containing new purposed position of the Rover * @property {Number} position.x - x value of new Rover position * @property {Number} position.y - y value of new Rover position * @property {Number} roverIndex - Relevant Rover's index integer * @returns {Boolean} collisionDetected - Will the Rover collide with anothe Rover */ checkOutOfBounds({ x, y }) { let outOfBounds = false; if (x > this.gridSize.w || x < 0) { outOfBounds = true; } else if (y > this.gridSize.h || y < 0) { outOfBounds = true; } return outOfBounds; } /** * Print out the final positions of Rovers into the console (and return them) * @returns {String} output - All final Rover positions and orientations * (and some extra details if they're erroneous) */ printFinalPositions() { let output = ``; this.rovers.forEach(rover => { output += `${rover.state.position.x}${rover.state.position.y} ${rover.state.orientation}` if (rover.state.status === statusEnums['CRITICAL_FAILURE']) { output += ` - Rover is INVALID. ${rover.state.details}`; } output += `\n`; }); output += '=========='; console.log(output); return output; } }
JavaScript
class Header extends React.Component{ constructor(props){ super(props); this.state = { navbarShown: false, }; this.toggleNavbar = this.toggleNavbar.bind(this); } toggleNavbar(){ this.setState((state) => ({ navbarShown: !state.navbarShown })); } render(){ return ( <> <div className = "Header rows_container"> <div className = "row cols_container align_center section_padding"> <div className="rows_container center align_center"> {this.props.headerWidgetBtn} </div> <Navbar AppURLs = {this.props.AppURLs} navbarShown = {this.state.navbarShown} navbarLinks = {[ {URL: this.props.AppURLs.domain, text: 'Home'}, {URL: this.props.AppURLs.domain+'fonts', text: 'Applications'}, {URL: '#', text: 'About'}, {URL: this.props.AppURLs.domain+'admin/home', text: 'Login'}, ]} toggleNavbar = {this.toggleNavbar} /> </div> { (this.props.subHeader !== null ? <div className="subHeader cols_container space_between align_center section_padding"> <div className="cols_container align_center"> {this.props.subHeader.leftCol} </div> <div className="cols_container align_center"> {this.props.subHeader.rightCol} </div> </div> : '' ) } {this.props.headerWidget} </div> </> // ); } }
JavaScript
class AudioResources { // Construtor. constructor(numcanais) { this.numcanais = numcanais||10; this.sons = {}; this.canais = []; this.ativos = {}; this.loop = []; for(var i = 0; i < this.numcanais; i++) { this.canais[i] = { "audio": new Audio(), "fim": -1 }; } } // Carrega e adiciona uma faixa de audio. Load(key, src, loop) { this.sons[key] = new Audio(src); this.sons[key].load(); this.loop.push(loop); } // Reproduz uma faixa de audio. Play(key, duration) { if(this.ativos[key]) return; if(duration) { this.ativos[key] = true; setTimeout((function(that){ return function(){ delete that.ativos[key]; }; })(this), duration); } var agora = new Date(); for(var i = 0; i < this.numcanais; i++) { if(this.canais[i].fim<agora.getTime()) { this.canais[i].fim = agora.getTime()+this.sons[key].duration*1000; this.canais[i].audio.src = this.sons[key].src; this.canais[0].audio.addEventListener('ended', function() { this.currentTime = 0; this.play(); }, false); this.canais[i].audio.play(); break; } } } }
JavaScript
class DateFormat extends Helper { get defaultOutputFormat() { const config = getOwner(this).resolveRegistration('config:environment'); return config.date.outputFormat; } compute([date, outputFormat, inputFormat], options = {}) { if (!date) { return; } let normalizedDate = normalizeDate(date, inputFormat); const outFormat = outputFormat || this.defaultOutputFormat; if (options.timeZone) { normalizedDate = utcToZonedTime(normalizedDate, options.timeZone); } return format(normalizedDate, outFormat, options); } }
JavaScript
class HttpClientError extends Error { /** * @param {String} message * @param {Number} status * A function to load all routes */ constructor(message = 'HTTPClientError occured!') { super(message); this.message = message; Error.captureStackTrace(this, this.constructor); } /** * @param {String} str * A function to load all routes */ set message(str) { if (str instanceof Object) { this.message = JSON.stringify(str); } else { this.message = str; } } }
JavaScript
class Http400Error extends HttpClientError { /** * constructor function to for HTTP400 error * @param {String} message * @param {Number} status */ constructor(message = 'bad request', status = 400) { super(message); this.status = status; } }
JavaScript
class Http404Error extends HttpClientError { /** * constructor function for HTTP404 error * @param {String} message * @param {Number} status */ constructor(message = 'Method not found', status = 404) { super(message); this.status = status; } }
JavaScript
class LambdaActor { constructor(){ this.executionContext = new ExecutionContext(); this.executionContext.receive = this._postBack; } send = (text) => { this.executionContext.send(text); }; _postBack = (msg) => { this.receive(msg); }; // to be overwritten receive = () => {}; }
JavaScript
class SimpleWitBot extends index_1.WitAiBot { constructor() { super(...arguments); // intents mappings bound to specific Wit.ai Bot, the intent names MUST match // the intents as defined in Wit.ai Console. this.intents = { provide_name: (data, request) => this.askEmailorPhone(data.entities, request), by_email: (data, request) => this.contactMeByEmail(data, request), by_phone: (data, request) => this.contactMeByPhone(data, request), provide_phone: (data, request) => this.providePhoneNumber(data.entities, request), provide_email: (data, request) => this.provideEmailAddress(data.entities, request), unknown: (data, request) => this.unknown(data, request) }; } // The following method is invoked only for a start event, sent by Vivocha at the very beginning // of the conversation (in other words it wakes-up the bot) async getStartMessage(request) { const res = { event: 'continue', messages: [prepareBotMessage("Hello, I'm a Vivocha Wit Bot, what's your name?")], data: request.data, settings: request.settings, //Please note how contexts are set (and checked in each intent handler) context: _.merge(request.context, { contexts: ['ask_for_name'] }) }; return res; } // user provided her name, then the Wit.ai 'provide_name' was detected async askEmailorPhone(entities, request) { let name = ''; if (entities.contact) { name = entities.contact.map(v => v.value).join(' '); } const pre = `Thank you ${name}, `; let response = { event: 'continue', messages: [prepareBotMessage(`${pre}do you prefer to be contacted by email or by phone?`)], data: { name }, contexts: ['recontact_by_email_or_phone'] }; return response; } ; // user said she prefers to be contacted by email... async contactMeByEmail(data, request) { let response = {}; if (this.inContext(request.context.contexts, ['recontact_by_email_or_phone'])) { response = { messages: [prepareBotMessage('Good, send me your email address, please')], contexts: [...request.context.contexts, 'ask_for_email'], event: 'continue', data: request.data }; } else { response = { messages: [prepareBotMessage('ERROR')], contexts: ['end'], data: request.data || {}, event: 'end' }; } return response; } // user chose to be contacted by phone async contactMeByPhone(data, request) { let response = {}; if (this.inContext(request.context.contexts, ['recontact_by_email_or_phone'])) { response = { messages: [prepareBotMessage(`OK ${request.data.name}, text me your phone number, please`)], contexts: [...request.context.contexts, 'ask_for_phone'], event: 'continue', data: request.data }; } else { response = { messages: [prepareBotMessage('ERROR')], contexts: ['end'], data: request.data || {}, event: 'end' }; } return response; } // user sent her phone number and the correponding intent was detected by the Wit.ai NLP engine async providePhoneNumber(data, request) { let response = {}; if (this.inContext(request.context.contexts, ['ask_for_phone', 'recontact_by_email_or_phone'])) { response = { messages: [prepareBotMessage(`Perfect, ${request.data.name}. We will call you as soon as possible. Thank you and bye! :)`)], contexts: ['end'], // collect phone number entity data: { phone: data.phone_number[0].value }, // Bot sends the 'end' event to communicate to Vivocha to close the contact, conversation finished. event: 'end' }; } else { response = { messages: [prepareBotMessage('ERROR')], contexts: ['end'], data: request.data || {}, event: 'end' }; } return response; } // user chose to be recontacted by email and provided the related address async provideEmailAddress(data, request) { let response = {}; if (this.inContext(request.context.contexts, ['ask_for_email', 'recontact_by_email_or_phone'])) { response = { messages: [prepareBotMessage(`Perfect, ${request.data.name}. We will send soon an email to the provided address. Thank you and goodbye! :)`)], contexts: ['end'], // collect email address data: { email: data.email[0].value }, event: 'end' }; } else { response = { messages: [prepareBotMessage('ERROR')], contexts: ['end'], data: request.data || {}, event: 'end' }; } return response; } // when Wit.ai is not able to detect an intent, WitAiBot class maps an 'unknown' intent, here's the handler async unknown(data, request) { let response = { event: 'continue', messages: [prepareBotMessage("Sorry, I didn't get that. Can you say it again?")], contexts: request.context.contexts, data: request.data || {} }; return response; } }
JavaScript
class PfUtil { constructor () { this.isMSIE = (new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) !== null) ? parseFloat( RegExp.$1 ) : false; this.isIE = /(MSIE|Trident\/|Edge\/)/i.test(window.navigator.userAgent); } addClass (el, c) { // where modern browsers fail, use classList if (el.classList) { el.classList.add(c); } else { el.className += ' ' + c; el.offsetWidth; } } removeClass (el, c) { if (el.classList) { el.classList.remove(c); } else { el.className = el.className.replace(c,'').replace(/^\s+|\s+$/g,''); } } getClosest (el, s) { //el is the element and s the selector of the closest item to find // source http://gomakethings.com/climbing-up-and-down-the-dom-tree-with-vanilla-javascript/ const former = s.charAt(0); const latter = s.substr(1); for ( ; el && el !== document; el = el.parentNode ) {// Get closest match if ( former === '#' ) { // If selector is an ID if ( el.id === latter ) { return el; } } else if ( former === '.' ) {// If selector is a class if ( new RegExp(latter).test(el.className) ) { return el; } } else { // we assume other selector is tag name if ( el.nodeName === s ) { return el; } } } return false; } // tooltip / popover stuff isElementInViewport (t) { // check if this.tooltip is in viewport const r = t.getBoundingClientRect(); return ( r.top >= 0 && r.left >= 0 && r.bottom <= (window.innerHeight || document.documentElement.clientHeight) && r.right <= (window.innerWidth || document.documentElement.clientWidth) ); } getScroll () { // also Affix and scrollSpy uses it return { y: window.pageYOffset || document.documentElement.scrollTop, x: window.pageXOffset || document.documentElement.scrollLeft }; } reflow (el) { // force reflow return el.offsetHeight; } once (el, type, listener, self) { let one = function (e) { try { listener.call(self, e); } finally { el.removeEventListener(type, one); } }; el.addEventListener(type, one); } }
JavaScript
class Toast { // #region Static functions /** * Get html for the error container. * * @param {string} id * @returns {string} raw HTML string */ static getContainerHTML(id) { return `<div id="${id}" class="position-fixed bottom-0 end-0 p-3" style="z-index: 11"> <div class="toast-container"> </div> </div>`; } /** * Get html for a single toast item. * * @param {string} id * @param {string} body * @param {boolean} success * @returns {string} raw HTML string */ static singleToastItem(id, body, success = false) { return `<div id="${id}" class="toast${ success ? ' toast-success' : '' } align-items-center" role="alert" aria-live="assertive" aria-atomic="true"> <div class="d-flex"> <div class="toast-body"> ${body} </div> <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button> </div> </div>`; } // #endregion // #region Private instance variables /** @type {JQuery} */ #container; // #endregion // #region Public functions /** * Create a toast object. * * @constructor * @param {JQuery} parentContainer * @param {string} containerId */ constructor(parentContainer, containerId) { parentContainer.append(Toast.getContainerHTML(containerId)); this.#container = $(`#${containerId}`); } /** * Get id of containing dom element. * * @returns {string} id */ getId() { return this.#container[0].id; } /** * Show toast message for a limited time. * * @param {string} id * @param {string} body * @param {number} fadeTime * @param {number} removeTime * @param {boolean} success * @param {{animation: boolean|undefined, autohide: boolean|undefined, delay: number|undefined}} options */ flash(id, body, fadeTime, removeTime, success, options) { this.#container.append(Toast.singleToastItem(id, body, success)); const selector = $(`#${id}`); const toast = new BSToast(selector, options); toast.show(); setTimeout(() => { toast.dispose(); setTimeout(() => { selector.remove(); }, removeTime); }, fadeTime); } /** * Remove dom element for this toast. */ remove() { this.#container.remove(); } // #endregion }
JavaScript
class ExtendedError extends Error { /** * @description Create a custom (extended) error. * @param {string} message Error message * @param {...*} params Extra parameters */ constructor(message, ...params) { super(...params); this.message = message; this.name = this.constructor.name; Error.captureStackTrace && Error.captureStackTrace(this, this.constructor); } }
JavaScript
class GlancerEngine { constructor() { this.loader = new FileLoader(); this.resources = new Resources(); } createLoop(canvas) { return new Loop(canvas); } }
JavaScript
class Loop { /** * @param {HTMLCanvasElement} canvas */ constructor(canvas) { this.status = Loop.STOPPED; this.render = new Render(); this.controller = undefined; this.scene = undefined; this.frame = 0; this.watch = undefined; } setController(controller) { if (this.controller) this.controller.releaseControl(); this.controller = controller; return controller.requestControl(this.render.context.canvas); } /** * Start loop * @return {Boolean} */ start() { if (this.frame > 0) this.stop(); this.watch = new TimeWatch(); let controllerPosition; const frameLoop = timeNow => { this.watch.tick(timeNow); if (this.controller) { this.status = Loop.CONTROLLER; this.controller.update(this.watch.delta); controllerPosition = this.controller.position; } else controllerPosition = undefined; if (this.scene) { this.status = Loop.SCENE; this.scene.update(this.watch.delta); if (this.render) { this.status = Loop.RENDER; if (! this.render.drawScene(this.watch.delta, this.scene, controllerPosition)) return false; } } this.status = Loop.REQUEST; this.frame = requestAnimationFrame(frameLoop, this.render.canvas); }; this.frame = requestAnimationFrame(frameLoop, this.render.canvas); return true; } /** * Stop loop * @return {Boolean} */ stop() { if (this.frame == 0) return false; cancelAnimationFrame(this.frame); this.frame = 0; return true; } }
JavaScript
class FluidType extends HTMLElement{// render function get html(){return` <style>:host { --fluid-type-min-size: 1; --fluid-type-max-size: 2; --fluid-type-min-screen: 20; --fluid-type-max-screen: 88; font-size: calc( (var(--fluid-type-min-size) * 1rem) + (var(--fluid-type-max-size) - var(--fluid-type-min-size)) * (100vw - (var(--fluid-type-min-screen) * 1rem)) / (var(--fluid-type-max-screen) - var(--fluid-type-min-screen)) ); }</style> <slot></slot>`}// properties available to the custom element for data binding static get properties(){return{}}/** * Store the tag name to make it easier to obtain directly. * @notice function name must be here for tooling to operate correctly */static get tag(){return"fluid-type"}/** * life cycle */constructor(delayRender=!1){super();// set tag for later use this.tag=FluidType.tag;this.template=document.createElement("template");this.attachShadow({mode:"open"});if(!delayRender){this.render()}}/** * life cycle, element is afixed to the DOM */connectedCallback(){if(window.ShadyCSS){window.ShadyCSS.styleElement(this)}}render(){this.shadowRoot.innerHTML=null;this.template.innerHTML=this.html;if(window.ShadyCSS){window.ShadyCSS.prepareTemplate(this.template,this.tag)}this.shadowRoot.appendChild(this.template.content.cloneNode(!0))}}
JavaScript
class StateComponent extends React.Component { constructor() { super(); this.subscription = null; this.handleUpdate = this.handleUpdate.bind(this); } componentWillMount() { this.setState({ stateProps: getStatePropsFromKeys(this.props.keys) }); this.subscription = store.subscribe(this.handleUpdate); } componentWillUnmount() { if (typeof this.subscription === 'function') { this.subscription(); } } handleUpdate() { const stateProps = getStatePropsFromKeys(this.props.keys); const isEqual = Object .keys(this.state.stateProps) .map(k => ({ key: k, value: this.state.stateProps[k] })) .every(item => item.value === stateProps[item.key]); if (!isEqual) { this.setState({ stateProps }); } } render() { const { Component } = this.props; return ( <Component {...this.props.props} {...this.state.stateProps} /> ); } }
JavaScript
class WT_NumberUnitView extends HTMLElement { constructor() { super(); this.attachShadow({mode: "open"}); this.shadowRoot.appendChild(this._getTemplate().content.cloneNode(true)); this._numberText = ""; this._unitText = ""; this._isInit = false; } _getTemplate() { return WT_NumberUnitView.TEMPLATE; } _defineChildren() { this._number = this.shadowRoot.querySelector(`#number`); this._unit = this.shadowRoot.querySelector(`#unit`); } connectedCallback() { this._defineChildren(); this._isInit = true; this._updateFromNumberText(); this._updateFromUnitText(); } _updateFromNumberText() { this._number.textContent = this._numberText; } /** * Sets the text value of this view's number component. * @param {String} text The new text value. */ setNumberText(text) { if (this._numberText === text) { return; } this._numberText = text; if (this._isInit) { this._updateFromNumberText(); } } _updateFromUnitText() { this._unit.textContent = this._unitText; } /** * Sets the text value of this view's unit component. * @param {String} text The new text value. */ setUnitText(text) { if (this._unitText === text) { return; } this._unitText = text; if (this._isInit) { this._updateFromUnitText(); } } }
JavaScript
class Tabs extends Container { /** * @desc Create an instance of Tabs * @constructor * @param {module:nyc/Tabs~Tabs.Options} options Constructor options */ constructor(options) { super(options.target) this.getContainer().append($(Tabs.HTML)).addClass('tabs') this.btns = this.find('.btns') this.tabs = this.find('.container') /** * @desc The active tab * @public * @member {jQuery} */ this.active = null /** * @private * @member {jQuery} */ this.ready = false this.render(options.tabs) } /** * @desc Open a tab * @public * @method * @param {jQuery|Element|string} tab Tab panel */ open(tab) { tab = this.find(tab) this.find('.btns h2').removeClass('active') this.find('.tab') .attr('aria-hidden', true) .removeClass('active') this.btns.find('.btn') .removeClass('active') tab.addClass('active') .attr('aria-hidden', false) .attr('tabindex', 1000) .focus() this.find('.btn').attr('aria-selected', false) tab.data('btn').addClass('active') .attr('aria-selected', true) .parent().addClass('active') this.active = tab this.trigger('change', this) } /** * @private * @method * @param {Array<module:nyc/Tabs~Tabs.Tab>} tabs The tabs */ render(tabs) { let opened = false tabs.forEach((tab, i) => { const btnId = nyc.nextId('tab-btn') const tb = $(tab.tab) .addClass(`tab tab-${i}`) .attr('aria-labelledby', btnId) .attr('role', 'tabpanel') .attr('aria-hidden', true) const pnlId = tb.attr('id') || nyc.nextId('tab-pnl') tb.attr('id', pnlId) const btn = $(Tabs.BTN_HTML) .attr('id', btnId) .attr('aria-controls', pnlId) .attr('aria-selected', false) .click($.proxy(this.btnClick, this)) .addClass(`btn-tab btn-${i}`) .data('tab', tb) .append(tab.title) tb.data('btn', btn) this.btns.append($('<h2></h2>').append(btn)) this.tabs.append(tb) if (tab.active) { this.open(tb) opened = true } }) if (!opened) { this.open(tabs[0].tab) } this.ready = true } /** * @private * @method * @param {jQuery.Event} event Event object */ btnClick(event) { this.open($(event.currentTarget).data('tab')) } }
JavaScript
class SvelteComponent { $destroy() { destroy_component(this, 1); this.$destroy = noop; } $on(type, callback) { const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = [])); callbacks.push(callback); return () => { const index = callbacks.indexOf(callback); if (index !== -1) callbacks.splice(index, 1); }; } $set($$props) { if (this.$$set && !is_empty($$props)) { this.$$.skip_bound = true; this.$$set($$props); this.$$.skip_bound = false; } } }
JavaScript
class SvelteComponentDev extends SvelteComponent { constructor(options) { if (!options || (!options.target && !options.$$inline)) { throw new Error("'target' is a required option"); } super(); } $destroy() { super.$destroy(); this.$destroy = () => { console.warn('Component was already destroyed'); // eslint-disable-line no-console }; } $capture_state() { } $inject_state() { } }
JavaScript
class RouteItem { /** * Initializes the object and creates a regular expression from the path, using regexparam. * * @param {string} path - Path to the route (must start with '/' or '*') * @param {SvelteComponent|WrappedComponent} component - Svelte component for the route, optionally wrapped */ constructor(path, component) { if (!component || typeof component != "function" && (typeof component != "object" || component._sveltesparouter !== true)) { throw Error("Invalid component object"); } // Path must be a regular or expression, or a string starting with '/' or '*' if (!path || typeof path == "string" && (path.length < 1 || path.charAt(0) != "/" && path.charAt(0) != "*") || typeof path == "object" && !(path instanceof RegExp)) { throw Error("Invalid value for \"path\" argument - strings must start with / or *"); } const { pattern, keys } = parse(path); this.path = path; // Check if the component is wrapped and we have conditions if (typeof component == "object" && component._sveltesparouter === true) { this.component = component.component; this.conditions = component.conditions || []; this.userData = component.userData; this.props = component.props || {}; } else { // Convert the component to a function that returns a Promise, to normalize it this.component = () => Promise.resolve(component); this.conditions = []; this.props = {}; } this._pattern = pattern; this._keys = keys; } /** * Checks if `path` matches the current route. * If there's a match, will return the list of parameters from the URL (if any). * In case of no match, the method will return `null`. * * @param {string} path - Path to test * @returns {null|Object.<string, string>} List of paramters from the URL if there's a match, or `null` otherwise. */ match(path) { // If there's a prefix, check if it matches the start of the path. // If not, bail early, else remove it before we run the matching. if (prefix) { if (typeof prefix == "string") { if (path.startsWith(prefix)) { path = path.substr(prefix.length) || "/"; } else { return null; } } else if (prefix instanceof RegExp) { const match = path.match(prefix); if (match && match[0]) { path = path.substr(match[0].length) || "/"; } else { return null; } } } // Check if the pattern matches const matches = this._pattern.exec(path); if (matches === null) { return null; } // If the input was a regular expression, this._keys would be false, so return matches as is if (this._keys === false) { return matches; } const out = {}; let i = 0; while (i < this._keys.length) { // In the match parameters, URL-decode all values try { out[this._keys[i]] = decodeURIComponent(matches[i + 1] || "") || null; } catch(e) { out[this._keys[i]] = null; } i++; } return out; } /** * Dictionary with route details passed to the pre-conditions functions, as well as the `routeLoading`, `routeLoaded` and `conditionsFailed` events * @typedef {Object} RouteDetail * @property {string|RegExp} route - Route matched as defined in the route definition (could be a string or a reguar expression object) * @property {string} location - Location path * @property {string} querystring - Querystring from the hash * @property {object} [userData] - Custom data passed by the user * @property {SvelteComponent} [component] - Svelte component (only in `routeLoaded` events) * @property {string} [name] - Name of the Svelte component (only in `routeLoaded` events) */ /** * Executes all conditions (if any) to control whether the route can be shown. Conditions are executed in the order they are defined, and if a condition fails, the following ones aren't executed. * * @param {RouteDetail} detail - Route detail * @returns {boolean} Returns true if all the conditions succeeded */ async checkConditions(detail) { for (let i = 0; i < this.conditions.length; i++) { if (!await this.conditions[i](detail)) { return false; } } return true; } }
JavaScript
class Controller extends PureComponent { state = { isLoading: false, value: '', }; handleChangeValue = ({ value }) => { this.setState({ isLoading: this.props.isLoading, value, }); // Set loading state simulation if (this.props.isLoading) { setTimeout(this.unsetLoading, 1000); } } // Unset loading state simulation unsetLoading = () => { this.setState({ isLoading: false, }); } render () { const { isLoading, value } = this.state; const { isLoading: _omit, ...props } = this.props; return ( <AutoComplete {...props} isLoading={isLoading} onChange={this.handleChangeValue} value={value} /> ); } }
JavaScript
class Tree { /** * Remkate the tree from the root with the options specified * * @param {P5.Vector[]} root * @param {*} options * @memberof Tree */ constructor(root, options) { this.options = options; this.makeTree(root, options); } /** * Remkate the tree from the root with the options specified * * @param {P5.Vector[]} root * @param {*} options * @memberof Tree */ makeTree(root, options) { this.options = options; this.rootBranch = new Branch(root[0], root[1], options); this.branches = []; this.branches[0] = this.rootBranch; for (let i = 1; i < options.tree.maxBranches; i += 1) { for (let j = this.branches.length - 1; j >= 0; j -= 1) { const branch = this.branches[j]; if (!branch.finished) { let left = true; let right = true; if (options.mutate.active) { left = Math.random() <= options.mutate.branch; right = Math.random() <= options.mutate.branch; } if (left) this.branches.push(branch.branch(true)); if (right) this.branches.push(branch.branch(false)); } this.branches[j].finished = true; } } } /** * Draw the current Tree * @param {P5} sketch * @memberof Tree */ draw(sketch) { const { appearance, tree } = this.options; const { maxBranches } = tree; sketch.colorMode(sketch.HSB, maxBranches); const saturation = appearance.saturation * (maxBranches / 360); const brightness = appearance.brightness * (maxBranches / 360); for (let i = 0; i < this.branches.length; i += 1) { const branch = this.branches[i]; branch.draw(sketch, saturation, brightness); if (this.options.appearance.leaves && branch.level === maxBranches - 1) { sketch.stroke(maxBranches, 0, maxBranches, maxBranches); sketch.ellipse(branch.end.x, branch.end.y, 1); } } sketch.colorMode(sketch.RGB, 255); } }
JavaScript
class Button extends Phaser.Button { /** * Button * @param {Phaser.Game} aGame Current game instance. * @param {Number} aX X position of the Button. * @param {Number} aY Y position of the Button. * @param {any} aKey The image key (in the Game.Cache) to use as the texture for this Button. * @param {any} aCallback The function to call when this Button is pressed. * @param {any} aCallbackContext The context in which the callback will be called (usually 'this'). * @param {any} aOverFrame The frame / frameName when the button is in the Over state. * @param {any} aOutFrame The frame / frameName when the button is in the Out state. * @param {any} aDownFrame The frame / frameName when the button is in the Down state. * @param {any} aUpFrame The frame / frameName when the button is in the Up state. */ constructor(aGame, aX, aY, aKey, aCallback, aCallbackContext, aOverFrame, aOutFrame, aDownFrame, aUpFrame) { super( aGame, aX, aY, aKey || 'environments4', aCallback || function() {this.game.state.start("Level")}, aCallbackContext /* || this */, aOverFrame == undefined || aOverFrame == null? null : aOverFrame, aOutFrame == undefined || aOutFrame == null? 'elementStone015' : aOutFrame, aDownFrame == undefined || aDownFrame == null? null : aDownFrame, aUpFrame == undefined || aUpFrame == null? null : aUpFrame ); } }
JavaScript
class DeferredPromise { constructor() { this._promise = new Promise((resolve, reject) => { this.resolve = resolve; this.reject = reject; }); this.then = this._promise.then.bind(this._promise); this.catch = this._promise.catch.bind(this._promise); this[Symbol.toStringTag] = 'Promise'; } }
JavaScript
class Map extends Component { constructor(props) { super(props); this.state = { people: {}, status: "default", activeMode: false, distance: null, isInLocation: false, statusDict: { default: "Set Location", success: <i className="fas fa-camera"></i>, fail: "Not in Location", loading: "Verifying" }, viewport: { width: "100%", height: "100%", latitude: 42.3792848, longitude: -71.1156926, draggable: false, zoom: 15 } }; } checkLocation = e => { e.preventDefault(); let dist; if (!this.props.coords) { dist = 0; } else { dist = this.checkDistance( this.props.coords.latitude, this.props.coords.longitude, this.state.viewport.latitude, this.state.viewport.longitude ); this.props.checkMapLocation( this.props.coords.latitude, this.props.coords.longitude, dist ); } this.setState( { status: "loading", distance: dist }, () => { setTimeout(() => { this.setState({ status: "success" }); }, 2500); } ); }; checkDistance = (userLat, userLong, locationLat, locationLong) => { let distance = 0; if (userLat == locationLat && userLong == locationLong) { distance = 0; } else { var radlat1 = (Math.PI * userLat) / 180; var radlat2 = (Math.PI * locationLat) / 180; var theta = userLong - locationLong; var radtheta = (Math.PI * theta) / 180; var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); if (dist > 1) { dist = 1; } dist = Math.acos(dist); dist = (dist * 180) / Math.PI; dist = dist * 60 * 1.1515; // if (unit=="K") { dist = dist * 1.609344 } // if (unit=="N") { dist = dist * 0.8684 } distance = dist; } return distance; }; uploadContent = () => { this.setState({ activeMode: true }); this.props.uploadContentClick(); }; onViewportChange = viewport => { const { width, height, ...etc } = viewport; this.setState({ viewport: etc }); }; render() { console.log("this is the current status", this.state.status); return ( <div className={ this.state.status == "success" ? "active-mode map-view" : "map-view" } style={{ height: "calc(100% - 50px)", width: "100%" }} > <ReactMapGL className="active-mode" width="100%" height="100%" mapboxApiAccessToken="pk.eyJ1IjoidGlmZmFueW1xIiwiYSI6ImNrMDl3a2p3cjBkZGYzbW55djZ4NDgzMzcifQ.GcKDVp7Hzst2xXfpldKGcg" {...this.state.viewport} onViewportChange={viewport => this.setState({ viewport })} > <Marker draggable={false} latitude={this.state.viewport.latitude} longitude={this.state.viewport.longitude} offsetLeft={-20} offsetTop={-10} > <div className="meeting-point"></div> </Marker> {/* <HeatmapOverlay locations={[42.376700, -71.112420]} {...this.state.viewport}/> */} </ReactMapGL> {this.state.showLoading == true ? ( <div className="loading-div"> <Loading /> </div> ) : null} <Button disabled={this.state.status === "fail" ? true : false} className={ "map-submit-btn " + (this.state.status === "loading" ? " loading-btn " : "") + (this.state.status === "success" ? "success-btn " : "") + (this.state.status === "fail" ? "fail-btn" : "") } onClick={ this.state.status === "success" ? this.uploadContent : this.checkLocation } > {this.state.statusDict[this.state.status]} </Button> </div> ); } }
JavaScript
class InfiniteScrollModule extends Module { /** * @type {number} */ page = 1; /** * @type {string} */ sort = 'new'; /** * @type {string} */ type = 'all'; /** * @type {string} */ q = ''; /** * @type {HTMLElement} * @private */ posts = null; /** * @type {HTMLElement} * @private */ loading = null; /** * Returns whether the module should be enabled by default. Should * return a truthy or falsy value. * * @returns {boolean} */ static isEnabledByDefault = () => { return true; }; /** * Returns the label displayed next to the checkbox on the settings page * * @returns {string} */ getLabel = () => { return 'Infinite Scroll'; }; /** * Returns the help text displayed under the label on the settings page * * @returns {string} */ getHelp = () => { return 'Automatically fetches the next page of post when you reach the bottom of the page.'; }; /** * Called from the content script * * The content script has access to the chrome extension API but does not * have access to the ruqqus `window` object. */ execContentContext = () => { this.onDOMReady(() => { this.posts = document.getElementById('posts'); if (!this.posts) { return; } const pageLinks = document.querySelectorAll('.page-link'); if (!pageLinks || pageLinks.length < 2) { console.error('No page link found.'); return; } const href = pageLinks[1].getAttribute('href'); if (!href) { console.log('End of feed.'); return; } pageLinks[0].style.display = 'none'; pageLinks[1].style.display = 'none'; this.loading = document.createElement('img'); this.loading.setAttribute('src', getLoaderURL()); this.loading.setAttribute('style', 'display: none;'); this.html.insertAfter(pageLinks[1], this.loading); const parsed = queryString.parse(href); this.page = parseInt(parsed.page || 0, 10); this.sort = parsed.sort; this.type = parsed.t; this.q = parsed.q; if (!this.page) { this.page = 2; } const observer = new IntersectionObserver(this.handleIntersect, { rootMargin: '0px', threshold: 1.0 }); const cards = this.posts.querySelectorAll('.card'); observer.observe(cards[cards.length - 1]); }); }; /** * Called from the script injected into the page * * Code run from here has access to the ruqqus `window` object but not the * chrome extension API. */ execWindowContext = () => { this.listen('rp.InfiniteScrollModule.wireupCard', this.handleWireupCard); }; /** * Called when the bottom of the page is reached * * @param {IntersectionObserverEntry[]} entries * @param {IntersectionObserver} observer * @private */ handleIntersect = (entries, observer) => { const entry = entries[0]; if (entry.isIntersecting) { this.loading.style.display = 'block'; fetch(`https://ruqqus.com${document.location.pathname}?sort=${this.sort}&page=${this.page}&t=${this.type}&q=${this.q}`) .then((resp) => resp.text()) .then((text) => { const template = this.html.createElement('template', { 'html': text }); const cards = template.content.querySelectorAll('#posts .card'); if (cards && cards.length > 0) { cards.forEach((card) => { this.posts.appendChild(card); this.dispatch('rp.InfiniteScrollModule.wireupCard', { id: card.getAttribute('id') }); }); this.page += 1; observer.disconnect(); observer.observe(cards[cards.length - 1]); } this.dispatch('rp.change'); }) .finally(() => { this.loading.style.display = 'none'; }); } }; /** * Adds event listeners to new cards. This must be done from the window context to have * access to the window.upvote() and window.downvote() functions. * * @param {CustomEvent} e * @see https://github.com/ruqqus/ruqqus/blob/7477b2d088560f2ac39e723821e8bd7be11087fa/ruqqus/assets/js/all_js.js#L1030 */ handleWireupCard = (e) => { const { upvote, downvote } = window; const card = document.getElementById(e.detail.id); const upvoteButton = card.querySelector('.upvote-button'); const downvoteButton = card.querySelector('.downvote-button'); const image = card.querySelector('.post-img'); upvoteButton.addEventListener('click', upvote, false); upvoteButton.addEventListener('keydown', (event) => { if (event.keyCode === 13) { upvote(event); } }, false); downvoteButton.addEventListener('click', downvote, false); downvoteButton.addEventListener('keydown', (event) => { if (event.keyCode === 13) { downvote(event); } }, false); // createElement used in handleIntersect strips out the inline JS ruqqus included. // We have to add it back for image popups to work. if (image) { const src = image.getAttribute('src'); const possible = ['i.ruqqus.com', 'imgur.com', 'cdn.discordapp.com', 'media.giphy.com']; for (let i = 0; i < possible.length; i++) { if (src.includes(possible[i])) { const a = image.closest('a'); if (a) { const link = a.getAttribute('href'); image.setAttribute( 'onclick', `if (!window.__cfRLUnblockHandlers) return false; expandDesktopImage('${link}','${link}')` ); } } } // createElement also removes the target attribute. const link = image.closest('a'); link.setAttribute('target', '_blank'); } }; }
JavaScript
class d3chart { constructor(selection, data, config, cfg) { this.selection = d3.select(selection); this.data = data; this.cfg = cfg; this._setConfig(config); // Resize listener this.onResize = () => { this.resizeChart(); }; window.addEventListener("resize", this.onResize); this.initChart(); } _setConfig(config) { // Set up configuration Object.keys(config).forEach(key => { if (config[key] instanceof Object && config[key] instanceof Array === false) { Object.keys(config[key]).forEach(sk => { this.cfg[key][sk] = config[key][sk]; }); } else this.cfg[key] = config[key]; }); } /** * Init chart */ initChart() { console.error('d3chart.initChart not implemented'); } /** * Resize chart pipe */ setScales() { console.error('d3chart.setScales not implemented'); } /** * Set chart dimensional sizes */ setChartDimension() { console.error('d3chart.setChartDimension not implemented'); } /** * Bind data to main elements groups */ bindData() { console.error('d3.chart.bindData not implemented'); } /** * Add new chart's elements */ enterElements() { console.error('d3.chart.enterElements not implemented'); } /** * Update chart's elements based on data change */ updateElements() { console.error('d3.chart.updateElements not implemented'); } /** * Remove chart's elements without data */ exitElements() { console.error('d3.chart.exitElements not implemented'); } /** * Set up chart dimensions */ getDimensions() { this.cfg.width = parseInt(this.selection.node().offsetWidth) - this.cfg.margin.left - this.cfg.margin.right; this.cfg.height = parseInt(this.selection.node().offsetHeight) - this.cfg.margin.top - this.cfg.margin.bottom; } /** * Returns chart's data */ getData() { return this.data; } /** * Add new data elements */ enterData(data) { this.data = this.data.concat(data); this.setScales(); this.updateChart(); } /** * Update existing data elements */ updateData(data) { this.data = [...data]; this.setScales(); this.updateChart(); } /** * Compute data before operate */ computeData() {} /** * Remove data elements */ exitData(filter) { this.data.forEach((d, i) => { let c = 0; Object.keys(filter).forEach(key => { if (filter[key] == d[key]) c++; }); if (c == Object.keys(filter).length) { this.data.splice(i, 1); } }); this.setScales(); this.updateChart(); } /** * Init chart commons elements (div > svg > g; tooltip) */ initChartFrame(classname = 'undefined') { // Wrapper div this.wrap = this.selection.append('div').attr("class", "chart__wrap chart__wrap--" + classname); // SVG element this.svg = this.wrap.append('svg').attr("class", "chart chart--" + classname); // General group for margin convention this.g = this.svg.append("g").attr("class", "chart__margin-wrap chart__margin-wrap--" + classname).attr("transform", `translate(${this.cfg.margin.left},${this.cfg.margin.top})`); // Tooltip this.selection.selectAll('.chart__tooltip').remove(); this.tooltip = this.wrap.append('div').attr('class', "chart__tooltip chart__tooltip--" + classname); } /** * Compute element color */ colorElement(d, key = undefined) { key = key ? key : this.cfg.key; // if key is set, return own object color key if (this.cfg.color.key) return d[this.cfg.color.key]; // base color is default one if current key is set, else current one let baseColor = this.cfg.currentKey ? this.cfg.color.default : this.cfg.color.current; // if scheme is set, base color is color scheme if (this.cfg.color.scheme) { baseColor = this.colorScale(d[key]); } // if keys is an object, base color is color key if exists if (this.cfg.color.keys && this.cfg.color.keys instanceof Object && this.cfg.color.keys instanceof Array === false) { if (typeof this.cfg.color.keys[key] == 'string') { baseColor = this.cfg.color.keys[key]; } else if (typeof this.cfg.color.keys[d[key]] == 'string') { baseColor = this.cfg.color.keys[d[key]]; } } // if current key is set and key is current, base color is current if (this.cfg.currentKey && d[this.cfg.key] === this.cfg.currentKey) { baseColor = this.cfg.color.current; } return baseColor; } /** * Update chart methods */ updateChart() { this.computeData(); this.bindData(); this.setScales(); this.enterElements(); this.updateElements(); this.exitElements(); } /** * Resize chart methods */ resizeChart() { this.getDimensions(); //this.setScales(); this.setChartDimension(); this.updateChart(); } /** * Update chart configuration */ updateConfig(config) { this._setConfig(config); this.resizeChart(); } /** * Destroy chart methods */ destroyChart() { window.removeEventListener("resize", this.onResize); } }
JavaScript
class d3barchart extends d3chart { constructor(selection, data, config) { super(selection, data, config, { margin: { top: 10, right: 30, bottom: 20, left: 40 }, key: 'key', currentKey: false, values: [], orientation: 'vertical', labelRotation: 0, color: { key: false, keys: false, scheme: false, current: "#1f77b4", default: "#AAA", axis: "#000" }, axis: { yTitle: false, xTitle: false, yFormat: ".0f", xFormat: ".0f", yTicks: 10, xTicks: 10 }, tooltip: { label: false }, transition: { duration: 350, ease: "easeLinear" } }); } /** * Init chart */ initChart() { // Set up dimensions this.getDimensions(); this.initChartFrame('barchart'); // Set up scales this.xScale = d3$1.scaleBand(); this.xScaleInn = d3$1.scaleBand(); this.yScale = d3$1.scaleLinear(); // Axis group this.axisg = this.g.append('g').attr('class', 'chart__axis chart__axis--barchart'); // Horizontal grid this.yGrid = this.axisg.append("g").attr("class", "chart__grid chart__grid--y chart__grid--barchart"); // Bottom axis this.xAxis = this.axisg.append("g").attr("class", "chart__axis-x chart__axis-x--barchart"); // Vertical axis title if (this.cfg.axis.yTitle) this.yAxisTitle = this.axisg.append('text').attr('class', 'chart__axis-title chart__axis-title--barchart').attr("transform", 'rotate(-90)').style("text-anchor", "middle"); this.setChartDimension(); this.updateChart(); } /** * Resize chart pipe */ setScales() { this.xScale.rangeRound(this.cfg.orientation !== 'horizontal' ? [0, this.cfg.width] : [0, this.cfg.height]).paddingInner(0.1).domain(this.data.map(d => d[this.cfg.key])); this.xScaleInn.domain(this.cfg.values).rangeRound([0, this.xScale.bandwidth()]).paddingInner(0.05); this.yScale.rangeRound(this.cfg.orientation !== 'horizontal' ? [0, this.cfg.height] : [this.cfg.width, 0]).domain([d3$1.max(this.data, d => d3$1.max(this.cfg.values.map(v => d[v]))), 0]); if (this.cfg.color.scheme instanceof Array === true) { this.colorScale = d3$1.scaleOrdinal().range(this.cfg.color.scheme); } else if (typeof this.cfg.color.scheme === 'string') { this.colorScale = d3$1.scaleOrdinal(d3$1[this.cfg.color.scheme]); } const yGridFunction = this.cfg.orientation !== 'horizontal' ? d3$1.axisLeft(this.yScale).tickSize(-this.cfg.width).ticks(this.cfg.axis.yTicks, this.cfg.axis.yFormat) : d3$1.axisBottom(this.yScale).tickSize(-this.cfg.height).ticks(this.cfg.axis.yTicks, this.cfg.axis.yFormat); const xAxisFunction = this.cfg.orientation !== 'horizontal' ? d3$1.axisBottom(this.xScale) : d3$1.axisLeft(this.xScale); // Horizontal grid this.yGrid.attr("transform", this.cfg.orientation !== 'horizontal' ? 'translate(0,0)' : `translate(0,${this.cfg.height})`).transition(this.transition).call(yGridFunction); // Bottom axis this.xAxis.attr("transform", this.cfg.orientation !== 'horizontal' ? `translate(0,${this.cfg.height})` : 'translate(0,0)').call(xAxisFunction); } /** * Set chart dimensional sizes */ setChartDimension() { // SVG element this.svg.attr("viewBox", `0 0 ${this.cfg.width + this.cfg.margin.left + this.cfg.margin.right} ${this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom}`).attr("width", this.cfg.width + this.cfg.margin.left + this.cfg.margin.right).attr("height", this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom); // Vertical axis title if (this.cfg.axis.yTitle) this.yAxisTitle.attr("y", -this.cfg.margin.left + 10).attr("x", -this.cfg.height / 2).text(this.cfg.axis.yTitle); // Bottom axis label rotation if (this.cfg.labelRotation !== 0) this.xAxis.selectAll('text').attr("y", Math.cos(this.cfg.labelRotation * Math.PI / 180) * 9).attr("x", Math.sin(this.cfg.labelRotation * Math.PI / 180) * 9).attr("dy", ".35em").attr("transform", `rotate(${this.cfg.labelRotation})`).style("text-anchor", "start"); } /** * Bind data to main elements groups */ bindData() { // Set transition this.transition = d3$1.transition('t').duration(this.cfg.transition.duration).ease(d3$1[this.cfg.transition.ease]); // Bars groups this.itemg = this.g.selectAll('.chart__bar-group').data(this.data, d => d[this.cfg.key]); } /** * Add new chart's elements */ enterElements() { const newbars = this.itemg.enter().append('g').attr('class', 'chart__bar-group chart__bar-group--barchart').attr('transform', d => { if (this.cfg.orientation !== 'horizontal') { return `translate(${this.xScale(d[this.cfg.key])},0)`; } return `translate(0,${this.xScale(d[this.cfg.key])})`; }); const rects = newbars.selectAll('.chart__bar').data(d => this.cfg.values.map(v => { const dat = { ...d }; dat[this.cfg.key] = d[this.cfg.key]; return dat; })).enter().append('rect').attr('class', 'chart__bar chart__bar--barchart').classed('chart__bar--current', d => { return this.cfg.currentKey && d[this.cfg.key] === this.cfg.currentKey; }).attr('x', (d, i) => { return this.cfg.orientation !== 'horizontal' ? this.xScaleInn(this.cfg.values[i % this.cfg.values.length]) : 0; }).attr('y', (d, i) => { return this.cfg.orientation !== 'horizontal' ? this.cfg.height : this.xScaleInn(this.cfg.values[i % this.cfg.values.length]); }).attr('height', 0).attr('width', 0).on('mouseover', (d, i) => { const key = this.cfg.values[i % this.cfg.values.length]; this.tooltip.html(() => { return `<div>${key}: ${d[key]}</div>`; }).classed('active', true); }).on('mouseout', () => { this.tooltip.classed('active', false); }).on('mousemove', () => { this.tooltip.style('left', window.event['pageX'] - 28 + 'px').style('top', window.event['pageY'] - 40 + 'px'); }); } /** * Update chart's elements based on data change */ updateElements() { // Bars groups this.itemg.transition(this.transition).attr('transform', d => { return this.cfg.orientation !== 'horizontal' ? `translate(${this.xScale(d[this.cfg.key])},0)` : `translate(0,${this.xScale(d[this.cfg.key])})`; }); // Bars this.g.selectAll('.chart__bar').transition(this.transition).attr('fill', (d, i) => this.colorElement(d, this.cfg.values[i % this.cfg.values.length])).attr('x', (d, i) => { return this.cfg.orientation !== 'horizontal' ? this.xScaleInn(this.cfg.values[i % this.cfg.values.length]) : 0; }).attr('y', (d, i) => { return this.cfg.orientation !== 'horizontal' ? this.yScale(+d[this.cfg.values[i % this.cfg.values.length]]) : this.xScaleInn(this.cfg.values[i % this.cfg.values.length]); }).attr('width', (d, i) => { return this.cfg.orientation !== 'horizontal' ? this.xScaleInn.bandwidth() : this.yScale(+d[this.cfg.values[i % this.cfg.values.length]]); }).attr('height', (d, i) => { return this.cfg.orientation !== 'horizontal' ? this.cfg.height - this.yScale(+d[this.cfg.values[i % this.cfg.values.length]]) : this.xScaleInn.bandwidth(); }); } /** * Remove chart's elements without data */ exitElements() { this.itemg.exit().transition(this.transition).style("opacity", 0).remove(); } }
JavaScript
class d3linechart extends d3chart { constructor(selection, data, config) { super(selection, data, config, { margin: { top: 20, right: 20, bottom: 20, left: 40 }, values: [], date: { key: false, inputFormat: "%Y-%m-%d", outputFormat: "%Y-%m-%d" }, color: { key: false, keys: false, scheme: false, current: '#1f77b4', default: '#AAA', axis: '#000' }, curve: 'curveLinear', points: { visibleSize: 3, hoverSize: 6 }, axis: { yTitle: false, xTitle: false, yFormat: ".0f", xFormat: "%Y-%m-%d", yTicks: 5, xTicks: 3 }, tooltip: { labels: false }, transition: { duration: 350, ease: 'easeLinear' } }); } /** * Init chart */ initChart() { // Set up dimensions this.getDimensions(); this.initChartFrame('linechart'); // Format date functions this.parseTime = d3$2.timeParse(this.cfg.date.inputFormat); this.formatTime = d3$2.timeFormat(this.cfg.date.outputFormat); // Init scales this.yScale = d3$2.scaleLinear(); this.xScale = d3$2.scaleTime(); this.line = d3$2.line(); // Axis group this.axisg = this.g.append('g').attr('class', 'chart__axis chart__axis--linechart'); // Horizontal grid this.yGrid = this.axisg.append("g").attr("class", "chart__grid chart__grid--y chart__grid--linechart"); // Bottom axis this.xAxis = this.axisg.append("g").attr("class", "chart__axis-x chart__axis-x--linechart"); // Vertical axis this.yAxis = this.axisg.append("g").attr("class", "chart__axis-y chart__axis-y--linechart chart__grid"); // Vertical axis title if (this.cfg.axis.yTitle) this.yAxisTitle = this.axisg.append('text').attr('class', 'chart__axis-title chart__axis-title--linechart').attr("transform", 'rotate(-90)').style("text-anchor", "middle"); this.setChartDimension(); this.updateChart(); } /** * Calcule required derivated data */ computeData() { // Calcule transpose data const tData = []; this.cfg.values.forEach((j, i) => { tData[i] = {}; tData[i].key = j; tData[i].values = []; }); this.data.forEach(d => { d.jsdate = this.parseTime(d[this.cfg.date.key]); }); this.data.sort((a, b) => a.jsdate - b.jsdate); this.data.forEach((d, c) => { d.min = 9999999999999999999; d.max = -9999999999999999999; this.cfg.values.forEach((j, i) => { tData[i].values.push({ x: d.jsdate, y: +d[j], k: i }); if (d[j] < d.min) d.min = +d[j]; if (d[j] > d.max) d.max = +d[j]; }); }); this.tData = tData; } /** * Set up chart dimensions (non depending on data) */ setChartDimension() { // Resize SVG element this.svg.attr("viewBox", `0 0 ${this.cfg.width + this.cfg.margin.left + this.cfg.margin.right} ${this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom}`).attr("width", this.cfg.width + this.cfg.margin.left + this.cfg.margin.right).attr("height", this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom); // Vertical axis title if (this.cfg.axis.yTitle) this.yAxisTitle.attr("y", -this.cfg.margin.left + 10).attr("x", -this.cfg.height / 2).text(this.cfg.axis.yTitle); } /** * Set up scales */ setScales() { // Calcule vertical scale this.yScale.domain([0, d3$2.max(this.data, d => d.max)]).rangeRound([this.cfg.height, 0]); // Calcule horizontal scale this.xScale.domain(d3$2.extent(this.data, d => d.jsdate)).rangeRound([0, this.cfg.width]); if (this.cfg.color.scheme instanceof Array === true) { this.colorScale = d3$2.scaleOrdinal().range(this.cfg.color.scheme); } else if (typeof this.cfg.color.scheme === 'string') { this.colorScale = d3$2.scaleOrdinal(d3$2[this.cfg.color.scheme]); } // Set up line function this.line.x(d => this.xScale(d.x)).y(d => this.yScale(d.y)).curve(d3$2[this.cfg.curve]); // Redraw grid this.yGrid.call(d3$2.axisLeft(this.yScale).tickSize(-this.cfg.width).ticks(this.cfg.axis.yTicks, this.cfg.axis.yFormat)); // Redraw horizontal axis this.xAxis.attr("transform", `translate(0,${this.cfg.height})`).call(d3$2.axisBottom(this.xScale).tickFormat(this.formatTime).ticks(this.cfg.axis.xTicks, this.cfg.axis.xFormat)); } /** * Bind data to main elements groups */ bindData() { // Set transition this.transition = d3$2.transition('t').duration(this.cfg.transition.duration).ease(d3$2[this.cfg.transition.ease]); // Lines group this.linesgroup = this.g.selectAll(".chart__lines-group").data(this.tData, d => d.key); // Don't continue if points are disabled if (this.cfg.points === false) return; // Set points store if (!this.pointsg || this.pointsg instanceof Array === false) { this.pointsg = []; } } /** * Add new chart's elements */ enterElements() { // Elements to add const newgroups = this.linesgroup.enter().append('g').attr("class", "chart__lines-group chart__lines-group--linechart"); // Lines newgroups.append('path').attr("class", "chart__line chart__line--linechart").attr('fill', 'transparent').attr("d", d => this.line(d.values.map(v => ({ y: 0, x: v.x, k: v.k })))); // Don't continue if points are disabled if (this.cfg.points === false) return; this.cfg.values.forEach((k, i) => { // Point group let gp = this.g.selectAll('.chart__points-group--' + k).data(this.data).enter().append('g').attr('class', 'chart__points-group chart__points-group--linechart chart__points-group--' + k).attr('transform', d => `translate(${this.xScale(d.jsdate)},${this.cfg.height})`); // Hover point gp.append('circle').attr('class', 'chart__point-hover chart__point-hover--linechart').attr('fill', 'transparent').attr('r', this.cfg.points.hoverSize).on('mouseover', (d, j) => { this.tooltip.html(_ => { const label = this.cfg.tooltip.labels && this.cfg.tooltip.labels[i] ? this.cfg.tooltip.labels[i] : k; return ` <div>${label}: ${this.tData[i].values[j].y}</div> `; }).classed('active', true); }).on('mouseout', _ => { this.tooltip.classed('active', false); }).on('mousemove', _ => { this.tooltip.style('left', window.event['pageX'] - 28 + 'px').style('top', window.event['pageY'] - 40 + 'px'); }); // Visible point gp.append('circle').attr('class', 'chart__point-visible chart__point-visible--linechart').attr('pointer-events', 'none'); this.pointsg.push({ selection: gp, key: k }); }); } /** * Update chart's elements based on data change */ updateElements() { // Color lines this.linesgroup.attr('stroke', d => this.colorElement(d, 'key')); // Redraw lines this.g.selectAll('.chart__line').attr('stroke', d => this.colorElement(d, 'key')).transition(this.transition).attr("d", (d, i) => this.line(this.tData[i].values)); // Don't continue if points are disabled if (this.cfg.points === false) return; // Redraw points this.pointsg.forEach((p, i) => { p.selection.transition(this.transition).attr('transform', d => `translate(${this.xScale(d.jsdate)},${this.yScale(d[p.key])})`); // Visible point p.selection.selectAll('.chart__point-visible').attr('fill', d => this.colorElement(p, 'key')).attr('r', this.cfg.points.visibleSize); // Hover point p.selection.selectAll('.chart__point-hover').attr('r', this.cfg.points.hoverSize); }); } /** * Remove chart's elements without data */ exitElements() { this.linesgroup.exit().transition(this.transition).style("opacity", 0).remove(); } }
JavaScript
class d3piechart extends d3chart { constructor(selection, data, config) { super(selection, data, config, { margin: { top: 40, right: 20, bottom: 40, left: 20 }, key: '', value: 'value', color: { key: false, keys: false, scheme: false, current: '#1f77b4', default: '#AAA', axis: '#000' }, radius: { inner: false, outter: false, padding: 0, round: 0 }, transition: { duration: 350, ease: 'easeLinear' } }); } /** * Init chart */ initChart() { // Set up dimensions this.getDimensions(); this.initChartFrame('piechart'); this.cScale = d3$3.scaleOrdinal(); this.arc = d3$3.arc(); this.outerArc = d3$3.arc(); this.pie = d3$3.pie().sort(null).value(d => d[this.cfg.value]).padAngle(this.cfg.radius.padding); if (this.cfg.radius && this.cfg.radius.inner) { const outRadius = this.cfg.radius.outter ? this.cfg.radius.outter : Math.min(this.cfg.width, this.cfg.height) / 2; this.cfg.radius.relation = this.cfg.radius.inner ? this.cfg.radius.inner / outRadius : 0; } this.gcenter = this.g.append('g'); this.setChartDimension(); this.updateChart(); } /** * Set up chart dimensions (non depending on data) */ setChartDimension() { // SVG element this.svg.attr("viewBox", `0 0 ${this.cfg.width + this.cfg.margin.left + this.cfg.margin.right} ${this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom}`).attr("width", this.cfg.width + this.cfg.margin.left + this.cfg.margin.right).attr("height", this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom); // Center element this.gcenter.attr('transform', `translate(${this.cfg.width / 2}, ${this.cfg.height / 2})`); } /** * Bind data to main elements groups */ bindData() { this.itemg = this.gcenter.selectAll('.chart__slice-group').data(this.pie(this.data), d => d.data[this.cfg.key]); // Set transition this.transition = d3$3.transition('t').duration(this.cfg.transition.duration).ease(d3$3[this.cfg.transition.ease]); } /** * Set up scales */ setScales() { // Set up radius this.cfg.radius.outter = this.cfg.radius && this.cfg.radius.outter ? this.cfg.radius.outter : Math.min(this.cfg.width, this.cfg.height) / 2; let inRadius = this.cfg.radius && this.cfg.radius.inner ? this.cfg.radius.inner : 0; if (this.cfg.radius.relation) { inRadius = this.cfg.radius.outter * this.cfg.radius.relation; } // Set up arcs this.arc = d3$3.arc().outerRadius(this.cfg.radius.outter).innerRadius(inRadius).cornerRadius(this.cfg.radius.round); this.outerArc = d3$3.arc().outerRadius(this.cfg.radius.outter * 1.1).innerRadius(this.cfg.radius.outter * 1.1); // Set up color scheme if (this.cfg.color.scheme) { if (this.cfg.color.scheme instanceof Array === true) { this.colorScale = d3$3.scaleOrdinal().domain(this.data.map(d => d[this.cfg.key])).range(this.cfg.color.scheme); } else { this.colorScale = d3$3.scaleOrdinal(d3$3[this.cfg.color.scheme]).domain(this.data.map(d => d[this.cfg.key])); } } } /** * Add new chart's elements */ enterElements() { const newg = this.itemg.enter().append('g').attr("class", "chart__slice-group chart__slice-group--piechart"); // PATHS newg.append("path").attr("class", "chart__slice chart__slice--piechart").transition(this.transition).delay((d, i) => i * this.cfg.transition.duration).attrTween('d', d => { const i = d3$3.interpolate(d.startAngle + 0.1, d.endAngle); return t => { d.endAngle = i(t); return this.arc(d); }; }).style("fill", d => this.colorElement(d.data)).style('opacity', 1); // LABELS newg.append('text').attr("class", "chart__label chart__label--piechart").style('opacity', 0).attr("transform", d => { let pos = this.outerArc.centroid(d); pos[0] = this.cfg.radius.outter * (this.midAngle(d) < Math.PI ? 1.1 : -1.1); return "translate(" + pos + ")"; }).attr('text-anchor', d => this.midAngle(d) < Math.PI ? 'start' : 'end').text(d => d.data[this.cfg.key]).transition(this.transition).delay((d, i) => i * this.cfg.transition.duration).style('opacity', 1); // LINES newg.append('polyline').attr("class", "chart__line chart__line--piechart").style('opacity', 0).attr('points', d => { let pos = this.outerArc.centroid(d); pos[0] = this.cfg.radius.outter * 0.95 * (this.midAngle(d) < Math.PI ? 1.1 : -1.1); return [this.arc.centroid(d), this.outerArc.centroid(d), pos]; }).transition(this.transition).delay((d, i) => i * this.cfg.transition.duration).style('opacity', 1); } /** * Update chart's elements based on data change */ updateElements() { // PATHS this.itemg.selectAll(".chart__slice").style('opacity', 0).data(this.pie(this.data), d => d.data[this.cfg.key]).transition(this.transition).delay((d, i) => i * this.cfg.transition.duration).attrTween('d', d => { const i = d3$3.interpolate(d.startAngle + 0.1, d.endAngle); return t => { d.endAngle = i(t); return this.arc(d); }; }).style("fill", d => this.colorElement(d.data)).style('opacity', 1); // LABELS this.itemg.selectAll(".chart__label").data(this.pie(this.data), d => d.data[this.cfg.key]).text(d => d.data[this.cfg.key]).transition(this.transition).attr("transform", d => { let pos = this.outerArc.centroid(d); pos[0] = this.cfg.radius.outter * (this.midAngle(d) < Math.PI ? 1.1 : -1.1); return "translate(" + pos + ")"; }).attr('text-anchor', d => this.midAngle(d) < Math.PI ? 'start' : 'end'); // LINES this.itemg.selectAll(".chart__line").data(this.pie(this.data), d => d.data[this.cfg.key]).transition(this.transition).attr('points', d => { let pos = this.outerArc.centroid(d); pos[0] = this.cfg.radius.outter * 0.95 * (this.midAngle(d) < Math.PI ? 1.1 : -1.1); return [this.arc.centroid(d), this.outerArc.centroid(d), pos]; }); } /** * Remove chart's elements without data */ exitElements() { this.itemg.exit().transition(this.transition).style("opacity", 0).remove(); } midAngle(d) { return d.startAngle + (d.endAngle - d.startAngle) / 2; } /** * Store the displayed angles in _current. * Then, interpolate from _current to the new angles. * During the transition, _current is updated in-place by d3.interpolate. */ arcTween(a) { var i = d3$3.interpolate(this._current, a); this._current = i(0); return t => this.arc(i(t)); } }
JavaScript
class d3slopechart extends d3chart { constructor(selection, data, config) { super(selection, data, config, { margin: { top: 10, right: 100, bottom: 20, left: 100 }, key: '', currentKey: false, values: ['start', 'end'], color: { key: false, keys: false, scheme: false, current: '#1f77b4', default: '#AAA', axis: '#000' }, axis: { titles: false }, points: { visibleRadius: 3 }, opacity: 0.5, transition: { duration: 350, ease: 'easeLinear' } }); } /** * Init chart */ initChart() { // Set up dimensions this.getDimensions(); this.initChartFrame('slopechart'); // Set up scales this.yScale = d3$4.scaleLinear(); // Axis group const axisg = this.g.append('g').attr('class', 'chart__axis chart__axis--slopechart'); // Vertical left axis this.startAxis = axisg.append('line').attr("class", "chart__axis-y chart__axis-y--slopechart chart__axis-y--start").attr('x1', 0).attr('x2', 0).attr('y1', 0).attr('stroke', this.cfg.color.axis); // Vertical right axis this.endAxis = axisg.append('line').attr("class", "chart__axis-y chart__axis-y--slopechart chart__axis-y--end").attr('y1', 0).attr('stroke', this.cfg.color.axis); // Axis labels if (this.cfg.axis.titles) { this.startl = axisg.append('text').attr('class', 'chart__axis-text chart__axis-text--slopechart chart__axis-text--start').attr('text-anchor', 'middle').attr('y', this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom - 12).text(this.cfg.axis.titles[0]); this.endl = axisg.append('text').attr('class', 'chart__axis-text chart__axis-text--slopechart chart__axis-text--end').attr('text-anchor', 'middle').attr('y', this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom - 12).text(this.cfg.axis.titles[1]); } this.setChartDimension(); this.updateChart(); } /** * Set up chart dimensions (non depending on data) */ setChartDimension() { // SVG element this.svg.attr("viewBox", `0 0 ${this.cfg.width + this.cfg.margin.left + this.cfg.margin.right} ${this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom}`).attr("width", this.cfg.width + this.cfg.margin.left + this.cfg.margin.right).attr("height", this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom); // Vertical left axis position this.startAxis.attr('y2', this.cfg.height); // Vertical right axis position this.endAxis.attr('x1', this.cfg.width).attr('x2', this.cfg.width).attr('y2', this.cfg.height); // Axis labels if (this.cfg.axis.titles) { this.startl.attr('y', this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom - 12); this.endl.attr('x', this.cfg.width).attr('y', this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom - 12); } } /** * Set up scales */ setScales() { // Set up dimensional scales this.yScale.rangeRound([this.cfg.height, 0]).domain([d3$4.min(this.data, d => d[this.cfg.values[0]] < d[this.cfg.values[1]] ? d[this.cfg.values[0]] * 0.9 : d[this.cfg.values[1]] * 0.9), d3$4.max(this.data, d => d[this.cfg.values[0]] > d[this.cfg.values[1]] ? d[this.cfg.values[0]] * 1.1 : d[this.cfg.values[1]] * 1.1)]); // Set up color scheme if (this.cfg.color.scheme) { if (this.cfg.color.scheme instanceof Array === true) { this.colorScale = d3$4.scaleOrdinal().domain(this.data.map(d => d[this.cfg.key])).range(this.cfg.color.scheme); } else { this.colorScale = d3$4.scaleOrdinal(d3$4[this.cfg.color.scheme]).domain(this.data.map(d => d[this.cfg.key])); } } } /** * Bind data to main elements groups */ bindData() { // Lines group selection data this.linesgroup = this.g.selectAll(".chart__lines-group").data(this.data, d => d[this.cfg.key]); // Set transition this.transition = d3$4.transition('t').duration(this.cfg.transition.duration).ease(d3$4[this.cfg.transition.ease]); } /** * Add new chart's elements */ enterElements() { // Elements to add const newlines = this.linesgroup.enter().append('g').attr("class", "chart__lines-group chart__lines-group--slopechart"); // Lines to add newlines.append('line').attr("class", "chart__line chart__line--slopechart").classed('chart__line--current', d => this.cfg.currentKey && d[this.cfg.key] == this.cfg.currentKey).attr('stroke', d => this.colorElement(d)).style("opacity", this.cfg.opacity).attr("x1", 0).attr("x2", this.cfg.width).transition(this.transition).attr("y1", d => this.yScale(d[this.cfg.values[0]])).attr("y2", d => this.yScale(d[this.cfg.values[1]])); // Vertical left axis points group to add const gstart = newlines.append('g').attr('class', 'chart__points-group chart__points-group--slopechart chart__points-group--start'); gstart.transition(this.transition).attr('transform', d => 'translate(0,' + this.yScale(d[this.cfg.values[0]]) + ')'); // Vertical left axis points to add gstart.append('circle').attr('class', 'chart__point chart__point--slopechart chart__point--start').attr('fill', d => this.colorElement(d)).attr('r', this.cfg.points.visibleRadius); // Vertical left axis label to add gstart.append('text').attr('class', 'chart__label chart__label--slopechart chart__label--start').attr('text-anchor', 'end').attr('y', 3).attr('x', -5).text(d => d[this.cfg.key] + ' ' + d[this.cfg.values[0]]); // Vertical right axis points group to add const gend = newlines.append('g').attr('class', 'chart__points-group chart__points-group--slopechart chart__points-group--end').attr('transform', 'translate(' + this.cfg.width + ',0)'); gend.transition(this.transition).attr('transform', d => 'translate(' + this.cfg.width + ',' + this.yScale(d[this.cfg.values[1]]) + ')'); // Vertical right axis points to add gend.append('circle').attr('class', 'chart__point chart__point--slopechart chart__point--end').attr('fill', d => this.colorElement(d)).attr('r', this.cfg.points.visibleRadius); // Vertical right axis label to add gend.append('text').attr('class', 'chart__label chart__label--slopechart chart__label--end').attr('text-anchor', 'start').attr('y', 3).attr('x', 5).text(d => d[this.cfg.values[1]] + ' ' + d[this.cfg.key]); } /** * Update chart's elements based on data change */ updateElements() { // Lines to modify this.linesgroup.selectAll('.chart__line').data(this.data, d => d[this.cfg.key]).transition(this.transition).attr("x1", 0).attr("x2", this.cfg.width).attr("y1", d => this.yScale(d[this.cfg.values[0]])).attr("y2", d => this.yScale(d[this.cfg.values[1]])); // Left axis points to modify this.linesgroup.selectAll('.chart__points-group--start').data(this.data, d => d[this.cfg.key]).transition(this.transition).attr('transform', d => 'translate(0,' + this.yScale(d[this.cfg.values[0]]) + ')'); // Left axis labels to modify this.linesgroup.selectAll('.chart__label--start').data(this.data, d => d[this.cfg.key]).text(d => { return d[this.cfg.key] + ' ' + d[this.cfg.values[0]]; }); // Right axis points to modify this.linesgroup.selectAll('.chart__points-group--end').data(this.data, d => d[this.cfg.key]).transition(this.transition).attr('transform', d => 'translate(' + this.cfg.width + ',' + this.yScale(d[this.cfg.values[1]]) + ')'); // Right axis labels to modify this.linesgroup.selectAll('.chart__label--end').data(this.data, d => d[this.cfg.key]).text(d => d[this.cfg.values[1]] + ' ' + d[this.cfg.key]); } /** * Remove chart's elements without data */ exitElements() { this.linesgroup.exit().transition(this.transition).style("opacity", 0).remove(); } }
JavaScript
class d3wordscloud extends d3chart { constructor(selection, data, config) { super(selection, data, config, { margin: { top: 20, right: 20, bottom: 20, left: 20 }, key: 'word', value: 'size', fontFamily: 'Arial', angle: { steps: 2, start: 0, end: 90 }, color: { key: false, keys: false, scheme: false, current: '#1f77b4', default: '#AAA', axis: '#000' }, transition: { duration: 350, ease: 'easeLinear' } }); } /** * Init chart */ initChart() { // Set up dimensions this.getDimensions(); this.initChartFrame('wordscloud'); this.gcenter = this.g.append('g'); this.setChartDimension(); this.updateChart(); } /** * Compute data before operate */ computeData() { let layout = d3$6.cloud().size([this.cfg.width, this.cfg.height]).words(this.data.map(d => ({ text: d[this.cfg.key], size: d[this.cfg.value] }))).rotate(() => this.wordsAngle(this.cfg.angle)).font(this.cfg.fontFamily).fontSize(d => d.size).on("end", d => { this.tData = d; }).start(); } /** * Set up chart dimensions (non depending on data) */ setChartDimension() { // Resize SVG element this.svg.attr("viewBox", `0 0 ${this.cfg.width + this.cfg.margin.left + this.cfg.margin.right} ${this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom}`).attr("width", this.cfg.width + this.cfg.margin.left + this.cfg.margin.right).attr("height", this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom); // Center element this.gcenter.attr('transform', `translate(${this.cfg.width / 2}, ${this.cfg.height / 2})`); } /** * Bind data to main elements groups */ bindData() { // Set transition this.transition = d3$6.transition('t').duration(this.cfg.transition.duration).ease(d3$6[this.cfg.transition.ease]); // Word group selection data this.wordgroup = this.gcenter.selectAll(".chart__word-group").data(this.tData, d => d.text); } /** * Set up scales */ setScales() { if (this.cfg.color.scheme instanceof Array === true) { this.colorScale = d3$6.scaleOrdinal().range(this.cfg.color.scheme); } else if (typeof this.cfg.color.scheme === 'string') { this.colorScale = d3$6.scaleOrdinal(d3$6[this.cfg.color.scheme]); } } /** * Add new chart's elements */ enterElements() { // Elements to add const newwords = this.wordgroup.enter().append('g').attr("class", "chart__word-group chart__word-group--wordscloud"); newwords.append("text").style("font-size", d => d.size + "px").style("font-family", d => d.font).attr("text-anchor", "middle").attr('fill', d => this.colorElement(d, 'text')).attr("transform", d => `translate(${[d.x, d.y]})rotate(${d.rotate})`).text(d => d.text); } /** * Update chart's elements based on data change */ updateElements() { this.wordgroup.selectAll('text').data(this.tData, d => d.text).transition(this.transition).attr('fill', d => this.colorElement(d, 'text')).style("font-size", d => d.size + "px").attr("transform", d => `translate(${[d.x, d.y]})rotate(${d.rotate})`); } /** * Remove chart's elements without data */ exitElements() { this.wordgroup.exit().transition(this.transition).style("opacity", 0).remove(); } /** * Word's angle */ wordsAngle(angle) { if (typeof this.cfg.angle === 'number') { // Config angle is fixed number return this.cfg.angle; } else if (typeof this.cfg.angle === 'object') { if (this.cfg.angle instanceof Array === true) { // Config angle is custom array const idx = this.randomInt(0, this.cfg.angle.length - 1); return this.cfg.angle[idx]; } else { // Config angle is custom object const angle = (this.cfg.angle.end - this.cfg.angle.start) / (this.cfg.angle.steps - 1); return this.cfg.angle.start + this.randomInt(0, this.cfg.angle.steps) * angle; } } return 0; } randomInt(min, max) { const i = Math.ceil(min); const j = Math.floor(max); return Math.floor(Math.random() * (j - i + 1)) + i; } }
JavaScript
class d3sliceschart extends d3chart { constructor(selection, data, config) { super(selection, data, config, { margin: { top: 40, right: 20, bottom: 40, left: 20 }, key: '', value: 'value', color: { key: false, keys: false, scheme: false, current: '#1f77b4', default: '#AAA', axis: '#000' }, radius: { inner: false, outter: false, padding: 0, round: 0 }, transition: { duration: 350, ease: 'easeLinear' } }); } /** * Init chart */ initChart() { // Set up dimensions this.getDimensions(); this.initChartFrame('sliceschart'); this.cScale = d3$7.scaleOrdinal(); this.rScale = d3$7.scaleLinear(); this.arc = d3$7.arc(); this.pie = d3$7.pie().sort(null).value(() => 1).padAngle(this.cfg.radius.padding); if (this.cfg.radius && this.cfg.radius.inner) { const outRadius = this.cfg.radius.outter ? this.cfg.radius.outter : Math.min(this.cfg.width, this.cfg.height) / 2; this.cfg.radius.relation = this.cfg.radius.inner ? this.cfg.radius.inner / outRadius : 0; } this.gcenter = this.g.append('g'); this.setChartDimension(); this.updateChart(); } /** * Set up chart dimensions (non depending on data) */ setChartDimension() { // SVG element this.svg.attr("viewBox", `0 0 ${this.cfg.width + this.cfg.margin.left + this.cfg.margin.right} ${this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom}`).attr("width", this.cfg.width + this.cfg.margin.left + this.cfg.margin.right).attr("height", this.cfg.height + this.cfg.margin.top + this.cfg.margin.bottom); // Center element this.gcenter.attr('transform', `translate(${this.cfg.width / 2}, ${this.cfg.height / 2})`); } /** * Bind data to main elements groups */ bindData() { this.itemg = this.gcenter.selectAll('.chart__slice-group').data(this.pie(this.data), d => d.data[this.cfg.key]); // Set transition this.transition = d3$7.transition('t').duration(this.cfg.transition.duration).ease(d3$7[this.cfg.transition.ease]); } /** * Set up scales */ setScales() { // Set up radius this.cfg.radius.outter = this.cfg.radius && this.cfg.radius.outter ? this.cfg.radius.outter : Math.min(this.cfg.width, this.cfg.height) / 2; this.inRadius = this.cfg.radius && this.cfg.radius.inner ? this.cfg.radius.inner : 0; if (this.cfg.radius.relation) { this.inRadius = this.cfg.radius.outter * this.cfg.radius.relation; } // Set up arcs this.arc = d3$7.arc().outerRadius(this.cfg.radius.outter).innerRadius(this.inRadius).cornerRadius(this.cfg.radius.round); this.rScale.range([this.inRadius, this.cfg.radius.outter]).domain([0, d3$7.max(this.data, d => d[this.cfg.value])]); // Set up color scheme if (this.cfg.color.scheme) { if (this.cfg.color.scheme instanceof Array === true) { this.colorScale = d3$7.scaleOrdinal().domain(this.data.map(d => d[this.cfg.key])).range(this.cfg.color.scheme); } else { this.colorScale = d3$7.scaleOrdinal(d3$7[this.cfg.color.scheme]).domain(this.data.map(d => d[this.cfg.key])); } } } /** * Add new chart's elements */ enterElements() { const newg = this.itemg.enter().append('g').attr("class", "chart__slice-group chart__slice-group--sliceschart"); // BACKGROUNDS newg.append("path").attr("class", "chart__slice chart__slice--sliceschart").on('mouseover', (d, i) => { const key = d.data[this.cfg.key]; const value = d.data[this.cfg.value]; this.tooltip.html(() => { return `<div>${key}: ${value}</div>`; }).classed('active', true); }).on('mouseout', () => { this.tooltip.classed('active', false); }).on('mousemove', () => { this.tooltip.style('left', window.event['pageX'] - 28 + 'px').style('top', window.event['pageY'] - 40 + 'px'); }).transition(this.transition).delay((d, i) => i * this.cfg.transition.duration).attrTween('d', d => { const i = d3$7.interpolate(d.startAngle + 0.1, d.endAngle); return t => { d.endAngle = i(t); return this.arc(d); }; }).style("fill", d => this.cfg.color.default).style('opacity', 1); // FILLS newg.append("path").attr("class", "chart__slice chart__slice--sliceschart").transition(this.transition).delay((d, i) => i * this.cfg.transition.duration).attrTween('d', d => { const i = d3$7.interpolate(d.startAngle + 0.1, d.endAngle); const arc = d3$7.arc().outerRadius(this.rScale(d.data[this.cfg.value])).innerRadius(this.inRadius).cornerRadius(this.cfg.radius.round); return t => { d.endAngle = i(t); return arc(d); }; }).style("fill", d => this.colorElement(d.data)).style('pointer-events', 'none').style('opacity', 1); } /** * Update chart's elements based on data change */ updateElements() {} /* // PATHS this.itemg.selectAll(".chart__slice") .style('opacity', 0) .data(this.pie(this.data), d => d.data[this.cfg.key]) .transition(this.transition) .delay((d,i) => i * this.cfg.transition.duration) .attrTween('d', d => { const i = d3.interpolate(d.startAngle+0.1, d.endAngle); return t => { d.endAngle = i(t); return this.arc(d) } }) .style("fill", this.cfg.color.default) .style('opacity', 1); */ /** * Remove chart's elements without data */ exitElements() { this.itemg.exit().transition(this.transition).style("opacity", 0).remove(); } midAngle(d) { return d.startAngle + (d.endAngle - d.startAngle) / 2; } /** * Store the displayed angles in _current. * Then, interpolate from _current to the new angles. * During the transition, _current is updated in-place by d3.interpolate. */ arcTween(a) { var i = d3$7.interpolate(this._current, a); this._current = i(0); return t => this.arc(i(t)); } }
JavaScript
class Connector { /** * @param {BaseAudioContext} context */ constructor(context) { const gain = context.createGain() this.input = gain this.output = gain } /** * Connect the output to a destination. * @param {AudioNode} dest */ connect(dest) { this.output.connect(dest.input ? dest.input : dest) } /** * Disconnect the output. */ disconnect() { this.output.disconnect() } }
JavaScript
class UserMedia extends ToneAudioNode { constructor() { super(optionsFromArguments(UserMedia.getDefaults(), arguments, ["volume"])); this.name = "UserMedia"; const options = optionsFromArguments(UserMedia.getDefaults(), arguments, ["volume"]); this._volume = this.output = new Volume({ context: this.context, volume: options.volume, }); this.volume = this._volume.volume; readOnly(this, "volume"); this.mute = options.mute; } static getDefaults() { return Object.assign(ToneAudioNode.getDefaults(), { mute: false, volume: 0 }); } /** * Open the media stream. If a string is passed in, it is assumed * to be the label or id of the stream, if a number is passed in, * it is the input number of the stream. * @param labelOrId The label or id of the audio input media device. * With no argument, the default stream is opened. * @return The promise is resolved when the stream is open. */ open(labelOrId) { return __awaiter(this, void 0, void 0, function* () { assert(UserMedia.supported, "UserMedia is not supported"); // close the previous stream if (this.state === "started") { this.close(); } const devices = yield UserMedia.enumerateDevices(); if (isNumber(labelOrId)) { this._device = devices[labelOrId]; } else { this._device = devices.find((device) => { return device.label === labelOrId || device.deviceId === labelOrId; }); // didn't find a matching device if (!this._device && devices.length > 0) { this._device = devices[0]; } assert(isDefined(this._device), `No matching device ${labelOrId}`); } // do getUserMedia const constraints = { audio: { echoCancellation: false, sampleRate: this.context.sampleRate, noiseSuppression: false, mozNoiseSuppression: false, } }; if (this._device) { // @ts-ignore constraints.audio.deviceId = this._device.deviceId; } const stream = yield navigator.mediaDevices.getUserMedia(constraints); // start a new source only if the previous one is closed if (!this._stream) { this._stream = stream; // Wrap a MediaStreamSourceNode around the live input stream. const mediaStreamNode = this.context.createMediaStreamSource(stream); // Connect the MediaStreamSourceNode to a gate gain node connect(mediaStreamNode, this.output); this._mediaStream = mediaStreamNode; } return this; }); } /** * Close the media stream */ close() { if (this._stream && this._mediaStream) { this._stream.getAudioTracks().forEach((track) => { track.stop(); }); this._stream = undefined; // remove the old media stream this._mediaStream.disconnect(); this._mediaStream = undefined; } this._device = undefined; return this; } /** * Returns a promise which resolves with the list of audio input devices available. * @return The promise that is resolved with the devices * @example * Tone.UserMedia.enumerateDevices().then((devices) => { * // print the device labels * console.log(devices.map(device => device.label)); * }); */ static enumerateDevices() { return __awaiter(this, void 0, void 0, function* () { const allDevices = yield navigator.mediaDevices.enumerateDevices(); return allDevices.filter(device => { return device.kind === "audioinput"; }); }); } /** * Returns the playback state of the source, "started" when the microphone is open * and "stopped" when the mic is closed. */ get state() { return this._stream && this._stream.active ? "started" : "stopped"; } /** * Returns an identifier for the represented device that is * persisted across sessions. It is un-guessable by other applications and * unique to the origin of the calling application. It is reset when the * user clears cookies (for Private Browsing, a different identifier is * used that is not persisted across sessions). Returns undefined when the * device is not open. */ get deviceId() { if (this._device) { return this._device.deviceId; } else { return undefined; } } /** * Returns a group identifier. Two devices have the * same group identifier if they belong to the same physical device. * Returns null when the device is not open. */ get groupId() { if (this._device) { return this._device.groupId; } else { return undefined; } } /** * Returns a label describing this device (for example "Built-in Microphone"). * Returns undefined when the device is not open or label is not available * because of permissions. */ get label() { if (this._device) { return this._device.label; } else { return undefined; } } /** * Mute the output. * @example * const mic = new Tone.UserMedia(); * mic.open().then(() => { * // promise resolves when input is available * }); * // mute the output * mic.mute = true; */ get mute() { return this._volume.mute; } set mute(mute) { this._volume.mute = mute; } dispose() { super.dispose(); this.close(); this._volume.dispose(); this.volume.dispose(); return this; } /** * If getUserMedia is supported by the browser. */ static get supported() { return isDefined(navigator.mediaDevices) && isDefined(navigator.mediaDevices.getUserMedia); } }
JavaScript
class Logo extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.shadowRoot.appendChild(template.content.cloneNode(true)); } }
JavaScript
class SmartCursor { constructor(i = 0) { this.cursor = i; this.memorizedCursor = i; } jump(i) { check(i); this.cursor = i; this.memorizedCursor = i; return this; } skip(_field, nextPos = 1) { this.next(nextPos); return this; } diff(sync = true) { const memorized = this.cursor - this.memorizedCursor; if (sync) { this.jump(this.cursor); } return memorized; } memorize() { this.memorizedCursor = this.cursor; return this; } next(nextPos = 1) { check(nextPos); const clone = this.cursor; this.cursor += nextPos; return clone; } get memorized() { return this.memorizedCursor; } get cur() { return this.cursor; } }
JavaScript
class Nexus { server; /** * get header * @returns {{Accept: string, Referer, "X-nexus-ui": string}} */ getHeader() { return { Accept: 'application/json,application/vnd.siesta-error-v1+json,application/vnd.siesta-validation-errors-v1+json', Referer: this.server, 'X-nexus-ui': 'true' } } /** * login to nexus repository manager * @param username username * @param password password * @returns {Promise<void>} */ async login(username, password) { const url = `https://${(this.server)}/service/local/authentication/login` const header = { ...this.getHeader(), Authorization: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}` } const result = await axios.get(url, {headers: {...header}}) this.cookie = `NXSESSIONID=${cookie.parse(result.headers['set-cookie'][0]).NXSESSIONID}` } /** * get staging repositories * @returns {Promise<*>} */ async getStagingRepositories() { const url = `https://${(this.server)}/service/local/staging/profile_repositories` const header = { ...this.getHeader(), Cookie: this.cookie } const result = await axios.get(url, {headers: {...header}}) return result.data.data } /** * Close and wait * @param repositoryId repository id * @returns {Promise<void>} */ async closeAndWait(repositoryId) { //post close request const url = `https://${(this.server)}/service/local/staging/bulk/close` const data = { data: { description: '', stagedRepositoryIds: [repositoryId] } } const header = { ...this.getHeader(), 'Content-Type': 'application/json', Cookie: this.cookie } await axios.post(url, {data: {...data}}, {headers: {...header}}) //wait while (true) { await sleep(20000) const url = `https://${(this.server)}/service/local/staging/repository/${repositoryId}/activity` const header = { ...this.getHeader(), Cookie: this.cookie } const result = await axios.get(url, {headers: {...header}}) const closeEvents = result.data.filter((e) => e.name === 'close')[0].events const failEvents = closeEvents.filter((e) => e.name === 'ruleFailed') if (failEvents.length >= 1) { throw new Error('Nexus close failed:', JSON.stringify(failEvents)) } if (closeEvents[closeEvents.length - 1].name === 'repositoryClosed') { break } } } /** * Release staging repository and drop it * @param repositoryId repository id * @returns {Promise<void>} */ async releaseAndDrop(repositoryId) { const url = `https://${(this.server)}/service/local/staging/bulk/promote` const data = { autoDropAfterRelease: true, description: '', stagedRepositoryIds: [repositoryId] } const header = { ...this.getHeader(), 'Content-Type': 'application/json', Cookie: this.cookie } await axios.post(url, {data: {...data}}, {headers: {...header}}) } }
JavaScript
class ListItem extends React.Component { constructor() { super(); // youll see why later in the functions this.initialState = { // are we picked up? isActive: false, // is moved from initial pos (using the mouse as the reference) hasMoved: false, // initial MOUSE locations mInitX: 0, mInitY: 0, // mouse offset from initial locations mOffsetX: 0, mOffsetY: 0, } this.state = Object.assign( this.initialState, { isOutOfBounds: false, // should the item be removed threshold: 65, // threshold beyond which we are considered 'removed' } ); // dem func bindings for (let l of ['pickUp', 'letGo', 'drag']) { this[l] = this[l].bind(this); } } /* register and deregister mouse events, we don't want these around after an item has been 'let go' */ componentWillUpdate(nextProps, nextState) { if (nextState.isActive && !this.state.isActive) { // picked up return this.register('mousemove', this.drag).register('mouseup', this.letGo); } if (!nextState.isActive && this.state.isActive) { // let go return this.register('mousemove', this.drag, true).register('mouseup', this.letGo, true); } } /* we want the visual classes to update before kicking off the delete, so the logic waits till now */ componentDidUpdate(prevProps, prevState) { if (this.state.isOutOfBounds && !this.state.isActive) { return this.props.removeItem(this.props.id); } } /* short hand for adding and removing document event listeners + chainable bonus */ register(eventName, func, undo = false) { document[!undo ? 'addEventListener' : 'removeEventListener'](eventName, func); return this; } /* method to set the 'picked up' state of the element, aka 'selected' */ pickUp(e) { if (!this.isLeftMouse(e)) return false; this.setState({ isActive: true, mInitX: e.pageX, mInitY: e.pageY, }); this.silenceEvent(e); // quiet the mouse events to minimize collateral damage } /* method to 'let go' of the item */ letGo(e) { const newState = { isActive: false, hasMoved: false, } // if we're out of bounds, dont reset the position, otherwise do this.setState( (!this.state.isOutOfBounds) ? this.initialState : newState ); } /* function continuously called while an item is 'moving', see componentWillUpdate bindng */ drag(e) { const offset = e.pageX - this.state.mInitX; // calculate the distance we moved this.setState({ hasMoved: true, isOutOfBounds: (offset > this.state.threshold), mOffsetX: offset, }); } /* helper to minimize repetition, we don't want mouse events doing anything while picked up */ silenceEvent(e) { e.stopPropagation(); e.preventDefault(); } /* helper to ignore the right mouse click when picking up */ isLeftMouse(e) { if ('buttons' in e) { return e.buttons === 1; } else if ('which' in e) { return e.which === 1; } else { return e.button === 1; } } /* returns a 'style' object for the distance offset. ORDER IS IMPORTANT */ getElemPixelPos() { let pos = '0px'; if (this.state.isOutOfBounds || this.state.hasMoved && this.state.isActive && this.state.mOffsetX > 0) { pos = this.state.mOffsetX + 'px'; } return { left: pos, }; } /* // @TODO optimize this, no need to keep re-assigning abstract out class compilation to nt pollute the render */ getElemClasses() { let stateClasses = ''; if (this.state.isActive) { stateClasses = stateClasses + ' is-active'; } if (this.state.hasMoved) { stateClasses = stateClasses + ' is-moving'; } if (this.state.isOutOfBounds) { stateClasses = stateClasses + ' state-deleting'; } return 'item-zone' + stateClasses; } /* you know the deal */ render() { return ( <div className={this.getElemClasses()}> <div className="item" isPickedUp={this.state.isSelected} onMouseDown={this.pickUp} style={ this.getElemPixelPos() } > <span> {this.props.title} </span> </div> <div className="delete-overlay"> <span className="delete"> <svg className="skull-icon" width="48" height="48" viewBox="0 0 48 48" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink"> <defs> <path d="M40.567 32.208A19.907 19.907 0 0 0 44 21C44 9.954 35.046 1 24 1S4 9.954 4 21c0 4.153 1.266 8.011 3.433 11.208A4.487 4.487 0 0 0 6 35.5c0 2.48 2.015 4.5 4.5 4.5h2.728l.859 7h19.826l.86-7H37.5c2.48 0 4.5-2.015 4.5-4.5a4.49 4.49 0 0 0-1.433-3.292z" id="a"/> <mask id="b" x="0" y="0" width="40" height="46" fill="#fff"> <use xlinkHref="#a"/> </mask> </defs> <g fill="none" fill-rule="evenodd"> <use stroke="#BC4155" mask="url(#b)" stroke-width="6" xlinkHref="#a"/> <path d="M17 30a5 5 0 1 0 0-10 5 5 0 0 0 0 10zm14 0a5 5 0 1 0 0-10 5 5 0 0 0 0 10zm-9.527 2.99c.051-.546.537-.99 1.093-.99.552 0 .958.451.907.99l-.38 4.02c-.051.546-.537.99-1.093.99a.894.894 0 0 1-.907-.99l.38-4.02zm3 4.02c.051.546.537.99 1.093.99a.894.894 0 0 0 .907-.99l-.38-4.02A1.115 1.115 0 0 0 25 32a.894.894 0 0 0-.907.99l.38 4.02z" fill="#BC4155"/> </g> </svg> </span> </div> {/*<DevPanel values={this.state} />*/} </div> ); } }
JavaScript
class List extends React.Component { constructor() { super(); this.state = { items: ['Click and drag to delete', 'Pick Me!', 'This One', 'Pick the other guys'].map( i => ({ id: uuid.v4(), title: i, })), } // dem func bindings for (let f of ['removeOne', 'addOne']) { this[f] = this[f].bind(this); } } addOne() { this.setState({ items: [...this.state.items, { id: uuid.v4(), title: 'Haven\'t had enough huh...' }] }) } removeOne(id) { this.setState({ items: this.state.items.filter( i => i.id !== id ), }); } render() { return ( <div className="list"> <div className="list-inner"> <header className="list-header"> <h3>My List</h3> <button className="btn-add-one" onClick={this.addOne}>Add Item</button> </header> <ul className="list-items"> <ReactCSSTransitionGroup transitionName="drag" transitionEnter={false} transitionLeaveTimeout={330}> { this.state.items.map( (v, k) => ( <ListItem key={v.id} {...v} removeItem={this.removeOne} /> )) } </ ReactCSSTransitionGroup> </ul> </div> <div className="shadow"></div> </div> ) } }
JavaScript
class ASTBundle { constructor() { this.asts = {}; this.nodesByKey = new Map(); this.sources = {}; } /** * Clones, adds, and indexes the given AST. * The following fields are added to each AST node method: * - a `biASTId` string field * - a `biKey` string field containing the result of `toNodeKey` * - a `codeSlice` string field * @param {string} astId * @param {Node} ast - root babel node of the AST * @param {string} code - the source code corresponding to the AST */ add(astId, ast, code) { ast = cloneDeep(ast); // eslint-disable-line no-param-reassign traverseAST(ast, (node) => { if (!node.biId) { return; } node.biASTId = astId; // eslint-disable-line no-param-reassign node.biKey = toNodeKey(astId, node.biId); // eslint-disable-line no-param-reassign this.nodesByKey.set(node.biKey, node); }); attachCodeSlicesToAST(ast, code); this.asts[astId] = ast; this.sources[astId] = code; } /** * Retrieve the specified node from the specified AST. * @param {string} astId * @param {number} nodeId * @returns {Node|undefined} */ getNode(astId, nodeId) { return this.nodesByKey.get(toNodeKey(astId, nodeId)); } /** * Retrieve the specified node using its composite key. * @param {*} nodeKey * @returns {Node|undefined} */ getNodeByKey(nodeKey) { return this.nodesByKey.get(nodeKey); } /** * Retrieve all nodes for which a given function returns true. * @param {function} filterFn takes a node and returns true if it should be included in the output * @returns {Node[]} all matching nodes */ filterNodes(filterFn) { const results = []; Object.keys(this.asts).forEach((astId) => { traverseAST(this.asts[astId], (node) => { if (filterFn(node)) { results.push(node); } }); }); return results; } /** * @returns {Object} a representation of this ASTBundle that can be serialized as JSON * and later deserialized and loaded using fromJSON */ asJSON() { const asts = {}; Object.keys(this.asts).forEach((key) => { asts[key] = cloneDeep(this.asts[key]); traverseAST(asts[key], (node) => { delete node.biASTId; // eslint-disable-line no-param-reassign delete node.biKey; // eslint-disable-line no-param-reassign delete node.codeSlice; // eslint-disable-line no-param-reassign }); }); return { asts, sources: this.sources, }; } /** * Restores an instance that was saved using asJSON() * @param {Object} input * @returns {ASTBundle} */ static fromJSON(input) { if (!input.asts || !input.sources) { throw new Error('Expected `asts` and `sources` fields'); } const astb = new ASTBundle(); Object.keys(input.asts).forEach((key) => { astb.add(key, input.asts[key], input.sources[key]); }); return astb; } }
JavaScript
class OuterTransferable extends JSTransferable { constructor() { super(); // Create a detached MessagePort at this.inner const c = new MessageChannel(); this.inner = c.port1; c.port2.postMessage(this.inner, [ this.inner ]); } [kTransferList] = common.mustCall(() => { return [ this.inner ]; }); [kTransfer] = common.mustCall(() => { return { data: { inner: this.inner }, deserializeInfo: 'does-not:matter' }; }); }
JavaScript
class Menu { // creates the menu at the provided position constructor(x, y) { this.x = x; this.y = y; // spacing between the elements this.spacing = 5; // flag whether the menu is hidded atm this.hidden = false; // start y pos let elemY = y; // a parent div containing all menu elements this.parentDiv = createDiv(''); this.parentDiv.style('color', '#ffffffff'); // Label for Speed input field this.speedInputLabel = createDiv("Speed:"); this.speedInputLabel.position(x, elemY); this.speedInputLabel.parent(this.parentDiv); elemY += this.distToNextY(this.speedInputLabel); // speed input field this.speedInput = createInput(speed, 'number'); this.speedInput.position(x, elemY); this.speedInput.parent(this.parentDiv); this.speedInput.changed(value => speed = value.srcElement.valueAsNumber); elemY += this.distToNextY(this.speedInput); // Label for distance scale value input field this.distScaleInputLabel = createDiv("Distance Scale:"); this.distScaleInputLabel.position(x, elemY); this.distScaleInputLabel.parent(this.parentDiv); elemY += this.distToNextY(this.distScaleInputLabel); // distance scale Input field this.distScaleInput = createInput(distScale, 'number'); this.distScaleInput.position(x, elemY); this.distScaleInput.parent(this.parentDiv); this.distScaleInput.changed(value => distScale = value.srcElement.valueAsNumber); elemY += this.distToNextY(this.distScaleInput); // Label for color offset value input field this.colorOffsetInputLabel = createDiv("Color Offset:"); this.colorOffsetInputLabel.position(x, elemY); this.colorOffsetInputLabel.parent(this.parentDiv); elemY += this.distToNextY(this.colorOffsetInputLabel); // color offset Input field this.colorOffsetInput = createInput(colorOffset, 'number'); this.colorOffsetInput.position(x, elemY); this.colorOffsetInput.parent(this.parentDiv); this.colorOffsetInput.changed(value => colorOffset = value.srcElement.valueAsNumber); elemY += this.distToNextY(this.colorOffsetInput); // Label for max radius value input field this.maxRInputLabel = createDiv("Max Radius:"); this.maxRInputLabel.position(x, elemY); this.maxRInputLabel.parent(this.parentDiv); elemY += this.distToNextY(this.maxRInputLabel); // max radius Input field this.maxRInput = createInput(maxRadius, 'number'); this.maxRInput.position(x, elemY); this.maxRInput.parent(this.parentDiv); this.maxRInput.changed(value => maxRadius = value.srcElement.valueAsNumber); elemY += this.distToNextY(this.maxRInput); // Button to clear the field this.clearFieldButton = createButton("Clear"); this.clearFieldButton.position(x, elemY); this.clearFieldButton.parent(this.parentDiv); this.clearFieldButton.mouseClicked(clearField); } // gets the difference to the next y position distToNextY(element) { return element.size().height + this.spacing; } toggle() { if (this.hidden) { this.parentDiv.show(); } else { this.parentDiv.hide(); } this.hidden = !this.hidden; } }
JavaScript
class IApiResponse { /** * Constructs a new <code>IApiResponse</code>. * @alias module:model/IApiResponse * @class * @param responseCode {Number} * @param type {module:model/IApiResponse.TypeEnum} * @param message {String} */ constructor(responseCode, type, message) { this['responseCode'] = responseCode;this['type'] = type;this['message'] = message; } /** * Constructs a <code>IApiResponse</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/IApiResponse} obj Optional instance to populate. * @return {module:model/IApiResponse} The populated <code>IApiResponse</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new IApiResponse(); if (data.hasOwnProperty('responseCode')) { obj['responseCode'] = ApiClient.convertToType(data['responseCode'], 'Number'); } if (data.hasOwnProperty('type')) { obj['type'] = ApiClient.convertToType(data['type'], 'String'); } if (data.hasOwnProperty('message')) { obj['message'] = ApiClient.convertToType(data['message'], 'String'); } if (data.hasOwnProperty('debugMessage')) { obj['debugMessage'] = ApiClient.convertToType(data['debugMessage'], 'String'); } } return obj; } /** * @member {Number} responseCode */ responseCode = undefined; /** * @member {module:model/IApiResponse.TypeEnum} type */ type = undefined; /** * @member {String} message */ message = undefined; /** * @member {String} debugMessage */ debugMessage = undefined; /** * Allowed values for the <code>type</code> property. * @enum {String} * @readonly */ static TypeEnum = { /** * value: "ERROR" * @const */ "ERROR": "ERROR", /** * value: "SUCCESS" * @const */ "SUCCESS": "SUCCESS" }; }
JavaScript
class Batcher extends Plugins.interfaces.Processor { constructor() { super(); this._buffer = []; this._size = 100; } /** * @inheritDoc */ set configuration(configuration) { this._size = configuration.size || 100; this._interval = configuration.interval || 0; } /** * @inheritDoc */ process(events, done) { for (let event of events) { this._buffer.push(event); if (this._buffer.length >= this._size) { if (this._timeout) { clearTimeout(this._timeout); delete this._timeout; } done(this._buffer); this._buffer = []; } } if (this._interval && !this._timeout) { this._timeout = setTimeout(() => { done(this._buffer); this._buffer = []; }, this._interval); } } }
JavaScript
class TableElement extends api.core.Instance { static get instanceClassName () { return 'TableElement'; } init () { this.listen('scroll', this.scroll.bind(this)); this.content = this.querySelector('tbody'); this.isResizing = true; } get isScrolling () { return this._isScrolling; } set isScrolling (value) { if (this._isScrolling === value) return; this._isScrolling = value; if (value) { this.addClass(TableSelector.SHADOW); this.scroll(); } else { this.removeClass(TableSelector.SHADOW); this.removeClass(TableSelector.SHADOW_LEFT); this.removeClass(TableSelector.SHADOW_RIGHT); } } /* ajoute la classe fr-table__shadow-left ou fr-table__shadow-right sur fr-table en fonction d'une valeur de scroll et du sens (right, left) */ scroll () { const isMin = this.node.scrollLeft <= SCROLL_OFFSET; const max = this.content.offsetWidth - this.node.offsetWidth - SCROLL_OFFSET; const isMax = Math.abs(this.node.scrollLeft) >= max; const isRtl = document.documentElement.getAttribute('dir') === 'rtl'; const minSelector = isRtl ? TableSelector.SHADOW_RIGHT : TableSelector.SHADOW_LEFT; const maxSelector = isRtl ? TableSelector.SHADOW_LEFT : TableSelector.SHADOW_RIGHT; if (isMin) { this.removeClass(minSelector); } else { this.addClass(minSelector); } if (isMax) { this.removeClass(maxSelector); } else { this.addClass(maxSelector); } } resize () { this.isScrolling = this.content.offsetWidth > this.node.offsetWidth; } dispose () { this.isScrolling = false; } }
JavaScript
class SubmitButton extends Component { render() { return ( <button cy-data="submitButton" id="submitButton" type="submit">Submit</button> ) } }
JavaScript
class DefaultHeader extends Component { constructor(props){ super(props) this.updateSearchResults = this.props.updateSearchResults.bind(this) } isLoggedIn(){ return localStorage.getItem('session_id') && localStorage.getItem('session_id') !== 'undefined'; } onHeaderSearchFocused(){ this.displaySearchResults() } initAutoComplete(e){ let searchTerm = e.target.value var s = [] s.push(e.target) // fire query only by 2 caracs if(searchTerm.length > 0 && searchTerm.length%2 == 0){ let wc = commons.getWorkingContainerId() searchService .searchContainerMemberByLoginLike(searchTerm, wc) .then(response => { if(response && response.data && response.data.length > 0) { setAutocompleteData(s[0], response.data) } else { noAutoCompleteData(s[0]) } }) } else if(searchTerm.length == 0){ closeAllLists(); } } render() { var json = localStorage.getItem('workingContainer'), wc = JSON.parse(json), container = wc.name, isAdmin = commons.isAdministrator() var adminMenu = '' if(isAdmin){ adminMenu = ( <NavItem className="px-3"> <NavLink to="/appVersionHistory" className="nav-link" >Manager</NavLink> </NavItem> ) } return ( <React.Fragment> <AppNavbarBrand className="d-lg-down-none navbrand-jsoagger-logo" full={{ src: logo, width: 180, height: 55, alt: 'JSOAGGER Logo' }} minimized={{ src: logo, width: 30, height: 30, alt: 'JSOAGGER Logo' }}/> <Nav className="d-md-down-none" navbar> <NavItem className="px-3"/> <div className="autocomplete"> <input className="myautocompleteInput__1" type="text" name="myCountry" onChange={e => this.initAutoComplete(e)} autocomplete="off" placeholder="Search for ..."/> </div> </Nav> <Nav className="ml-auto" navbar> <NavItem className="px-3"> <NavLink to="#" className="btn btn-danger" ><i className="fa fa-plus fa-md"></i> New item</NavLink> </NavItem> <NavItem className="px-3"> <NavLink to="/c/home" className="nav-link" >Home</NavLink> </NavItem> {adminMenu} <NavItem className="jsoagger-container-location"> <NavLink to="/c/switchContainers" className="nav-link"> <i className="jsoagger-header-logo"></i> <span><strong>{container}</strong></span> </NavLink> </NavItem> <UserMenu /> </Nav> </React.Fragment> ); } }